import { useState } from 'react'
import { validateEmail, validatePassword, validatePhone } from '@/lib/validation'
import { PhoneInput } from '@/components/PhoneInput'

// Админский / API endpoint — переключается через PUBLIC_APP_URL на этапе
// билда. Дефолт — admin.food-market.kz (там и API и админ-SPA).
const APP_URL = (import.meta.env.PUBLIC_APP_URL as string | undefined) ?? 'https://admin.food-market.kz'
const API_URL = APP_URL

interface Props {
  defaultPlan?: string
  defaultShops?: number
  defaultCashes?: number
  defaultWarehouses?: number
}

type FieldErrors = Partial<Record<'email' | 'password' | 'orgName' | 'phone' | 'agree', string>>

export default function SignupForm({ defaultPlan = 'start' }: Props) {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [orgName, setOrgName] = useState('')
  const [phone, setPhone] = useState('')
  const [plan, setPlan] = useState(defaultPlan)
  const [agree, setAgree] = useState(false)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({})

  const validate = (): FieldErrors => {
    const e: FieldErrors = {}
    const em = validateEmail(email);    if (em) e.email = em
    const pw = validatePassword(password); if (pw) e.password = pw
    if (!orgName.trim()) e.orgName = 'Название магазина обязательно для заполнения'
    const ph = validatePhone(phone);    if (ph) e.phone = ph
    if (!agree) e.agree = 'Подтвердите согласие с офертой и политикой ПДн'
    return e
  }

  const submit = async (ev: React.FormEvent) => {
    ev.preventDefault()
    const errs = validate()
    setFieldErrors(errs)
    if (Object.keys(errs).length) return
    setError(null); setBusy(true)
    try {
      const res = await fetch(`${API_URL}/api/auth/signup`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password, organizationName: orgName, phone: phone || null, plan }),
      })
      if (!res.ok) {
        const j = await res.json().catch(() => ({}))
        throw new Error(j.error ?? `HTTP ${res.status}`)
      }
      const tokRes = await fetch(`${API_URL}/connect/token`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          grant_type: 'password', username: email, password,
          client_id: 'food-market-web',
          scope: 'openid profile email roles api offline_access',
        }),
      })
      if (!tokRes.ok) throw new Error('Регистрация прошла, но токен не выпущен. Войдите вручную.')
      const tok = await tokRes.json() as { access_token: string; refresh_token: string }
      const url = `${APP_URL}/auth-bridge#access=${encodeURIComponent(tok.access_token)}&refresh=${encodeURIComponent(tok.refresh_token)}&welcome=1`
      window.location.assign(url)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Ошибка регистрации')
    } finally { setBusy(false) }
  }

  const inputCls = (hasError: boolean) =>
    `w-full h-10 rounded-md border px-3 text-sm focus:outline-none focus:ring-2 ${
      hasError ? 'border-red-400 focus:ring-red-300' : 'border-slate-300 focus:ring-brand'
    }`

  return (
    <form onSubmit={submit} noValidate className="space-y-4">
      {error && (
        <div className="p-3 rounded-md bg-red-50 text-red-700 text-sm border border-red-200">{error}</div>
      )}
      <Field label="Email" error={fieldErrors.email}>
        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
          autoComplete="email" placeholder="name@example.kz" className={inputCls(!!fieldErrors.email)} />
      </Field>
      <Field label="Пароль" hint="Минимум 8 символов, цифра и заглавная." error={fieldErrors.password}>
        <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
          autoComplete="new-password" className={inputCls(!!fieldErrors.password)} />
      </Field>
      <Field label="Название магазина" error={fieldErrors.orgName}>
        <input type="text" value={orgName} onChange={(e) => setOrgName(e.target.value)}
          placeholder="Наименование организации" className={inputCls(!!fieldErrors.orgName)} />
      </Field>
      <Field label="Телефон" error={fieldErrors.phone}>
        <PhoneInput value={phone} onChange={setPhone} required className={inputCls(!!fieldErrors.phone)} />
      </Field>
      <div>
        <div className="text-sm font-medium mb-2">Тариф</div>
        <div className="grid grid-cols-3 gap-2">
          {[
            { id: 'start', name: 'Старт', price: '5 000 ₸' },
            { id: 'business', name: 'Бизнес', price: 'от 10 000 ₸' },
            { id: 'network', name: 'Сеть', price: 'по запросу' },
          ].map((p) => (
            <label key={p.id} className={`p-2.5 rounded-md border cursor-pointer text-center text-sm ${plan === p.id ? 'border-brand bg-brand/5' : 'border-slate-200'}`}>
              <input type="radio" name="plan" className="hidden" checked={plan === p.id} onChange={() => setPlan(p.id)} />
              <div className="font-semibold">{p.name}</div>
              <div className="text-xs text-slate-500">{p.price}</div>
            </label>
          ))}
        </div>
      </div>
      <div>
        <label className="flex items-start gap-2 text-sm">
          <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} className="mt-1" />
          <span>Я согласен с <a href="/legal/offer" className="text-brand underline">офертой</a> и <a href="/legal/privacy" className="text-brand underline">политикой обработки ПДн</a>.</span>
        </label>
        {fieldErrors.agree && <p className="text-xs text-red-600 mt-1">{fieldErrors.agree}</p>}
      </div>
      <button type="submit" disabled={busy} className="w-full px-4 py-3 bg-brand text-white font-semibold rounded-md hover:bg-[#009305] disabled:opacity-60">
        {busy ? 'Регистрация…' : 'Начать бесплатно (90 дней)'}
      </button>
      <p className="text-xs text-center text-slate-500">Уже есть аккаунт? <a href={`${APP_URL}/login`} className="text-brand underline">Войти</a></p>
    </form>
  )
}

function Field({ label, hint, error, children }: { label: string; hint?: string; error?: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className="text-sm font-medium block mb-1.5">{label}</span>
      {children}
      {error && <span className="text-xs text-red-600 block mt-1">{error}</span>}
      {!error && hint && <span className="text-xs text-slate-500 block mt-1">{hint}</span>}
    </label>
  )
}
