'use client'

import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { Plus, Trash2 } from 'lucide-react'
import { Property } from '@/types'
import { propertySchema, PropertyFormValues } from '@/schema/property'
import {
  Form,
  FormSection,
  FormField,
  FormLabel,
  FormInput,
  FormSelect,
  FormTextarea,
  FormDatePicker,
  FormFileUpload,
  FormRadioGroup,
} from '@/components/ui/form'
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 { FormFileDropzone } from '@/components/ui/form/FormFileDropzone'

// Bank entry interface
interface BankEntry {
  bankName: string
  loanAmount: string
  document: string
}

export const EMPTY_PROPERTY: Property = {
  id: '',
  propertyAddress: '',
  addressDocument: '',
  ownedBy: '',
  propertyType: 'freehold',
  valuationAmount: '',
  valuationDocument: '',
  basisOfValuation: '',
  basisOfValuationDocument: '',
  basisOfValuationDate: '',
  titleSearchReport: '',
  titleSearchDate: '',
  titleSearchReportDocument: '',
  mortgagedBanks: [],
  securityDetails: '',
  typeOfCharge: 'exclusive',
  additionalDoc1: '',
  additionalDoc2: '',
  cersaiRegistered: false,
  rocChargeFiled: false,
}

const CHARGE_TYPES = ['1ST PARI PASSU', '2ND PARI PASSU', 'HYPOTHECATION']

interface Props {
  initial?: Property
  onSave: (data: Property) => Promise<void>
  onClose: () => void
  title?: string
}

