"use client";

import { useState, useEffect } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import ModalFooter from "@/components/ui/modal/ModalFooter";
import ModalBody from "@/components/ui/modal/ModalBody";
import ModalHeader from "@/components/ui/modal/ModalHeader";
import Modal from "@/components/ui/modal/Modal";
import { Form, FormField, FormLabel, FormSection, FormSelect, FormInput, FormTextarea, FormFileInput, FormMonthYearPicker, FormDatePicker } from "@/components/ui/form";
import { useForm as useFormHook } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { guarantorSchema, GuarantorFormValues } from "@/schema/Guarantor";
import { calculateAge } from "@/utils/age.utils";
import { Plus, Trash2, Edit, Check, Download, Share2, ShoppingCart, Eye } from "lucide-react";
import Button from "@/components/ui/buttons/Button";
import ActionGroup from "@/components/ui/buttons/ActionGroup";


export const EMPTY_GUARANTOR: GuarantorFormValues = {
    id: "",

    name: "",
    gender: "Male",
    dob: "",

    email: "",
    mobileNumber: "",

    address: "",
    nationality: "Indian",

    aadhar: "",
    aadharFile: "",

    pan: "",
    panFile: "",

    fathersName: "",
    mothersName: "",

    passportNumber: "",
    passportValidity: "",
    passportFile: "",

    shareholdingPercentage: 0,

    qualification: "",
    briefProfile: "",

    netWorth: "",
    netWorthDate: "",
    netWorthCertificate: "",

    guaranteeDetails: "",

    otherDirectorships: "",

    age: undefined,

    itrFiles: undefined,

    itrList: [],
};


interface Props {
    initial?: GuarantorFormValues;
    onSave?: (data: GuarantorFormValues) => Promise<void>;
    onClose: () => void;
    title?: string;
}

