import { useEffect, useRef, useState } from 'react';
import { useForm } from '@inertiajs/react';
import { FileText, Image as ImageIcon, Download, Loader2 } from 'lucide-react';
import { Button } from '@/Components/ui/button';
import { useToast } from '@/Components/Toast';
import { FloatingField } from '@/Components/Proto/UI/FloatingField';

/** h-11 in px — the floor, so a short address is the exact height of the inputs beside it. */
const INPUT_H = 44;
/** ~6 lines. Beyond this the address scrolls instead of pushing the document slots down. */
const MAX_ADDRESS_H = 132;

/**
 * CompanyNpwpSection — the "NPWP" tab on Edit Company (legacy listnpwp.php). A single-row form
 * on `company`: NPWPNo + NPWPName/NPWPAddress (stored UPPERCASE server-side) + five document
 * slots. Data comes from the tab's fetched payload; the write goes to CompanyNpwpController.
 * Renders inside the company <form>, so every control is type="button" / a plain file input.
 */

const SLOTS = [
    { key: 'npwp', label: 'NPWP' },
    { key: 'sppkp', label: 'SPPKP' },
    { key: 'ktp', label: 'KTP' },
    { key: 'kartunama', label: 'Kartu Nama' },
    { key: 'lainlain', label: 'Lain-lain' },
];

function FieldError({ message }) {
    return message ? <p className="mt-1 text-xs text-destructive">{message}</p> : null;
}

export default function CompanyNpwpSection({
    companyId = null, npwp = {}, slots = {}, readOnly = false, onSaved,
}) {
    const { show: showToast } = useToast();
    const form = useForm({
        NPWPNo: npwp.NPWPNo ?? '',
        NPWPName: npwp.NPWPName ?? '',
        NPWPAddress: npwp.NPWPAddress ?? '',
        npwp: null, sppkp: null, ktp: null, kartunama: null, lainlain: null,
    });

    const addressRef = useRef(null);
    const [fileNames, setFileNames] = useState({}); // freshly-picked file labels, per slot

    const pick = (key) => (e) => {
        const file = e.target.files?.[0] ?? null;
        form.setData(key, file);
        setFileNames((f) => ({ ...f, [key]: file?.name ?? '' }));
    };

    const save = () => {
        form.post(route('companies.npwp.update', companyId), {
            preserveScroll: true,
            forceFormData: true, // always multipart (file slots may be null)
            onSuccess: () => {
                onSaved?.();
            },
            onError: () => showToast('Please check the NPWP form and try again.', 'error'),
        });
    };

    // Grow-to-fit: reset to auto first so the box can also SHRINK when text is deleted, then
    // take the content height. Inline height beats the h-11 class, so a short address measures
    // exactly the same 44px as the inputs next to it.
    const fitAddress = (el) => {
        if (! el) return;
        el.style.height = 'auto';
        el.style.height = `${Math.min(Math.max(el.scrollHeight, INPUT_H), MAX_ADDRESS_H)}px`;
    };

    // Runs for the value the tab loaded with, not just for what the user types.
    useEffect(() => { fitAddress(addressRef.current); }, [form.data.NPWPAddress, readOnly]);

    return (
        <div className="flex flex-col gap-5 p-1">
            {/* Identity fields */}
            <div className="grid grid-cols-1 gap-3.5 md:grid-cols-3">
                <div>
                    <FloatingField label="NPWP No" value={form.data.NPWPNo} onChange={(e) => form.setData('NPWPNo', e.target.value)} disabled={readOnly} />
                    <FieldError message={form.errors.NPWPNo} />
                </div>
                <div>
                    <FloatingField label="NPWP Name" value={form.data.NPWPName} onChange={(e) => form.setData('NPWPName', e.target.value)} disabled={readOnly} />
                    <FieldError message={form.errors.NPWPName} />
                </div>
                <div>
                    {/* Looks EXACTLY like the two fields beside it while the address is short —
                        rows={1} makes FloatingField size a textarea like an input (h-11). It only
                        grows once the text actually wraps, which is the point: the column holds
                        500 characters and a fixed one-liner showed ~25 of them, unscrollable when
                        read-only. Capped at MAX_ADDRESS_H so one long address cannot push the
                        document slots off the screen; past that it scrolls. */}
                    <FloatingField
                        as="textarea"
                        rows={1}
                        ref={addressRef}
                        controlClassName="resize-none overflow-y-auto"
                        label="NPWP Address"
                        value={form.data.NPWPAddress}
                        onChange={(e) => { form.setData('NPWPAddress', e.target.value); fitAddress(e.target); }}
                        disabled={readOnly}
                    />
                    <FieldError message={form.errors.NPWPAddress} />
                </div>
            </div>

            {/* Document slots */}
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
                {SLOTS.map(({ key, label }) => {
                    const slot = slots[key] ?? {};
                    return (
                        <div key={key} className="flex flex-col gap-2 rounded-lg border border-border bg-secondary/20 p-3.5">
                            <div className="flex items-center justify-between">
                                <span className="text-xs font-bold text-card-foreground">{label}</span>
                                {slot.hasFile ? (
                                    <a href={route('companies.npwp.file', [companyId, key])}
                                        className="inline-flex items-center gap-1 text-[11px] font-semibold text-primary hover:underline">
                                        {slot.isImage ? <ImageIcon className="size-3.5" /> : <FileText className="size-3.5" />}
                                        <Download className="size-3" /> View
                                    </a>
                                ) : (
                                    <span className="text-[11px] italic text-muted-foreground">Belum ada file</span>
                                )}
                            </div>
                            {!readOnly && (
                                <>
                                    <input type="file" accept="application/pdf,image/*" onChange={pick(key)}
                                        className="w-full rounded-md border border-input bg-card px-2.5 py-1.5 text-[11px] text-foreground file:mr-2 file:rounded file:border-0 file:bg-secondary file:px-2 file:py-0.5 file:text-[11px]" />
                                    {fileNames[key] && <span className="truncate text-[10.5px] text-muted-foreground">Baru: {fileNames[key]}</span>}
                                    <FieldError message={form.errors[key]} />
                                </>
                            )}
                        </div>
                    );
                })}
            </div>

            <p className="m-0 text-[10.5px] italic text-muted-foreground">
                File: PDF atau image, maks 1MB per dokumen. Mengunggah file baru menggantikan yang lama (versi lama tetap tersimpan di history).
            </p>

            {!readOnly && (
                <div className="flex justify-end">
                    <Button type="button" onClick={save} disabled={form.processing} className="font-bold">
                        {form.processing ? <><Loader2 className="mr-2 size-4 animate-spin" />Menyimpan...</> : 'Simpan NPWP'}
                    </Button>
                </div>
            )}
        </div>
    );
}
