"use client";

import { useState } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Plus, Trash2, Edit, Check } from "lucide-react";
import { Shareholder } from "@/types";
import { shareholdingSchema, ShareholdingFormValues } from "@/schema/shareholding";

import {
    Form,
    FormSection,
    FormField,
    FormLabel,
    FormInput,
    FormSelect,
    FormRadioGroup,
} from "@/components/ui/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 Button from "@/components/ui/buttons/Button";
import ActionGroup from "@/components/ui/buttons/ActionGroup";

export const EMPTY_SHAREHOLDER: ShareholdingFormValues = {
    shareholderName: "",
    numberOfShares: "",
    shareholdingPercentage: "",
    typeOfShare: "Equity",
    referenceNumber: "",
    whetherDirectorInCompany: "no",
    whetherDemat: "no",
    isinNumber: "",
    category: "Individual",
    subCategory: "Public",
    subShareholders: [],
};

interface Props {
    initial?: Shareholder;
    onSave: (data: Shareholder) => Promise<void>;
    onClose: () => void;
    title?: string;
}

export default function ShareholdingForm({
    initial,
    onSave,
    onClose,
    title = "Add Shareholding",
}: Props) {
    const [globalError, setGlobalError] = useState<string>("");
    const [saving, setSaving] = useState(false);

    const defaultValues: ShareholdingFormValues = initial
        ? {
            id: initial.id,
            shareholderName: initial.shareholderName,
            numberOfShares: initial.shares,
            shareholdingPercentage: initial.holding,
            typeOfShare: initial.shareClass,
            referenceNumber: initial.referenceNo,
            whetherDirectorInCompany: (initial.whetherDirectorInCompany as "yes" | "no") || "no",
            whetherDemat: (initial.whetherDemat as "yes" | "no") || "no",
            isinNumber: initial.isinNumber || "",
            category: initial.category || "Individual",
            subCategory: initial.subCategory || "Public",
            subShareholders: initial.subHolders
                ? initial.subHolders.map(sh => ({
                    name: sh.shareholderName,
                    referenceNumber: sh.referenceNo,
                    shares: sh.shares,
                    shareholdingPercentage: sh.holding,
                    category: sh.category || "Individual",
                    subCategory: sh.subCategory || "Public",
                    typeOfShare: sh.shareClass || "Equity",
                    whetherDirectorInCompany: (sh.whetherDirectorInCompany as "yes" | "no") || "no",
                    whetherDemat: (sh.whetherDemat as "yes" | "no") || "no",
                    isinNumber: sh.isinNumber || "",
                }))
                : [],
        }
        : EMPTY_SHAREHOLDER;

    const form = useForm<ShareholdingFormValues>({
        resolver: zodResolver(shareholdingSchema),
        defaultValues: defaultValues,
    });

    const whetherDemat = form.watch("whetherDemat");
    const category = form.watch("category");

    const { fields: subShareholderFields, append: appendSubShareholder, remove: removeSubShareholder, update: updateSubShareholder } = useFieldArray({
        control: form.control,
        name: "subShareholders",
    });

    const [subName, setSubName] = useState("");
    const [subRef, setSubRef] = useState("");
    const [subShares, setSubShares] = useState("");
    const [subPct, setSubPct] = useState("");
    const [subClass, setSubClass] = useState("Individual");
    const [subCat, setSubCat] = useState("Public");
    const [subType, setSubType] = useState("Equity");
    const [subDirector, setSubDirector] = useState<"yes" | "no">("no");
    const [subDemat, setSubDemat] = useState<"yes" | "no">("no");
    const [subISIN, setSubISIN] = useState("");

    const [editingIdx, setEditingIdx] = useState<number | null>(null);
    const [subFieldError, setSubFieldError] = useState("");

    const handleAddSub = () => {
        if (!subName.trim()) {
            setSubFieldError("Sub-shareholder Name is required");
            return;
        }
        if (!subRef.trim()) {
            setSubFieldError("Reference No is required");
            return;
        }
        if (!subShares.trim()) {
            setSubFieldError("Shares is required");
            return;
        }
        if (!subPct.trim()) {
            setSubFieldError("% of Shareholding is required");
            return;
        }
        setSubFieldError("");

        const newSub = {
            name: subName,
            referenceNumber: subRef,
            shares: subShares,
            shareholdingPercentage: subPct,
            category: subClass,
            subCategory: subCat,
            typeOfShare: subType,
            whetherDirectorInCompany: subDirector,
            whetherDemat: subDemat,
            isinNumber: subDemat === "yes" ? subISIN : "",
        };

        if (editingIdx !== null) {
            updateSubShareholder(editingIdx, newSub);
            setEditingIdx(null);
        } else {
            appendSubShareholder(newSub);
        }

        // Reset fields
        setSubName("");
        setSubRef("");
        setSubShares("");
        setSubPct("");
        setSubClass("Individual");
        setSubCat("Public");
        setSubType("Equity");
        setSubDirector("no");
        setSubDemat("no");
        setSubISIN("");
    };

    const handleEditSub = (idx: number) => {
        const item = subShareholderFields[idx];
        setSubName(item.name);
        setSubRef(item.referenceNumber);
        setSubShares(item.shares.toString());
        setSubPct(item.shareholdingPercentage.toString().replace(/%/g, ""));
        setSubClass(item.category || "Individual");
        setSubCat(item.subCategory || "Public");
        setSubType(item.typeOfShare || "Equity");
        setSubDirector((item.whetherDirectorInCompany || "no") as "yes" | "no");
        setSubDemat((item.whetherDemat || "no") as "yes" | "no");
        setSubISIN(item.isinNumber || "");
        setEditingIdx(idx);
    };

    const handleRemoveSub = (idx: number) => {
        removeSubShareholder(idx);
        if (editingIdx === idx) {
            setEditingIdx(null);
            setSubName("");
            setSubRef("");
            setSubShares("");
            setSubPct("");
            setSubClass("Individual");
            setSubCat("Public");
            setSubType("Equity");
            setSubDirector("no");
            setSubDemat("no");
            setSubISIN("");
        }
    };

    async function onSubmit(data: ShareholdingFormValues) {
        setSaving(true);
        setGlobalError("");
        try {
            const submitData: Shareholder = {
                id: data.id || Date.now().toString(),
                shareholderName: data.shareholderName,
                shares: data.numberOfShares.toString(),
                holding: data.shareholdingPercentage.toString().endsWith("%")
                    ? data.shareholdingPercentage.toString()
                    : `${data.shareholdingPercentage}%`,
                effectiveHolding: data.shareholdingPercentage.toString().endsWith("%")
                    ? data.shareholdingPercentage.toString()
                    : `${data.shareholdingPercentage}%`,
                shareClass: data.typeOfShare || "Equity",
                referenceNo: data.referenceNumber,
                whetherDirectorInCompany: data.whetherDirectorInCompany,
                whetherDemat: data.whetherDemat,
                isinNumber: data.whetherDemat === "yes" ? data.isinNumber : "",
                category: data.category || "Individual",
                subCategory: data.subCategory || "Public",
                sbo: "No",
                subHolders: data.category === "Corporate" && data.subShareholders
                    ? data.subShareholders.map(sh => ({
                        id: Date.now().toString() + Math.random().toString(),
                        shareholderName: sh.name,
                        shares: sh.shares.toString(),
                        holding: sh.shareholdingPercentage.toString().endsWith("%")
                            ? sh.shareholdingPercentage.toString()
                            : `${sh.shareholdingPercentage}%`,
                        effectiveHolding: sh.shareholdingPercentage.toString().endsWith("%")
                            ? sh.shareholdingPercentage.toString()
                            : `${sh.shareholdingPercentage}%`,
                        shareClass: sh.typeOfShare || "Equity",
                        referenceNo: sh.referenceNumber,
                        category: sh.category || "Individual",
                        subCategory: sh.subCategory || "Public",
                        whetherDirectorInCompany: sh.whetherDirectorInCompany,
                        whetherDemat: sh.whetherDemat,
                        isinNumber: sh.whetherDemat === "yes" ? sh.isinNumber : "",
                        sbo: "No",
                    }))
                    : [],
            };

            await onSave(submitData);
            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="Shareholding Information">
                        <FormField colSpan={1}>
                            <FormLabel required>Shareholder Name</FormLabel>
                            <FormInput
                                name="shareholderName"
                                placeholder="Enter shareholder name"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel required>Number of Shares</FormLabel>
                            <FormInput
                                name="numberOfShares"
                                type="number"
                                placeholder="100000"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel required>% of Shareholding</FormLabel>
                            <FormInput
                                name="shareholdingPercentage"
                                type="number"
                                placeholder="25.00"
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Type of Share</FormLabel>
                            <FormSelect
                                name="typeOfShare"
                                options={["Equity", "Preference", "CCPS"]}
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel required>Reference Number</FormLabel>
                            <FormInput
                                name="referenceNumber"
                                type="text"
                                placeholder="Enter reference number"
                            />
                        </FormField>
                    </FormSection>

                    <FormSection title="Company Relationship">
                        <FormField colSpan={1}>
                            <FormLabel required>Whether Director in Company</FormLabel>
                            <FormRadioGroup
                                name='whetherDirectorInCompany'
                                direction='horizontal'
                                options={[
                                    { label: 'Yes', value: 'yes' },
                                    { label: 'No', value: 'no' }
                                ]}
                            />
                        </FormField>
                    </FormSection>

                    <FormSection title="Demat Details">
                        <FormField colSpan={1}>
                            <FormLabel required>Whether Demat</FormLabel>
                            <FormRadioGroup
                                name='whetherDemat'
                                direction='horizontal'
                                options={[
                                    { label: 'Yes', value: 'yes' },
                                    { label: 'No', value: 'no' }
                                ]}
                            />
                        </FormField>
                        {whetherDemat === 'yes' && (
                            <FormField colSpan={1}>
                                <FormLabel required>ISIN</FormLabel>
                                <FormInput
                                    name="isinNumber"
                                    type="text"
                                    placeholder="Enter ISIN number"
                                />
                            </FormField>
                        )}
                    </FormSection>

                    <FormSection title="Classification & Category">
                        <FormField colSpan={1}>
                            <FormLabel>Classification</FormLabel>
                            <FormSelect
                                name="category"
                                options={["Individual", "Corporate"]}
                            />
                        </FormField>

                        <FormField colSpan={1}>
                            <FormLabel>Category</FormLabel>
                            <FormSelect
                                name="subCategory"
                                options={["Public", "Investor", "Founder", "Family Member"]}
                            />
                        </FormField>
                    </FormSection>

                    {/* Sub-shareholder Section - Only when Corporate */}
                    {category === "Corporate" && (
                        <FormSection title="Sub-shareholder Info">
                            <FormField colSpan={2}>
                                <div className="flex items-center justify-between mb-6">
                                    <label className="text-[10px] font-semibold uppercase tracking-widest text-gray-500">
                                        Add Sub-shareholder
                                    </label>
                                </div>

                                <div className="border border-gray-200 rounded-lg overflow-hidden mb-4 bg-gray-50 p-4">
                                    <div className="grid grid-cols-2 gap-x-5 gap-y-4">
                                        <div>
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                                Name <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                value={subName}
                                                onChange={e => setSubName(e.target.value)}
                                                placeholder="Enter name"
                                                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"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                                Ref No <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                value={subRef}
                                                onChange={e => setSubRef(e.target.value)}
                                                placeholder="Enter reference"
                                                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"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                                Shares <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                type="number"
                                                value={subShares}
                                                onChange={e => setSubShares(e.target.value)}
                                                placeholder="0"
                                                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"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                               % Holding <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                type="number"
                                                value={subPct}
                                                onChange={e => setSubPct(e.target.value)}
                                                placeholder="0.00"
                                                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"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                                Classification
                                            </label>
                                            <select
                                                value={subClass}
                                                onChange={e => setSubClass(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="Individual">Individual</option>
                                                <option value="Corporate">Corporate</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                                Category
                                            </label>
                                            <select
                                                value={subCat}
                                                onChange={e => setSubCat(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="Public">Public</option>
                                                <option value="Investor">Investor</option>
                                                <option value="Founder">Founder</option>
                                                <option value="Family Member">Family Member</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                                Type of Share
                                            </label>
                                            <select
                                                value={subType}
                                                onChange={e => setSubType(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="Equity">Equity</option>
                                                <option value="Preference">Preference</option>
                                                <option value="CCPS">CCPS</option>
                                            </select>
                                        </div>
                                        <div className="col-span-1">
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-2">
                                                Whether Director <span className="text-red-500">*</span>
                                            </label>
                                            <div className="flex gap-6 mt-3">
                                                <label className="flex items-center gap-2 cursor-pointer">
                                                    <input
                                                        type="radio"
                                                        value="yes"
                                                        checked={subDirector === "yes"}
                                                        onChange={e => setSubDirector(e.target.value as "yes" | "no")}
                                                        className="w-4 h-4 accent-slate-800"
                                                    />
                                                    <span className="text-sm text-gray-700">Yes</span>
                                                </label>
                                                <label className="flex items-center gap-2 cursor-pointer">
                                                    <input
                                                        type="radio"
                                                        value="no"
                                                        checked={subDirector === "no"}
                                                        onChange={e => setSubDirector(e.target.value as "yes" | "no")}
                                                        className="w-4 h-4 accent-slate-800"
                                                    />
                                                    <span className="text-sm text-gray-700">No</span>
                                                </label>
                                            </div>
                                        </div>
                                        <div className="col-span-1">
                                            <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-2">
                                                Whether Demat <span className="text-red-500">*</span>
                                            </label>
                                            <div className="flex gap-6 mt-3">
                                                <label className="flex items-center gap-2 cursor-pointer">
                                                    <input
                                                        type="radio"
                                                        value="yes"
                                                        checked={subDemat === "yes"}
                                                        onChange={e => setSubDemat(e.target.value as "yes" | "no")}
                                                        className="w-4 h-4 accent-slate-800"
                                                    />
                                                    <span className="text-sm text-gray-700">Yes</span>
                                                </label>
                                                <label className="flex items-center gap-2 cursor-pointer">
                                                    <input
                                                        type="radio"
                                                        value="no"
                                                        checked={subDemat === "no"}
                                                        onChange={e => setSubDemat(e.target.value as "yes" | "no")}
                                                        className="w-4 h-4 accent-slate-800"
                                                    />
                                                    <span className="text-sm text-gray-700">No</span>
                                                </label>
                                            </div>
                                        </div>
                                        {subDemat === 'yes' && (
                                            <div className="col-span-1">
                                                <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
                                                    ISIN <span className="text-red-500">*</span>
                                                </label>
                                                <input
                                                    value={subISIN}
                                                    onChange={e => setSubISIN(e.target.value)}
                                                    placeholder="Enter ISIN number"
                                                    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"
                                                />
                                            </div>
                                        )}
                                    </div>

                                    {subFieldError && <p className="text-[10px] text-red-600 mt-3">{subFieldError}</p>}

                                    <div className="mt-4 flex justify-end">
                                        {editingIdx === null ? (
                                            <button
                                                type="button"
                                                onClick={handleAddSub}
                                                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
                                            </button>
                                        ) : (
                                            <ActionGroup>
                                                <Button
                                                    type="button"
                                                    onClick={() => {
                                                        setEditingIdx(null);
                                                        setSubName("");
                                                        setSubRef("");
                                                        setSubShares("");
                                                        setSubPct("");
                                                        setSubClass("Individual");
                                                        setSubCat("Public");
                                                        setSubType("Equity");
                                                        setSubDirector("no");
                                                        setSubDemat("no");
                                                        setSubISIN("");
                                                        setSubFieldError("");
                                                    }}
                                                    variant="outline"
                                                    size="sm"
                                                >
                                                    Cancel
                                                </Button>
                                                <Button
                                                    type="button"
                                                    onClick={handleAddSub}
                                                    variant="primary"
                                                    size="sm"
                                                    icon={Check}
                                                >
                                                    Update
                                                </Button>
                                            </ActionGroup>
                                        )}
                                    </div>
                                </div>

                                {/* Table */}
                                {subShareholderFields.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">Name</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">Ref</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">Shares</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">%</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">Class</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">Category</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">Type</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">Director</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">Demat</th>
                                                    <th className="px-3 py-2 text-left font-semibold text-gray-600">ISIN</th>
                                                    <th className="px-3 py-2 text-center font-semibold text-gray-600">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {subShareholderFields.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.name}</td>
                                                        <td className="px-3 py-2 text-gray-600">{field.referenceNumber}</td>
                                                        <td className="px-3 py-2 text-gray-600">{field.shares}</td>
                                                        <td className="px-3 py-2 text-gray-600">{field.shareholdingPercentage}</td>
                                                        <td className="px-3 py-2 text-gray-600 text-[10px]">{field.category}</td>
                                                        <td className="px-3 py-2 text-gray-600 text-[10px]">{field.subCategory}</td>
                                                        <td className="px-3 py-2 text-gray-600 text-[10px]">{field.typeOfShare}</td>
                                                        <td className="px-3 py-2 text-gray-600 text-[10px] capitalize">{field.whetherDirectorInCompany}</td>
                                                        <td className="px-3 py-2 text-gray-600 text-[10px] capitalize">{(field as any).whetherDemat || "no"}</td>
                                                        <td className="px-3 py-2 text-gray-600 text-[10px]">{(field as any).isinNumber || "-"}</td>
                                                        <td className="px-3 py-2 flex gap-2 justify-center">
                                                            <button
                                                                type="button"
                                                                onClick={() => handleEditSub(index)}
                                                                className="p-1 text-blue-600 hover:bg-blue-50 rounded"
                                                                title="Edit"
                                                            >
                                                                <Edit size={14} />
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={() => handleRemoveSub(index)}
                                                                className="p-1 text-red-600 hover:bg-red-50 rounded"
                                                                title="Delete"
                                                            >
                                                                <Trash2 size={14} />
                                                            </button>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                )}
                            </FormField>
                        </FormSection>
                    )}
                </Form>
            </ModalBody>
            <ModalFooter
                globalError={globalError}
                saving={saving}
                onClose={onClose}
                onSubmit={form.handleSubmit(onSubmit)}
            />
        </Modal>
    );
}