export default function GuarantorForm({
    initial,
    onSave,
    onClose,
    title = "Add Guarantor",
}: Props) {
    const [globalError, setGlobalError] = useState<string>("");
    const [saving, setSaving] = useState(false);

    const defaultValues = initial || EMPTY_GUARANTOR;

    const form = useFormHook<GuarantorFormValues>({
        resolver: zodResolver(guarantorSchema),
        defaultValues,
    });

    // Watch dob field and auto-calculate age
    useEffect(() => {
        const subscription = form.watch((data) => {
            const dob = data.dob as string;
            if (dob) {
                const age = calculateAge(dob);
                form.setValue('age', age || undefined);
            }
        });
        return () => subscription.unsubscribe();
    }, [form]);

    // ITR & Computation Field Array
    const { fields: itrFields, append: appendITR, remove: removeITR, update: updateITR } = useFieldArray({
        control: form.control,
        name: "itrList",
    });

    const [itrYear, setItrYear] = useState("");
    const [itrFiles, setItrFiles] = useState<File[]>([]);
    const [editingItrIdx, setEditingItrIdx] = useState<number | null>(null);
    const [itrError, setItrError] = useState("");
    const [isDragActive, setIsDragActive] = useState(false);

    const financialYears = [
        "2023-24", "2022-23", "2021-22", "2020-21", "2019-20",
        "2018-19", "2017-18", "2016-17", "2015-16", "2014-15"
    ];

    const handleDrag = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
        if (e.dataTransfer.items?.length) setIsDragActive(true);
    };

    const handleDragOut = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragActive(false);
    };

    const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragActive(false);

        const files = e.dataTransfer.files;
        if (files && files.length > 0) {
            setItrFiles(Array.from(files));
        }
    };

    const handleAddITR = () => {
        if (!itrYear.trim()) {
            setItrError("Financial Year is required");
            return;
        }
        if (itrFiles.length === 0) {
            setItrError("Please upload at least one file");
            return;
        }
        setItrError("");

        itrFiles.forEach((file) => {
            const newITR = {
                financialYear: itrYear,
                itrFile: file as any,
                fileName: file.name,
            };

            if (editingItrIdx !== null) {
                updateITR(editingItrIdx, newITR);
                setEditingItrIdx(null);
            } else {
                appendITR(newITR);
            }
        });

        // Reset fields
        setItrYear("");
        setItrFiles([]);
    };

    const handleEditITR = (idx: number) => {
        const item = itrFields[idx];
        setItrYear(item.financialYear);
        setItrFiles([]);
        setEditingItrIdx(idx);
    };

    const handleRemoveITR = (idx: number) => {
        removeITR(idx);
        if (editingItrIdx === idx) {
            setEditingItrIdx(null);
            setItrYear("");
            setItrFiles([]);
        }
    };

    async function onSubmit(data: GuarantorFormValues) {
        setSaving(true);
        setGlobalError("");
        try {
            if (onSave) {
                await onSave(data);
            }
            onClose();
        } catch (err: unknown) {
            setGlobalError(err instanceof Error ? err.message : "Failed to save.");
            setSaving(false);
        }
    }

    return (
        <Modal
            onClose={onClose}
            isOpen={true}
        >
            <ModalHeader
                title={title}
                subtitle=""
                onClose={onClose}
            />
            <ModalBody>
                <Form form={form} onSubmit={onSubmit} className="space-y-7">
                    <FormSection title="Basic Information">
                        <FormField colSpan={1}>
                            <FormLabel required>Name</FormLabel>
                            <FormInput
                                name="name"
                                placeholder="Enter guarantor name"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel required>Gender</FormLabel>
                            <FormSelect
                                name="gender"
                                options={["Male", "Female", "Other"]}
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel required>Date of Birth</FormLabel>
                            <FormDatePicker
                                name="dob"
                                placeholder="DD/MM/YYYY"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Age</FormLabel>
                            <FormInput
                                name="age"
                                type="number"
                                placeholder="Auto-calculated"
                                readOnly
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel required>Nationality</FormLabel>
                            <FormSelect
                                name="nationality"
                                options={["Indian", "NRI", "Other"]}
                            />
                        </FormField>
                    </FormSection>
                    <FormSection title="Contact Details">
                        <FormField colSpan={1}>
                            <FormLabel required>Email</FormLabel>
                            <FormInput
                                name="email"
                                type="email"
                                placeholder="name@example.com"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Mobile Number</FormLabel>
                            <FormInput
                                name="mobileNumber"
                                placeholder="+91 9876543210"
                            />
                        </FormField>

                        <FormField colSpan={2}>
                            <FormLabel required>Residential Address</FormLabel>
                            <FormTextarea
                                name="address"
                                rows={3}
                                placeholder="Enter address"
                            />
                        </FormField>
                    </FormSection>

                    <FormSection title="Identity Information">
                        <FormField colSpan={1}>
                            <FormLabel required>Aadhaar Number</FormLabel>
                            <FormInput
                                name="aadhar"
                                placeholder="123456789012"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel required>PAN Number</FormLabel>
                            <FormInput
                                name="pan"
                                placeholder="ABCDE1234F"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Passport Number</FormLabel>
                            <FormInput
                                name="passportNumber"
                                placeholder="Z1234567"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Passport Validity</FormLabel>
                            <FormDatePicker
                                name="passportValidity"
                                placeholder="DD/MM/YYYY"
                            />
                        </FormField>
                    </FormSection>
                    <FormSection title="Family Information">
                        <FormField colSpan={1}>
                            <FormLabel required>Father's Name</FormLabel>
                            <FormInput
                                name="fathersName"
                                placeholder="Enter father's name"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel required>Mother's Name</FormLabel>
                            <FormInput
                                name="mothersName"
                                placeholder="Enter mother's name"
                            />
                        </FormField>
                    </FormSection>

                    <FormSection title="Company Information">
                        <FormField colSpan={1}>
                            <FormLabel>% Shareholding</FormLabel>
                            <FormInput
                                name="shareholdingPercentage"
                                type="number"
                                placeholder="0.00"
                                disabled
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Qualification</FormLabel>
                            <FormInput
                                name="qualification"
                                placeholder="MBA, CA, B.Com etc."
                            />
                        </FormField>

                        <FormField colSpan={2}>
                            <FormLabel>Brief Profile & Role</FormLabel>
                            <FormTextarea
                                name="briefProfile"
                                rows={4}
                                placeholder="Brief profile and role in company"
                            />
                        </FormField>
                    </FormSection>

                    <FormSection title="Financial Information">
                        <FormField colSpan={1}>
                            <FormLabel required>Net Worth</FormLabel>
                            <FormInput
                                name="netWorth"
                                placeholder="₹ 10 Cr"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Net Worth Date</FormLabel>
                            <FormMonthYearPicker
                                name="netWorthDate"
                                placeholder="MM/YYYY"
                            />
                        </FormField>

                        <FormField colSpan={2}>
                            <FormLabel required>Guarantee Details</FormLabel>
                            <FormTextarea
                                name="guaranteeDetails"
                                rows={4}
                                placeholder="Enter guarantee details"
                            />
                        </FormField>
                    </FormSection>

                    <FormSection title="Other Directorships">
                        <FormField colSpan={2}>
                            <FormLabel>Other Directorships</FormLabel>
                            <FormTextarea
                                name="otherDirectorships"
                                rows={4}
                                placeholder="Mention company name, designation, role and stake held"
                            />
                        </FormField>
                    </FormSection>
                    <FormSection title="Document Uploads">
                        <FormField colSpan={1}>
                            <FormLabel>Aadhaar</FormLabel>
                            <FormFileInput name="aadharFile" />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>PAN</FormLabel>
                            <FormFileInput name="panFile" />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Passport</FormLabel>
                            <FormFileInput name="passportFile" />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Net Worth Certificate</FormLabel>
                            <FormFileInput name="netWorthCertificate" />
                        </FormField>

                        <FormField colSpan={2}>
                            <FormLabel>ITR & Computation</FormLabel>
                            <div className="border border-gray-200 rounded-lg overflow-hidden mb-4 bg-gray-50 p-4">
                                <div className="grid grid-cols-1 gap-y-4">
                                    <div>
                                        <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                            Financial Year <span className="text-red-500">*</span>
                                        </label>
                                        <select
                                            value={itrYear}
                                            onChange={e => setItrYear(e.target.value)}
                                            className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-slate-800"
                                        >
                                            <option value="">Select Financial Year</option>
                                            {financialYears.map(year => (
                                                <option key={year} value={year}>{year}</option>
                                            ))}
                                        </select>
                                    </div>
                                    <div>
                                        <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                            ITR Document
                                        </label>
                                        <div
                                            onDragOver={handleDrag}
                                            onDragEnter={handleDragIn}
                                            onDragLeave={handleDragOut}
                                            onDrop={handleDrop}
                                            className={`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors cursor-pointer bg-white ${
                                                isDragActive
                                                    ? "border-blue-500 bg-blue-50"
                                                    : "border-gray-300 hover:border-gray-400"
                                            }`}
                                        >
                                            <input
                                                type="file"
                                                id="itr-file-input"
                                                accept=".pdf,.doc,.docx"
                                                onChange={(e) => setItrFiles(Array.from(e.target.files || []))}
                                                className="hidden"
                                                multiple
                                            />
                                            <label htmlFor="itr-file-input" className="cursor-pointer block">
                                                <div className={isDragActive ? "text-blue-600" : "text-gray-600"}>
                                                    <div className="text-sm font-medium">
                                                        {itrFiles.length > 0 ? `${itrFiles.length} file(s) selected` : 'Click to upload or drag & drop'}
                                                    </div>
                                                    {itrFiles.length > 0 && (
                                                        <div className="text-xs text-gray-700 mt-2 max-h-32 overflow-y-auto">
                                                            {itrFiles.map((file, idx) => (
                                                                <div key={idx} className="text-left truncate">{file.name}</div>
                                                            ))}
                                                        </div>
                                                    )}
                                                    {itrFiles.length === 0 && <div className="text-xs text-gray-500 mt-1">PDF, DOC, DOCX (Max 50MB)</div>}
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                {itrError && <p className="text-[10px] text-red-600 mt-3">{itrError}</p>}

                                <div className="mt-4 flex justify-end">
                                    {editingItrIdx === null ? (
                                        <button
                                            type="button"
                                            onClick={handleAddITR}
                                            className="flex items-center justify-center gap-2 px-3 py-2 bg-slate-800 text-white hover:bg-slate-900 text-sm font-semibold rounded-lg transition-colors"
                                        >
                                            <Plus className="w-4 h-4" />
                                            Add More
                                        </button>
                                    ) : (
                                        <ActionGroup>
                                            <Button
                                                type="button"
                                                onClick={() => {
                                                    setEditingItrIdx(null);
                                                    setItrYear("");
                                                    setItrFiles([]);
                                                    setItrError("");
                                                }}
                                                variant="outline"
                                                size="sm"
                                            >
                                                Cancel
                                            </Button>
                                            <Button
                                                type="button"
                                                onClick={handleAddITR}
                                                variant="primary"
                                                size="sm"
                                                icon={Check}
                                            >
                                                Update
                                            </Button>
                                        </ActionGroup>
                                    )}
                                </div>
                            </div>

                            {/* ITR Table */}
                            {itrFields.length > 0 && (
                                <div className="overflow-x-auto border border-gray-200 rounded-lg">
                                    <table className="w-full text-[11px]">
                                        <thead className="bg-gray-100 border-b">
                                            <tr>
                                                <th className="px-3 py-2 text-left font-semibold text-gray-600">Financial Year</th>
                                                <th className="px-3 py-2 text-left font-semibold text-gray-600">Document</th>
                                                <th className="px-3 py-2 text-center font-semibold text-gray-600">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {itrFields.map((field, index) => (
                                                <tr key={field.id} className="border-t hover:bg-gray-50">
                                                    <td className="px-3 py-2 text-gray-900 font-medium">{field.financialYear}</td>
                                                    <td className="px-3 py-2 text-gray-600 text-[10px] truncate">
                                                        {field.itrFile ? (
                                                            typeof field.itrFile === 'string'
                                                                ? field.itrFile
                                                                : field.fileName || (field.itrFile as any)?.name || '✓ File Selected'
                                                        ) : '-'}
                                                    </td>
                                                    <td className="px-3 py-2">
                                                        <div className="flex gap-1 justify-center">
                                                            <button
                                                                type="button"
                                                                onClick={() => console.log("View", index)}
                                                                className="p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 rounded transition-colors"
                                                                title="View"
                                                            >
                                                                <Eye size={16} />
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => console.log("Share", index)}
                                                                className="p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 rounded transition-colors"
                                                                title="Share"
                                                            >
                                                                <Share2 size={16} />
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => console.log("Add to Cart", index)}
                                                                className="p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 rounded transition-colors"
                                                                title="Add to Cart"
                                                            >
                                                                <ShoppingCart size={16} />
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => console.log("Download", index)}
                                                                className="p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 rounded transition-colors"
                                                                title="Download"
                                                            >
                                                                <Download size={16} />
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => handleEditITR(index)}
                                                                className="p-1.5 text-blue-600 hover:bg-blue-50 rounded transition-colors"
                                                                title="Edit"
                                                            >
                                                                <Edit size={16} />
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => handleRemoveITR(index)}
                                                                className="p-1.5 text-red-600 hover:bg-red-50 rounded transition-colors"
                                                                title="Delete"
                                                            >
                                                                <Trash2 size={16} />
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </FormField>
                    </FormSection>
                </Form>
            </ModalBody>
            <ModalFooter
                globalError={globalError}
                saving={saving}
                onClose={onClose}
                onSubmit={form.handleSubmit(onSubmit)}
            />
        </Modal>
    );
}
