'use client'

import { useState, useEffect, useRef } from 'react'
import { Upload, Download, AlertCircle, Loader2, Plus, Trash2 } from 'lucide-react'
import SearchableSelect from '@/components/ui/SearchableSelect'
import Modal from '@/components/ui/modal/Modal'

import { useForm, useFieldArray, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'


import {
  Form,
  FormSection,
  FormField,
  FormLabel,
  FormInput,
  FormSelect,
  FormTextarea,
  FormDatePicker,
  FormMonthYearPicker,
  FormFileInput,
} from '@/components/ui/form'

import { getApiError } from '@/libs/api'
import { industryService } from '@/services/industry.service'
import { clientService } from '@/services/client.service'
import { ClientData } from '@/types'
import { clientParseGst, clientParsePlants, downloadTemplate, emptyToUndefined, normalizeDate } from '@/utils'
import { CONSTITUTION_OPTIONS, GST_STATE_CODES, TEMPLATE_EXAMPLE, TEMPLATE_HEADERS, UDHYAM_CLASSES } from '@/constants'
import { ClientFormValues, clientSchema } from '@/schema/client'
import ModalFooter from '../ui/modal/ModalFooter'
import Button from '../ui/buttons/Button'
import ModalHeader from '../ui/modal/ModalHeader'
import ModalBody from '../ui/modal/ModalBody'

interface SubIndustry { id: number; name: string }
interface Industry { id: number; name: string; subIndustries: SubIndustry[] }

interface Props {
  client?: ClientData | null
  onClose: () => void
  onSaved?: () => void
}

type Mode = 'manual' | 'import'

export default function ClientModal({ client, onClose, onSaved }: Props) {
  const isEdit = !!client
  const [mode, setMode] = useState<Mode>('manual')
  const [apiError, setApiError] = useState<string>('')
  const [industries, setIndustries] = useState<Industry[]>([])
  const [loadingInd, setLoadingInd] = useState(true)
  const [citySuggestions, setCitySugg] = useState<string[]>([])
  const [stateSuggestions, setStateSugg] = useState<string[]>([])
  const [importFile, setImportFile] = useState<File | null>(null)
  const [importError, setImportError] = useState('')
  const fileRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    industryService.getAll()
      .then(r => setIndustries(Array.isArray(r.data) ? r.data : []))
      .catch(() => setIndustries([]))
      .finally(() => setLoadingInd(false))
    clientService.getSuggestions()
      .then(r => { setCitySugg(r.data.cities ?? []); setStateSugg(r.data.states ?? []) })
      .catch(() => { })
  }, [])

  const form = useForm<ClientFormValues>({
    resolver: zodResolver(clientSchema(isEdit)),
    defaultValues: {
      isEdit,
      legalName: client?.legalName || '',
      shortName: client?.shortName || '',
      constitution: client?.constitution || '',
      cin: client?.cin || '',
      pan: client?.pan || '',
      pfNumber: client?.pfNumber || '',
      esicNumber: client?.esicNumber || '',
      iecCode: client?.iecCode || '',
      udhyamNumber: client?.udhyamNumber || '',
      udhyamValidTill: client?.udhyamValidTill || '',
      udhyamClass: client?.udhyamClass || '',
      leiNumber: client?.leiNumber || '',
      leiValidTill: client?.leiValidTill || '',
      cinDocument: undefined,
      panDocument: undefined,
      leiDocument: undefined,
      moaAoAPartnershipDeed: undefined,
      businessVintage: client?.businessVintage || '',
      gstEntries: clientParseGst(client?.gstNumber),
      incorporationDate: client?.incorporationDate ? normalizeDate(client.incorporationDate) : '',
      registeredOffice: client?.registeredOffice || '',
      plantEntries: clientParsePlants(client?.plantLocations) ?? [],
      city: client?.city || '',
      state: client?.state || '',
      website: client?.website || '',
      turnover: client?.turnover != null ? String(client.turnover) : '',
      turnoverFY: client?.turnoverFY || '',
      employees: client?.employees != null ? String(client.employees) : '',
      employeesRole: client?.employeesRole != null ? String(client.employeesRole) : '',
      employeesContract: client?.employeesContract != null ? String(client.employeesContract) : '',
      industryId: client?.industry?.id ? String(client.industry.id) : '',
      subIndustryId: client?.subIndustry?.id ? String(client.subIndustry.id) : '',
    }
  })

  const { watch, setValue, control, formState: { isSubmitting, errors } } = form
  const { fields: gstFields, append: appendGst, remove: removeGst } = useFieldArray({
    control,
    name: "gstEntries"
  })

  const { fields: plantFields, append: appendPlant, remove: removePlant } = useFieldArray({
    control,
    name: "plantEntries"
  })
  const selectedInd = watch('industryId')
  const subOptions = industries.find(i => String(i.id) === selectedInd)?.subIndustries ?? []
  const incDate = watch('incorporationDate')
  const vintage = incDate ? Math.floor((Date.now() - new Date(incDate).getTime()) / (1000 * 60 * 60 * 24 * 365.25)) : null
  const UPPER_FIELDS = ['pan', 'cin', 'iecCode', 'udhyamNumber', 'leiNumber']

  useEffect(() => {
    const subscription = watch((value, { name, type }) => {
      if (name && UPPER_FIELDS.includes(name) && value[name as keyof ClientFormValues]) {
        const currentVal = value[name as keyof ClientFormValues] as string
        if (currentVal !== currentVal.toUpperCase()) {
          setValue(name as keyof ClientFormValues, currentVal.toUpperCase(), { shouldValidate: true })
        }
      }
    })
    return () => subscription.unsubscribe()
  }, [watch, setValue])

  const buildFormData = (data: ClientFormValues, payload: Record<string, unknown>): FormData => {
    const fd = new FormData()
    for (const [key, val] of Object.entries(payload)) {
      if (val != null) fd.append(key, String(val))
    }
    const FILE_FIELDS: (keyof ClientFormValues)[] = ['cinDocument', 'panDocument', 'leiDocument', 'moaAoAPartnershipDeed']
    for (const field of FILE_FIELDS) {
      const val = data[field] as FileList | undefined
      if (val && val.length > 0) fd.append(field as string, val[0])
    }
    const gstins: string[] = []
    for (let i = 0; i < data.gstEntries.length; i++) {
      const cert = (data.gstEntries[i] as { gstCertificate?: FileList }).gstCertificate
      if (cert && cert.length > 0) {
        fd.append('gstCertificate', cert[0])
        gstins.push(data.gstEntries[i].gstin)
      }
    }
    for (const gstin of gstins) fd.append('gstCertificateGstin', gstin)
    return fd
  }

  const onSubmit = async (data: ClientFormValues) => {
    setApiError('')
    try {
      const payload: Record<string, unknown> = {
        legalName: data.legalName,
        shortName: data.shortName,
        constitution: data.constitution,
        cin: emptyToUndefined(data.cin),
        pan: data.pan,
        pfNumber: emptyToUndefined(data.pfNumber),
        esicNumber: emptyToUndefined(data.esicNumber),
        iecCode: emptyToUndefined(data.iecCode),
        udhyamNumber: emptyToUndefined(data.udhyamNumber),
        udhyamValidTill: emptyToUndefined(data.udhyamValidTill),
        udhyamClass: emptyToUndefined(data.udhyamClass),
        leiNumber: emptyToUndefined(data.leiNumber),
        leiValidTill: emptyToUndefined(data.leiValidTill),
        businessVintage: emptyToUndefined(data.businessVintage),
        gstNumber: JSON.stringify(data.gstEntries.map(({ gstCertificate, ...g }) => g)),
        incorporationDate: data.incorporationDate,
        registeredOffice: data.registeredOffice,
        plantLocations: isEdit
          ? JSON.stringify(data.plantEntries)
          : data.plantEntries?.map(p => p.name).filter(Boolean).join('; ') || null,
        city: emptyToUndefined(data.city),
        state: emptyToUndefined(data.state),
        website: emptyToUndefined(data.website),
        turnover: data.turnover,
        turnoverFY: emptyToUndefined(data.turnoverFY),
        employees: data.employees,
        employeesRole: data.employeesRole ? parseInt(data.employeesRole as string) : undefined,
        employeesContract: data.employeesContract ? parseInt(data.employeesContract as string) : undefined,
        industryId: emptyToUndefined(data.industryId),
        subIndustryId: emptyToUndefined(data.subIndustryId),
      }

      const fd = buildFormData(data, payload)

      if (isEdit) {
        await clientService.update(client!.slug, fd)
        onSaved?.()
      } else {
        await clientService.create(fd)
        onClose()
      }
    } catch (err) {
      setApiError(getApiError(err))
    }
  }

  const handleImport = async () => {
    if (!importFile) { setImportError('Please select a file.'); return }
    setTimeout(() => { onClose() }, 800)
  }

  return (
    <Modal
      maxWidth='max-w-5xl'
      onClose={onClose}
    >
      <ModalHeader title={isEdit ? 'Edit Client' : 'Add Client'} subtitle={isEdit ? client?.legalName : ''} onClose={onClose} />
      <ModalBody>

        {mode === 'manual' ? (
          <Form form={form} onSubmit={onSubmit} id="client-form" className="space-y-7">
            {/* Basic Identity */}
            <FormSection title="Basic Identity">
              <FormField colSpan={2}>
                <FormLabel required>Company Name</FormLabel>
                <FormInput name="legalName" placeholder="Aarna Industries Pvt Ltd" />
              </FormField>
              <FormField>
                <FormLabel required>Short Name</FormLabel>
                <FormInput name="shortName" placeholder="Aarna Industries" />
              </FormField>
              <FormField>
                <FormLabel required>Classification</FormLabel>
                <FormSelect name="constitution" options={CONSTITUTION_OPTIONS} />
              </FormField>
            </FormSection>

            {/* Registration Numbers */}
            <FormSection title="Registration Numbers">
              <FormField>
                <FormLabel required>CIN Number</FormLabel>
                <FormInput name="cin" placeholder="U28920MH2010PTC203456" className="font-mono uppercase" />
              </FormField>
              <FormField>
                <FormLabel required>CIN Document</FormLabel>
                <FormFileInput name="cinDocument" />
              </FormField>
              <FormField>
                <FormLabel required>PAN Number</FormLabel>
                <FormInput name="pan" placeholder="AABCA1234P" className="font-mono uppercase" />
              </FormField>
              <FormField>
                <FormLabel required>PAN Document</FormLabel>
                <FormFileInput name="panDocument" />
              </FormField>

              <FormField>
                <FormLabel>Business Vintage</FormLabel>
                <FormInput name="businessVintage" placeholder="Enter Number of years" />
              </FormField>
              <div />
              <FormField>
                <FormInput name="pfNumber" placeholder="MH/BAN/0012345" className="font-mono uppercase" />
              </FormField>
              <FormField>
                <FormLabel>ESIC Number</FormLabel>
                <FormInput name="esicNumber" placeholder="31000000000000001" className="font-mono uppercase" />
              </FormField>
              <FormField>
                <FormLabel>IEC Code</FormLabel>
                <FormInput name="iecCode" placeholder="AABCA1234" className="font-mono uppercase" />
              </FormField>
              <FormField>
                <FormLabel>Udhyam Registration</FormLabel>
                <FormInput name="udhyamNumber" placeholder="UDYAM-MH-02-0112345" className="font-mono uppercase" />
              </FormField>

              <FormField>
                <FormLabel>Udhyam Valid Till</FormLabel>
                <FormMonthYearPicker name="udhyamValidTill" />
              </FormField>

              {isEdit ? (
                <FormField>
                  <FormLabel hint="Micro / Small / Medium">Udhyam Classification</FormLabel>
                  <FormSelect name="udhyamClass" options={UDHYAM_CLASSES} />
                </FormField>
              ) : <div />}

              <FormField>
                <FormLabel>LEI Number</FormLabel>
                <FormInput name="leiNumber" placeholder="5493001KJTIIGC8Y1R12" className="font-mono uppercase" />
              </FormField>
              <FormField>
                <FormLabel>LEI Valid Till</FormLabel>
                <FormMonthYearPicker name="leiValidTill" />
              </FormField>
              <FormField>
                <FormLabel>LEI Document</FormLabel>
                <FormFileInput name="leiDocument" />
              </FormField>

              <FormField>
                <FormLabel>MOA & AOA/ Partnership Deed</FormLabel>
                <FormFileInput name="moaAoAPartnershipDeed" />
              </FormField>



              {/* GST Entries */}
              <div className="col-span-2 mt-1">
                <div className="flex items-center justify-between mb-2">
                  <FormLabel required hint="state auto-detected">GST Registrations</FormLabel>
                  <button type="button" onClick={() => appendGst({ gstin: '', state: '', regDate: '' })}
                    className="flex items-center gap-1 text-[10px] font-semibold text-slate-700 hover:text-slate-900 px-2 py-1 rounded-lg hover:bg-slate-100 transition-colors">
                    <Plus className="w-3 h-3" /> Add State
                  </button>
                </div>
                {errors.gstEntries?.root && <p className="text-[10px] text-red-500 mb-2">{errors.gstEntries.root.message}</p>}
                <div className="border border-gray-200 rounded-xl overflow-hidden">
                  <div className="bg-gray-50 px-3 py-2 space-y-2">
                    {gstFields.map((field, index) => (
                      <div key={field.id} className="grid grid-cols-[1.5fr_1.4fr_1fr_auto_auto] gap-2 items-start">
                        <div>
                          {index === 0 && <FormLabel required>GSTIN</FormLabel>}
                          <FormInput
                            name={`gstEntries.${index}.gstin` as const}
                            placeholder="27AABCA1234P1Z5"
                            className="font-mono uppercase text-xs"
                            onChange={e => {
                              const val = e.target.value.toUpperCase()
                              setValue(`gstEntries.${index}.gstin`, val, { shouldValidate: true })
                              if (val.length >= 2) {
                                const detected = GST_STATE_CODES[val.slice(0, 2)]
                                if (detected) setValue(`gstEntries.${index}.state`, detected, { shouldValidate: true })
                              } else if (!val) {
                                setValue(`gstEntries.${index}.state`, '', { shouldValidate: true })
                              }
                            }}
                          />
                        </div>

                        <div>
                          {index === 0 && <FormLabel><span className="normal-case">State (auto)</span></FormLabel>}
                          <FormInput
                            name={`gstEntries.${index}.state` as const}
                            placeholder="Auto from GSTIN"
                            className={`text-xs ${watch(`gstEntries.${index}.state`) && !errors.gstEntries?.[index]?.state ? 'text-emerald-700 font-semibold bg-emerald-50 border-emerald-200' : ''}`}
                          />
                        </div>
                        <div className='flex-shrink-1'>
                          {index === 0 && <FormLabel required>Registration Date</FormLabel>}
                          <FormDatePicker
                            name={`gstEntries.${index}.regDate` as const}
                            placeholder="Select date"
                            maxDate={new Date().toISOString().split('T')[0]}
                          />
                        </div>
                        <div>
                          {index === 0 && <FormLabel> GST Certificate</FormLabel>}
                          <FormFileInput name={`gstEntries.${index}.gstCertificate` as const} />
                        </div>
                        <div className={index === 0 ? 'pt-5' : ''}>
                          <button type="button" onClick={() => removeGst(index)} disabled={gstFields.length <= 1}
                            className="w-7 h-7 flex items-center justify-center rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors disabled:opacity-0 disabled:pointer-events-none">
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </FormSection>

            {/* Dates */}
            <FormSection title="Dates">
              <FormField>
                <FormLabel required>Incorporation Date</FormLabel>
                <FormDatePicker name="incorporationDate" placeholder="Select date" maxDate={new Date().toISOString().split('T')[0]} />
              </FormField>
              <FormField>
                <FormLabel hint="Auto calculated">Vintage (Years)</FormLabel>
                <div className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg bg-gray-50 text-gray-500">
                  {vintage !== null ? `${vintage} yr${vintage !== 1 ? 's' : ''}` : '—'}
                </div>
              </FormField>
            </FormSection>

            {/* Address */}
            <FormSection title="Address & Locations">
              <FormField colSpan={2}>
                <FormLabel required>Registered Office</FormLabel>
                <FormTextarea name="registeredOffice" rows={2} placeholder="Plot 45, MIDC Industrial Area..." />
              </FormField>

              {isEdit ? (
                <div className="col-span-2">
                  <div className="flex items-center justify-between mb-2">
                    <FormLabel>Plant Locations</FormLabel>
                    <button type="button" onClick={() => appendPlant({ name: '', address: '' })}
                      className="flex items-center gap-1 text-[10px] font-semibold text-slate-700 hover:text-slate-900 px-2 py-1 rounded-lg hover:bg-slate-100 transition-colors">
                      <Plus className="w-3 h-3" /> Add Location
                    </button>
                  </div>
                  {plantFields.length === 0 ? (
                    <p className="text-xs text-gray-400 py-2">No plant locations added.</p>
                  ) : (
                    <div className="space-y-2">
                      {plantFields.map((field, i) => (
                        <div key={field.id} className="grid grid-cols-[1fr_1.5fr_auto] gap-2 items-start">
                          <FormInput name={`plantEntries.${i}.name` as const} placeholder="Name / Unit No." className="text-xs" />
                          <FormInput name={`plantEntries.${i}.address` as const} placeholder="Address" className="text-xs" />
                          <button type="button" onClick={() => removePlant(i)} className="w-7 h-7 flex items-center justify-center rounded-lg text-muted-foreground hover:text-red-500 hover:bg-red-50 transition-colors">
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ) : (
                <FormField colSpan={2}>
                  <FormLabel hint="Multiple plants semicolon separated">Plant Locations</FormLabel>
                  <FormTextarea name="plantEntries.0.name" rows={2} placeholder="Location 1; Location 2" />
                </FormField>
              )}

              <div className="relative">
                <FormField>
                  <FormLabel>City</FormLabel>
                  <FormInput name="city" list="city-suggestions" placeholder="Mumbai" />
                </FormField>
                <datalist id="city-suggestions">{citySuggestions.map(c => <option key={c} value={c} />)}</datalist>
              </div>

              <div className="relative">
                <FormField>
                  <FormLabel>State</FormLabel>
                  <FormInput name="state" list="state-suggestions" placeholder="Maharashtra" />
                </FormField>
                <datalist id="state-suggestions">{stateSuggestions.map(s => <option key={s} value={s} />)}</datalist>
              </div>
            </FormSection>

            {/* Business Details */}
            <FormSection title="Business Details">
              <FormField>
                <FormLabel>Website Link</FormLabel>
                <FormInput name="website" type="url" placeholder="https://www.company.com" />
              </FormField>
              <div className="col-span-1" /> {/* Spacer */}

              <FormField>
                <FormLabel required>Annual Turnover (₹ Cr)</FormLabel>
                <FormInput name="turnover" type="number" placeholder="182" />
              </FormField>

              {isEdit ? (
                <FormField>
                  <FormLabel hint="e.g. FY 2023-24">Turnover as on FY</FormLabel>
                  <FormInput name="turnoverFY" placeholder="FY 2023-24" />
                </FormField>
              ) : (
                <FormField>
                  <FormLabel required>Employees</FormLabel>
                  <FormInput name="employees" type="number" placeholder="620" />
                </FormField>
              )}

              {isEdit && (
                <>
                  <FormField>
                    <FormLabel>On-Role Employees</FormLabel>
                    <FormInput name="employeesRole" type="number" placeholder="500" />
                  </FormField>
                  <FormField>
                    <FormLabel>Contractual Employees</FormLabel>
                    <FormInput name="employeesContract" type="number" placeholder="120" />
                  </FormField>
                </>
              )}

              {loadingInd ? (
                <div className="col-span-2 flex items-center gap-2 text-xs text-gray-400"><Loader2 className="w-3.5 h-3.5 animate-spin" /> Loading industries…</div>
              ) : (
                <>
                  <FormField>
                    <FormLabel>Industry</FormLabel>
                    <Controller name="industryId" control={control} render={({ field }) => (
                      <SearchableSelect label="" placeholder="Select industry…" value={field.value ?? ''} onChange={v => { field.onChange(v); setValue('subIndustryId', '') }} options={industries.map(i => ({ value: String(i.id), label: i.name }))} />
                    )} />
                  </FormField>
                  <FormField>
                    <FormLabel>Sub-Industry</FormLabel>
                    <Controller name="subIndustryId" control={control} render={({ field }) => (
                      <SearchableSelect label="" placeholder={selectedInd ? 'Select sub-industry…' : 'Select industry first'} value={field.value ?? ''} onChange={field.onChange} options={subOptions.map((s) => ({ value: String(s.id), label: s.name }))} disabled={!selectedInd || subOptions.length === 0} />
                    )} />
                  </FormField>
                </>
              )}
            </FormSection>
          </Form>
        ) : (
          <div className="space-y-4">
            <div className="bg-gray-50 border border-gray-100 rounded-xl p-4">
              <p className="text-xs font-semibold text-gray-700 mb-2">Template columns</p>
              <div className="flex flex-wrap gap-1.5">
                {TEMPLATE_HEADERS.map(h => (
                  <span key={h} className={`text-[10px] px-2 py-0.5 rounded-full border font-medium ${h.includes('*') ? 'bg-red-50 border-red-200 text-red-700' : 'bg-gray-100 border-gray-200 text-gray-600'}`}>
                    {h.replace('*', '')}
                  </span>
                ))}
              </div>
              <p className="text-[10px] text-gray-500 mt-2">GST format: <span className="font-mono text-slate-700">Maharashtra:27AABCA1234P1Z5:01/07/2017 | Gujarat:24AABCA1234P1Z9:15/03/2019</span></p>
            </div>
            <div className="flex items-center justify-between p-4 bg-blue-50 border border-blue-100 rounded-xl">
              <div>
                <p className="text-sm font-semibold text-blue-900">Download Template</p>
                <p className="text-xs text-blue-600 mt-0.5">Pre-filled example row included.</p>
              </div>
              <button onClick={downloadTemplate} className="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-blue-200 rounded-lg text-xs font-semibold text-blue-700 hover:bg-blue-50 transition-colors">
                <Download className="w-3.5 h-3.5" /> Download (.csv)
              </button>
            </div>
            <div onClick={() => fileRef.current?.click()} className="border-2 border-dashed border-gray-200 rounded-xl p-8 text-center cursor-pointer hover:border-gray-300 hover:bg-gray-50 transition-all">
              <Upload className="w-8 h-8 text-muted-foreground mx-auto mb-2" />
              {importFile ? <p className="text-sm font-semibold text-gray-700">{importFile.name}</p> : <><p className="text-sm font-semibold text-gray-600">Click to upload CSV / Excel</p><p className="text-xs text-gray-400 mt-1">.csv or .xlsx — max 5MB</p></>}
              <input ref={fileRef} type="file" accept=".csv,.xlsx,.xls" className="hidden" onChange={e => { setImportFile(e.target.files?.[0] ?? null); setImportError('') }} />
            </div>
            {importError && (
              <div className="flex items-center gap-2 text-xs text-red-600 bg-red-50 border border-red-100 rounded-lg px-3 py-2">
                <AlertCircle className="w-3.5 h-3.5 flex-shrink-0" /> {importError}
              </div>
            )}
          </div>
        )}
      </ModalBody>
      <ModalFooter
        globalError={apiError}
      >
        <>
          <Button variant="outline" onClick={onClose} >
            Cancel
          </Button>
          {mode === 'manual' ? (
            <Button type="submit" form="client-form" disabled={isSubmitting}>
              {isSubmitting ? 'Saving…' : isEdit ? 'Save Changes' : 'Save Client'}
            </Button>
          ) : (
            <Button type="button" onClick={handleImport} disabled={isSubmitting}>
              {isSubmitting ? 'Importing…' : 'Import Clients'}
            </Button>
          )}
        </>
      </ModalFooter>
    </Modal>
  )
}
