import { useEffect } from 'react'
import { useNavigate, useParams, Link } from 'react-router-dom'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { clientsApi } from '../../api'
import { ArrowLeftIcon } from '@heroicons/react/24/outline'
import toast from 'react-hot-toast'

const schema = z.object({
  full_name:               z.string().min(2, 'Name required'),
  phone:                   z.string().min(6, 'Phone required'),
  email:                   z.string().email().optional().or(z.literal('')),
  gender:                  z.string().optional(),
  date_of_birth:           z.string().optional(),
  address:                 z.string().optional(),
  nid_passport:            z.string().optional(),
  emergency_contact_name:  z.string().optional(),
  emergency_contact_phone: z.string().optional(),
  referred_by:             z.string().optional(),
  notes:                   z.string().optional(),
})
type FormData = z.infer<typeof schema>

export default function ClientFormPage() {
  const { id } = useParams()
  const isEdit = Boolean(id)
  const navigate = useNavigate()
  const qc = useQueryClient()

  const { data: client, isLoading } = useQuery({
    queryKey: ['client', id],
    queryFn: () => clientsApi.get(Number(id)).then(r => r.data.data),
    enabled: isEdit,
  })

  const { register, handleSubmit, reset, formState: { errors, isDirty } } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: { gender: '', full_name: '', phone: '', email: '' },
  })

  useEffect(() => {
    if (client) reset({
      full_name: client.full_name ?? '', phone: client.phone ?? '',
      email: client.email ?? '', gender: client.gender ?? '',
      date_of_birth: client.date_of_birth ?? '', address: client.address ?? '',
      nid_passport: client.nid_passport ?? '',
      emergency_contact_name: client.emergency_contact_name ?? '',
      emergency_contact_phone: client.emergency_contact_phone ?? '',
      referred_by: client.referred_by ?? '', notes: client.notes ?? '',
    })
  }, [client, reset])

  const mutation = useMutation({
    mutationFn: (data: FormData) => isEdit ? clientsApi.update(Number(id), data) : clientsApi.create(data),
    onSuccess: (res) => {
      qc.invalidateQueries({ queryKey: ['clients'] })
      if (isEdit) qc.invalidateQueries({ queryKey: ['client', id] })
      toast.success(isEdit ? 'Client updated.' : 'Client created.')
      navigate(isEdit ? `/clients/${id}` : `/clients/${res.data.data.id}`)
    },
    onError: (err: any) => {
      const errs = err.response?.data?.errors
      if (errs) Object.values(errs).flat().forEach((m: any) => toast.error(String(m)))
    },
  })

  if (isEdit && isLoading) return <div className="text-slate-400 text-center py-20">Loading…</div>

  const Field = ({ label, required, children, error }: any) => (
    <div>
      <label className="label">{label}{required && <span className="text-red-400 ml-1">*</span>}</label>
      {children}
      {error && <p className="text-red-400 text-xs mt-1">{error}</p>}
    </div>
  )

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div className="flex items-center gap-3">
        <Link to={isEdit ? `/clients/${id}` : '/clients'} className="p-2 text-slate-400 hover:text-white hover:bg-slate-700 rounded-lg transition-colors">
          <ArrowLeftIcon className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-white">{isEdit ? 'Edit Client' : 'Add New Client'}</h1>
          <p className="text-slate-400 text-sm">{isEdit ? `Editing: ${client?.full_name}` : 'Register a new gym member'}</p>
        </div>
      </div>

      <form onSubmit={handleSubmit((d) => mutation.mutate(d))} className="space-y-5">
        <div className="card space-y-4">
          <h2 className="font-semibold text-white border-b border-slate-700 pb-3">Basic Information</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Field label="Full Name" required error={errors.full_name?.message}>
              <input {...register('full_name')} className="input" placeholder="John Doe" />
            </Field>
            <Field label="Phone" required error={errors.phone?.message}>
              <input {...register('phone')} className="input" placeholder="01700000000" />
            </Field>
            <Field label="Email" error={errors.email?.message}>
              <input {...register('email')} type="email" className="input" placeholder="john@example.com" />
            </Field>
            <Field label="Gender">
              <select {...register('gender')} className="input">
                <option value="">Select gender</option>
                <option value="male">Male</option>
                <option value="female">Female</option>
                <option value="other">Other</option>
              </select>
            </Field>
            <Field label="Date of Birth">
              <input {...register('date_of_birth')} type="date" className="input" />
            </Field>
            <Field label="NID / Passport">
              <input {...register('nid_passport')} className="input" placeholder="NID or Passport number" />
            </Field>
          </div>
          <Field label="Address">
            <textarea {...register('address')} className="input h-20 resize-none" placeholder="Full address" />
          </Field>
        </div>

        <div className="card space-y-4">
          <h2 className="font-semibold text-white border-b border-slate-700 pb-3">Emergency Contact</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Field label="Contact Name">
              <input {...register('emergency_contact_name')} className="input" placeholder="Contact person name" />
            </Field>
            <Field label="Contact Phone">
              <input {...register('emergency_contact_phone')} className="input" placeholder="Contact phone" />
            </Field>
          </div>
        </div>

        <div className="card space-y-4">
          <h2 className="font-semibold text-white border-b border-slate-700 pb-3">Additional</h2>
          <Field label="Referred By">
            <input {...register('referred_by')} className="input" placeholder="Name or source" />
          </Field>
          <Field label="Internal Notes">
            <textarea {...register('notes')} className="input h-24 resize-none" placeholder="Staff notes…" />
          </Field>
        </div>

        <div className="flex gap-3 justify-end">
          <Link to={isEdit ? `/clients/${id}` : '/clients'} className="btn-secondary">Cancel</Link>
          <button type="submit" disabled={mutation.isPending || (isEdit && !isDirty)} className="btn-primary">
            {mutation.isPending ? 'Saving…' : isEdit ? 'Save Changes' : 'Create Client'}
          </button>
        </div>
      </form>
    </div>
  )
}