export default function AssetPropertiesForm({
  initial = EMPTY_PROPERTY,
  onSave,
  onClose,
  title = 'Add Property',

}: Props) {
  const [globalError, setGlobalError] = useState<string>('')
  const [saving, setSaving] = useState(false)
  const [bankEntries, setBankEntries] = useState<BankEntry[]>([
    { bankName: '', loanAmount: '', document: '' }
  ])

  const form = useForm<PropertyFormValues>({
    resolver: zodResolver(propertySchema),
    defaultValues: {
      ...initial,
      propertyType: initial?.propertyType || 'freehold',
      typeOfCharge: initial?.typeOfCharge || 'exclusive',
    },
  })

  const handleAddBank = () => {
    setBankEntries([...bankEntries, { bankName: '', loanAmount: '', document: '' }])
  }

  const handleRemoveBank = (index: number) => {
    if (bankEntries.length > 1) {
      setBankEntries(bankEntries.filter((_, i) => i !== index))
    }
  }

  const handleBankChange = (index: number, field: keyof BankEntry, value: string) => {
    const updated = [...bankEntries]
    updated[index][field] = value
    setBankEntries(updated)
  }

  async function onSubmit(data: PropertyFormValues) {
    setSaving(true)
    setGlobalError('')
    try {
      const submitData: Property = {
        ...data,
        mortgagedBanks: bankEntries.filter(b => b.bankName || b.loanAmount),
        typeOfCharge: data.typeOfCharge || 'exclusive',
      } as Property

      await onSave(submitData)
    } catch (err: unknown) {
      setGlobalError(err instanceof Error ? err.message : 'Failed to save.')
      setSaving(false)
    }
  }

  return (
    <Modal isOpen={true} onClose={onClose}>
      <ModalHeader title={title || 'Add Property'} subtitle='Add immovable property details' onClose={onClose} />
    <ModalBody>
  <Form form={form} onSubmit={onSubmit} className='space-y-7'>
    
    {/* 1. Property Details Section */}
    <FormSection title='Property Details'>
      <FormField colSpan={2}>
        <FormLabel required>Address of Property</FormLabel>
        <FormTextarea
          name='propertyAddress'
          rows={2}
          placeholder='Enter full location / address of the property'
        />
      </FormField>

      <FormField colSpan={2}>
        <FormLabel required>Upload Address Document</FormLabel>
        <FormFileUpload name='addressDocument' />
      </FormField>

      <FormField colSpan={1}>
        <FormLabel required>Owned by</FormLabel>
        <FormInput name='ownedBy' placeholder='Max 100 characters' maxLength={100} />
      </FormField>

      <FormField colSpan={1}>
        <FormLabel required>Property Type</FormLabel>
        {/* Freehold/Leasehold Radio Buttons/Option Box */}
        <FormRadioGroup
          name='propertyType' 
          direction='horizontal'
          options={[
            { label: 'Freehold', value: 'freehold' },
            { label: 'Leasehold', value: 'leasehold' }
          ]} 
        />
      </FormField>
    </FormSection>

    {/* 2. Valuation Details Section */}
    <FormSection title='Valuation Details'>
      <FormField colSpan={1}>
        <FormLabel required>Valuation (Amount in Cr)</FormLabel>
        <FormInput type='number' name='valuationAmount' placeholder='0.00' />
      </FormField>

      <FormField colSpan={1}>
   
        <FormFileDropzone
                name="valuationDocument"
                label="Valuation Document"
                accept=".pdf"
                maxSize={50}
              />

      </FormField>

      <FormField colSpan={1}>
        <FormLabel required>Basis of Valuation</FormLabel>
        <FormInput name='basisOfValuation' placeholder='Enter basis of valuation' />
      </FormField>

      <FormField colSpan={1}>
        <FormLabel required>Basis of Valuation Document</FormLabel>
        <FormFileUpload name='basisOfValuationDocument' />
      </FormField>

      <FormField colSpan={2}>
        <FormLabel>Basis of Valuation Date</FormLabel>
        <FormDatePicker name='basisOfValuationDate' placeholder='Select date' />
      </FormField>
    </FormSection>

    {/* 3. Legal & Title Search Report Section */}
    <FormSection title='Legal Compliance'>
      <FormField colSpan={1}>
        <FormLabel required>Title Search Report</FormLabel>
        <FormInput name='titleSearchReport' placeholder='Enter report details' />
      </FormField>

      <FormField colSpan={1}>
        <FormLabel required>Date</FormLabel>
        <FormDatePicker name='titleSearchDate' placeholder='Select report date' />
      </FormField>

      <FormField colSpan={2}>
        <FormLabel required>Title Search Report Document</FormLabel>
        <FormFileUpload name='titleSearchReportDocument' />
      </FormField>
    </FormSection>

    {/* 4. Bank Mortgage & Charge Details Section */}
    <FormSection title='Mortgage & Bank Charges'>
      <div className="col-span-2">
        <div className="flex items-center justify-between mb-4">
          <label className="text-[10px] font-semibold uppercase tracking-widest text-gray-500">
            Mortgaged Banks
            <span className="text-red-500">*</span>
            <span className="normal-case font-normal tracking-normal ml-1.5 text-gray-400">— add bank details</span>
          </label>
          <button
            type="button"
            onClick={handleAddBank}
            className="flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium text-slate-600 hover:text-slate-900 hover:bg-slate-50 rounded-lg transition-colors border border-slate-200"
          >
            <Plus className="w-3.5 h-3.5" />
            Add Bank
          </button>
        </div>

        {/* Bank entries table/rows */}
        <div className="space-y-2 border border-gray-200 rounded-lg p-3 bg-gray-50">
          <div className="grid grid-cols-[2fr_1.5fr_1fr_auto] gap-2 text-[10px] font-semibold uppercase tracking-widest text-gray-400 pb-2 border-b border-gray-200">
            <div>Bank Name</div>
            <div>Loan Amount (₹ Cr)</div>
            <div>Document</div>
            <div></div>
          </div>
          
          {/* Bank rows - dynamic */}
          {bankEntries.map((entry, index) => (
            <div key={index} className="grid grid-cols-[2fr_1.5fr_1fr_auto] gap-2 items-start">
              <input
                type="text"
                placeholder="Bank of India"
                value={entry.bankName}
                onChange={(e) => handleBankChange(index, 'bankName', e.target.value)}
                className="w-full px-2.5 py-2 text-xs border rounded-lg bg-white placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-slate-800 transition-all border-gray-200"
              />
              <input
                type="number"
                placeholder="5.5"
                value={entry.loanAmount}
                onChange={(e) => handleBankChange(index, 'loanAmount', e.target.value)}
                className="w-full px-2.5 py-2 text-xs border rounded-lg bg-white placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-slate-800 transition-all border-gray-200"
              />
              <div className="text-xs">
                <label className="block text-xs text-gray-600 mb-1 cursor-pointer">
                  <input
                    type="file"
                    onChange={(e) => handleBankChange(index, 'document', e.target.files?.[0]?.name || '')}
                    className="block w-full text-xs text-gray-700 file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-xs file:font-semibold file:bg-slate-800 file:text-white hover:file:bg-slate-700 cursor-pointer"
                  />
                </label>
                {entry.document && <p className="text-[10px] text-gray-600">{entry.document}</p>}
              </div>
              <button
                type="button"
                onClick={() => handleRemoveBank(index)}
                disabled={bankEntries.length === 1}
                className="w-7 h-7 flex items-center justify-center rounded-lg text-gray-400 hover:text-red-500 hover:bg-red-50 transition-colors disabled:opacity-0 disabled:pointer-events-none mt-0.5"
              >
                <Trash2 className="w-3.5 h-3.5" />
              </button>
            </div>
          ))}
        </div>
      </div>

      <FormField colSpan={2}>
        <FormLabel>Is security perfected with existing Bank/s</FormLabel>
        <FormTextarea 
          name='securityDetails' 
          rows={3} 
          placeholder='Mention the details of the Bank/s' 
        />
      </FormField>

      <FormField colSpan={2}>
        <FormLabel required>Type of Charge</FormLabel>
        <FormSelect 
          name='typeOfCharge' 
          options={[
            { label: 'Exclusive', value: 'exclusive' },
            { label: '1st Pari Passu', value: '1st_pari_passu' },
            { label: '2nd Pari Passu', value: '2nd_pari_passu' },
            { label: 'Hypothecation', value: 'hypothecation' }
          ]} 
        />
      </FormField>
    </FormSection>

    {/* 5. Additional Documents Section */}
    <FormSection title='Additional Documents'>
      <FormField colSpan={1}>
        <FormLabel>Document 1 Name</FormLabel>
        <FormFileUpload name='additionalDoc1' />
      </FormField>

      <FormField colSpan={1}>
        <FormLabel>Document 2 Name</FormLabel>
        <FormFileUpload name='additionalDoc2' />
      </FormField>
    </FormSection>

  </Form>
</ModalBody>
      <ModalFooter
        globalError={globalError}
        saving={saving}
        onClose={onClose}
        onSubmit={form.handleSubmit(onSubmit)}
      />
    </Modal>
  )
}
