'use client'

import { useCallback, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { X, AlertCircle, Plus, Download } from 'lucide-react'
import { normalizeDate } from '@/utils'
import { directorSchema, DirectorFormValues } from '@/schema/director'
import {
  Form,
  FormSection,
  FormField,
  FormLabel,
  FormInput,
  FormSelect,
  FormTextarea,
  FormDatePicker,
  FormMonthYearPicker,
  FormCheckbox,
  // FormCheckbox,
} from '@/components/ui/form'
import { DirectorData } from '@/types'
import Button from '@/components/ui/buttons/Button'
import Modal from '@/components/ui/modal/Modal'
import ModalHeader from '@/components/ui/modal/ModalHeader'
import ModalFooter from '@/components/ui/modal/ModalFooter'
import ModalBody from '@/components/ui/modal/ModalBody'
import { NATIONALITIES, YEARS } from '@/constants'
import { showError, showSuccess } from '@/components/ui/Toast'
import { directorService } from '@/services/director.document.service'
import { useStateContext } from '@/context/StateContext'
import { useParams } from 'next/navigation'
import { FormFileDropzone } from '@/components/ui/form/FormFileDropzone'


export const EMPTY_DIRECTOR: DirectorData = {
  name: '', gender: '', dob: '', email: '', mobile: '', address: '',
  nationality: 'Indian', aadharNumber: '', panNumber: '', panValidity: '',
  passportNumber: '', passportValidity: '', designationRoc: '', dinNumber: '',
  dinValidity: '', shareholdingPercent: '0', qualification: '', briefProfile: '',
  netWorth: '', isGuarantor: false, personalGuarantee: '', otherDirectorships: '',
  itr: '', computation: '', year: '', aadharFront: '', aadharBack: '',
  passportDocument: '', dinDocument: '',
  panDocument: '',photo:'',fatherName:'',motherName:''
}
const FILE_FIELDS = ['aadharFront', 'aadharBack', 'panDocument', 'passportDocument', 'dinDocument', 'itr', 'computation'] as const

interface Props {
  initial?: DirectorData
  onClose: () => void
  title?: string
}


export default function DirectorForm({ initial = EMPTY_DIRECTOR, onClose, title = 'Add Director' }: Props) {
  const [globalError, setGlobalError] = useState<string>('')
  const { recordID, setRefresh, refresh } = useStateContext();
  const [showItr, setShowItr] = useState(false);
  const clientId = useParams().clientId as string;


  const form = useForm<DirectorFormValues>({
    resolver: zodResolver(directorSchema),
    defaultValues: {
      ...initial,
      dob: normalizeDate(initial.dob) || '',
    }
  })

  const fetchDirector = useCallback(async (id: string) => {
    const res = await directorService.getOne(clientId, id);
    return res.data.data;
  }, []);

  const setFormData = useCallback((data: any) => {
    const str = (v: any) => v ?? ''
    form.reset({
      name: str(data.name),
      fatherName:str(data.fatherName),
      motherName:str(data.motherName),
      dob: normalizeDate(data.dob) ?? '',
      gender: str(data.gender),
      email: str(data.email),
      mobile: str(data.mobile),
      address: str(data.address),
      nationality: str(data.nationality),
      aadharNumber: str(data.aadharNumber),
      aadharFront: str(data.aadharFront),
      photo: str(data.photo),
      aadharBack: str(data.aadharBack),
      panNumber: str(data.panNumber),
      panDocument: str(data.panDocument),
      passportNumber: str(data.passportNumber),
      passportValidity: str(data.passportValidity),
      passportDocument: str(data.passportDocument),
      dinNumber: str(data.dinNumber),
      dinValidity: str(data.dinValidity),
      dinDocument: str(data.dinDocument),
      designationRoc: str(data.designationRoc),
      qualification: str(data.qualification),
      shareholdingPercent: data.shareholdingPercent ?? '0',
      briefProfile: str(data.briefProfile),
      netWorth: str(data.netWorth),
      isGuarantor: data.isGuarantor ?? false,
      personalGuarantee: str(data.personalGuarantee),
      otherDirectorships: str(data.otherDirectorships),
      itr: str(data.itr),
      computation: str(data.computation),
      year: str(data.year),
    })
  }, [form.reset])


  useEffect(() => {
    if (recordID) {
      fetchDirector(recordID)
        .then(setFormData)
        .catch(err => {
          console.error(err);
          showError("Failed to load director");
        });
    } else {
      form.reset({ ...EMPTY_DIRECTOR, dob: '' });
    }
  }, [recordID, fetchDirector, setFormData, form]);


  const dobValue = form.watch('dob')
  const age = dobValue
    ? Math.floor((Date.now() - new Date(dobValue).getTime()) / (1000 * 60 * 60 * 24 * 365.25))
    : null

  async function onSubmit(data: DirectorFormValues) {
    setGlobalError('')
    try {
      const formData = new FormData()
      Object.entries(data).forEach(([key, value]) => {
        if (value === undefined || value === null) return
        if (FILE_FIELDS.includes(key as any)) {
          if (value instanceof FileList && value.length > 0) {
            formData.append(key, value[0])
          } else if (typeof value === 'string' && value) {
            formData.append(key, value)
          }
        } else {
          formData.append(key, String(value))
        }
      })
      if (recordID) {
        await directorService.update(clientId, recordID, formData)
        showSuccess('Director updated successfully')
      } else {
        await directorService.create(clientId, formData)
        showSuccess('Director added successfully')
      }
      onClose()
    } catch (err: any) {
      setGlobalError(err?.message || 'Failed to save')
    } finally {
      setRefresh(!refresh);
    }
  }

  return (
    <Modal
      isOpen={true}
      onClose={onClose}
    >
      <ModalHeader title={title || 'Add Director'} subtitle='Add new director details' onClose={onClose} />
      <ModalBody>
        <Form form={form} onSubmit={onSubmit} className="space-y-7">
          <FormSection title="Personal Details">
            <FormField colSpan={2}>
              <FormLabel required>Full Name</FormLabel>
              <FormInput name="name" placeholder="Vikram Sethi" />
            </FormField>
             <FormField colSpan={1}>
              {/* <FormLabel hint="Photo">Photo</FormLabel> */}
              <FormFileDropzone label="Photo" name="photo" accept=".png,.jpg,.jpeg" />
            </FormField>
            <FormField colSpan={1}>
              <FormLabel required>Father Name</FormLabel>
              <FormInput name="fatherName" placeholder="Vikas Sethi" />
            </FormField>
            <FormField colSpan={1}>
              <FormLabel required>Mother Name</FormLabel>
              <FormInput name="motherName" placeholder="Ankita Sethi" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required hint="Photo on left — label shows guarantor/SBO">Gender</FormLabel>
              <FormSelect name="gender" options={['Male', 'Female', 'Other']} />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required hint={'Age auto-calculated'}>Date of Birth</FormLabel>
              <FormDatePicker name="dob" placeholder="Select date" maxDate={new Date().toISOString().split('T')[0]} />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>Age</FormLabel>
              <FormInput name="age" placeholder="Enter DOB" disabled value={age || ''} />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>Email</FormLabel>
              <FormInput name="email" type="email" placeholder="vikram@aarna.com" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required hint="With country code">Mobile Number</FormLabel>
              <FormInput name="mobile" placeholder="+91 98765 43210" />
            </FormField>

            <FormField colSpan={2}>
              <FormLabel>Address</FormLabel>
              <FormTextarea name="address" rows={2} placeholder="Residential address" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel>Nationality</FormLabel>
              <FormSelect name="nationality" options={NATIONALITIES} />
            </FormField>
          </FormSection>
          <FormSection title="Identity Documents">
            <FormField colSpan={1}>
              <FormLabel hint="12 digit">Aadhar Number</FormLabel>
              <FormInput name="aadharNumber" placeholder="1234 5678 9012" />
            </FormField>

            <FormField colSpan={1}>
              {/* <FormLabel hint="Adhar Front">Adhar Front</FormLabel> */}
              <FormFileDropzone label="Adhar Front" name="aadharFront" accept=".pdf,.doc,.docx" />
            </FormField>
            <FormField colSpan={1}>
              {/* <FormLabel hint="Adhar Back">Adhar Back</FormLabel> */}
              <FormFileDropzone label="Adhar Back" name="aadharBack" accept=".pdf,.doc,.docx" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel>PAN Number</FormLabel>
              <FormInput name="panNumber" placeholder="ABCDE1234F" />
            </FormField>
            <FormField colSpan={1}>
              {/* <FormLabel hint="PAN Document">PAN Document</FormLabel> */}
              <FormFileDropzone label="PAN Document" name="panDocument" accept=".pdf,.doc,.docx" />
            </FormField>


            <FormField colSpan={1}>
              <FormLabel>Passport Number</FormLabel>
              <FormInput name="passportNumber" placeholder="A1234567" />
            </FormField>

            <FormField colSpan={1}>
              {/* <FormLabel hint="Passport Document">Passport Document</FormLabel> */}
              <FormFileDropzone label="Passport Document" name="passportDocument" accept=".pdf,.doc,.docx" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel>Passport Valid Till</FormLabel>
              <FormMonthYearPicker name="passportValidity" placeholder="MM/YYYY" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel hint="Number and validity date">DIN Number</FormLabel>
              <FormInput name="dinNumber" placeholder="01234567" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel>DIN Validity</FormLabel>
              <FormMonthYearPicker name="dinValidity" placeholder="MM/YYYY" />
            </FormField>
          </FormSection>
          <FormSection title="Role & Shareholding">
            <FormField colSpan={1}>
              <FormLabel hint="Max 100 chars">Designation as per ROC</FormLabel>
              <FormInput name="designationRoc" placeholder="Managing Director" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel hint="Percentage">% Shareholding</FormLabel>
              <FormInput name="shareholdingPercent" type="number" placeholder="25.50" />
            </FormField>

            <FormField colSpan={2}>
              <FormLabel hint="Education qualifications">Qualification</FormLabel>
              <FormInput name="qualification" placeholder="MBA, IIM Ahmedabad" />
            </FormField>

            <FormField colSpan={2}>
              <FormLabel>Brief Profile & Role</FormLabel>
              <FormTextarea name="briefProfile" rows={2} placeholder="A few lines about profile and role" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel hint="With certificate">Net Worth (₹ Cr)</FormLabel>
              <FormInput name="netWorth" placeholder="45" />
            </FormField>
          </FormSection>
          <FormSection title="Guarantee & Other">
            <FormField colSpan={2}>
              <FormLabel>Personal Guarantee Details</FormLabel>
              <FormTextarea name="personalGuarantee" rows={2} placeholder="Whether Personal Guarantor for debt taken in name of Company…" />
            </FormField>

            <FormField colSpan={2}>
              <FormLabel>Other Directorships</FormLabel>
              <FormTextarea name="otherDirectorships" rows={2} placeholder="Company name, designation, role and stake held if any…" />
            </FormField>

            <FormField colSpan={2}>
              <FormCheckbox name="isGuarantor" label="Mark as Personal Guarantor / Significant Beneficial Owner" />
            </FormField>

            <FormField colSpan={2} className="flex gap-2 items-center justify-start">
              <Button type='button' name="Add ITR & Computation" variant="outline" size="sm" icon={Plus} onClick={() => setShowItr(!showItr)} />
              <Button type='button' name="Download Sample ITR & Computation" variant="outline" size="sm" icon={Download} />
            </FormField>

            {showItr && (

              <>
                <FormField colSpan={1}>
                  <FormLabel>Year</FormLabel>
                  <FormSelect name="year" options={YEARS} />
                </FormField>
                <FormField colSpan={1}>
                  {/* <FormLabel>ITR</FormLabel> */}
                  <FormFileDropzone label="ITR" name="itr" accept=".pdf" />
                </FormField>
                <FormField colSpan={1}>
                  {/* <FormLabel>Computation</FormLabel> */}
                  <FormFileDropzone label="Computation" name="computation" accept=".pdf" />
                </FormField>
              </>

            )}
          </FormSection>
        </Form>
      </ModalBody>
      <ModalFooter
        globalError={globalError}
        saving={form.formState.isSubmitting}
        onClose={onClose}
        onSubmit={form.handleSubmit(onSubmit)}
      />
    </Modal>
  )
}
