import { Head, router, useForm } from '@inertiajs/react';
import { Download, Printer, RotateCcw, Wallet } from 'lucide-react';
import InvoiceController from '@/actions/App/Http/Controllers/InvoiceController';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useI18n } from '@/hooks/use-i18n';

type InvoiceDetail = {
    id: number;
    invoice_number: string;
    invoice_date: string;
    due_date: string;
    current_fee_amount: string | number;
    previous_due_amount: string | number;
    discount_amount: string | number;
    total_amount: string | number;
    paid_amount: string | number;
    due_amount: string | number;
    status: string;
    student?: {
        id: number;
        student_code: string;
        name_bn: string;
        name_en: string | null;
        guardian_name: string | null;
        guardian_phone: string | null;
        current_enrollment?: {
            department?: { name_bn: string; name_en: string | null } | null;
            academic_class?: { name_bn: string; name_en: string | null } | null;
        } | null;
    } | null;
    items: Array<{
        id: number;
        description_bn: string;
        description_en: string | null;
        total_amount: string | number;
    }>;
    due_items: Array<{
        id: number;
        amount_snapshot: string | number;
        source_fee_charge?: { billing_year: number; billing_month: number; fee_category?: { name_bn: string; name_en: string | null } | null } | null;
    }>;
    allocations: Array<{
        id: number;
        allocated_amount: string | number;
        payment?: {
            id: number;
            receipt_number: string;
            payment_date: string;
            amount: string | number;
            status: string;
            payment_method?: { name_bn: string; name_en: string | null } | null;
        } | null;
    }>;
};

type PaymentMethodItem = { id: number; name_bn: string; name_en: string | null };

export default function InvoiceShow({
    invoice,
    institution,
    paymentMethods,
}: {
    invoice: InvoiceDetail;
    institution: { name_bn: string; name_en: string | null; address_bn?: string | null; phone?: string | null } | null;
    paymentMethods: PaymentMethodItem[];
}) {
    const { locale, t, localized } = useI18n();

    const payForm = useForm({
        amount: String(invoice.due_amount),
        payment_method_id: paymentMethods[0]?.id ? String(paymentMethods[0].id) : '',
        payment_date: new Date().toISOString().slice(0, 10),
        transaction_reference: '',
        remarks: '',
        send_whatsapp: true,
    });

    return (
        <>
            <Head title={invoice.invoice_number} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div className="flex items-center justify-between print:hidden">
                    <h1 className="text-2xl font-bold">{invoice.invoice_number}</h1>
                    <Button variant="outline" onClick={() => window.print()}>
                        <Printer className="mr-1.5 h-4 w-4" />
                        {locale === 'bn' ? 'প্রিন্ট / পিডিএফ' : 'Print / PDF'}
                    </Button>
                </div>

                {/* Minimal Invoice Paper */}
                <div className="minimal-card mx-auto w-full max-w-4xl bg-card p-6 md:p-10">
                    <div className="flex flex-wrap items-start justify-between gap-4 border-b pb-6">
                        <div>
                            <h2 className="text-xl font-bold text-primary">{localized(institution, 'name')}</h2>
                            {institution?.address_bn && <p className="text-sm text-muted-foreground">{institution.address_bn}</p>}
                            {institution?.phone && <p className="text-xs text-muted-foreground">{institution.phone}</p>}
                        </div>
                        <div className="text-right">
                            <span className="inline-flex rounded-full bg-primary/15 px-3 py-1 text-xs font-bold uppercase text-primary">
                                {invoice.status}
                            </span>
                            <p className="mt-2 text-lg font-bold">{invoice.invoice_number}</p>
                            <p className="text-xs text-muted-foreground">
                                {locale === 'bn' ? 'ইস্যু:' : 'Issue:'} {invoice.invoice_date} · {locale === 'bn' ? 'শেষ তারিখ:' : 'Due:'}{' '}
                                {invoice.due_date}
                            </p>
                        </div>
                    </div>

                    <div className="my-6 grid gap-4 sm:grid-cols-2">
                        <div>
                            <p className="text-xs font-semibold uppercase text-muted-foreground">
                                {locale === 'bn' ? 'শিক্ষার্থীর তথ্য' : 'Billed To'}
                            </p>
                            <p className="mt-1 font-semibold">{localized(invoice.student, 'name')}</p>
                            <p className="text-sm text-muted-foreground">{invoice.student?.student_code}</p>
                            <p className="text-xs text-muted-foreground">
                                {localized(invoice.student?.current_enrollment?.department, 'name')} ·{' '}
                                {localized(invoice.student?.current_enrollment?.academic_class, 'name')}
                            </p>
                        </div>
                        <div className="sm:text-right">
                            <p className="text-xs font-semibold uppercase text-muted-foreground">
                                {locale === 'bn' ? 'অভিভাবক' : 'Guardian'}
                            </p>
                            <p className="mt-1 text-sm">{invoice.student?.guardian_name ?? '—'}</p>
                            <p className="text-sm text-muted-foreground">{invoice.student?.guardian_phone ?? '—'}</p>
                        </div>
                    </div>

                    <table className="w-full text-left text-sm">
                        <thead className="border-y bg-muted/40 text-xs uppercase text-muted-foreground">
                            <tr>
                                <th className="px-3 py-2.5">#</th>
                                <th className="px-3 py-2.5">{locale === 'bn' ? 'বিবরণ' : 'Description'}</th>
                                <th className="px-3 py-2.5 text-right">{locale === 'bn' ? 'পরিমাণ' : 'Amount'}</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y">
                            {invoice.items.map((item, idx) => (
                                <tr key={item.id}>
                                    <td className="px-3 py-2.5 text-muted-foreground">{idx + 1}</td>
                                    <td className="px-3 py-2.5 font-medium">
                                        {locale === 'bn' ? item.description_bn : (item.description_en ?? item.description_bn)}
                                    </td>
                                    <td className="px-3 py-2.5 text-right font-medium">৳{Number(item.total_amount).toLocaleString()}</td>
                                </tr>
                            ))}
                            {invoice.due_items.map((due) => (
                                <tr key={`due-${due.id}`} className="bg-amber-500/5">
                                    <td className="px-3 py-2.5 text-amber-600">+</td>
                                    <td className="px-3 py-2.5">
                                        {locale === 'bn' ? 'পূর্বের বকেয়া:' : 'Previous Due:'}{' '}
                                        {localized(due.source_fee_charge?.fee_category, 'name')}{' '}
                                        {due.source_fee_charge ? `(${due.source_fee_charge.billing_month}/${due.source_fee_charge.billing_year})` : ''}
                                    </td>
                                    <td className="px-3 py-2.5 text-right font-medium text-amber-600">
                                        ৳{Number(due.amount_snapshot).toLocaleString()}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>

                    <div className="mt-6 flex justify-end">
                        <div className="w-full max-w-xs space-y-1.5 text-sm">
                            <div className="flex justify-between">
                                <span className="text-muted-foreground">{locale === 'bn' ? 'চলতি ফি' : 'Subtotal'}</span>
                                <span>৳{Number(invoice.current_fee_amount).toLocaleString()}</span>
                            </div>
                            <div className="flex justify-between">
                                <span className="text-muted-foreground">{locale === 'bn' ? 'পূর্বের বকেয়া' : 'Previous Due'}</span>
                                <span>৳{Number(invoice.previous_due_amount).toLocaleString()}</span>
                            </div>
                            <div className="flex justify-between border-t pt-1.5 font-bold">
                                <span>{locale === 'bn' ? 'সর্বমোট' : 'Total'}</span>
                                <span>৳{Number(invoice.total_amount).toLocaleString()}</span>
                            </div>
                            <div className="flex justify-between text-emerald-600">
                                <span>{locale === 'bn' ? 'জমা' : 'Paid'}</span>
                                <span>৳{Number(invoice.paid_amount).toLocaleString()}</span>
                            </div>
                            <div className="flex justify-between border-t pt-1.5 text-base font-bold text-rose-600">
                                <span>{locale === 'bn' ? 'বকেয়া' : 'Balance Due'}</span>
                                <span>৳{Number(invoice.due_amount).toLocaleString()}</span>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Payment History & Collection */}
                <div className="mx-auto grid w-full max-w-4xl gap-6 md:grid-cols-2 print:hidden">
                    {Number(invoice.due_amount) > 0 && (
                        <div className="minimal-card p-6">
                            <div className="mb-4 flex items-center gap-2">
                                <Wallet className="h-5 w-5 text-primary" />
                                <h3 className="font-semibold">{locale === 'bn' ? 'পেমেন্ট গ্রহণ করুন' : 'Collect Payment'}</h3>
                            </div>
                            <form
                                onSubmit={(e) => {
                                    e.preventDefault();
                                    payForm.submit(InvoiceController.recordPayment(invoice.id));
                                }}
                                className="space-y-3"
                            >
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'পরিমাণ (৳)' : 'Amount'}</Label>
                                    <Input
                                        type="number"
                                        step="0.01"
                                        min="0.01"
                                        value={payForm.data.amount}
                                        onChange={(e) => payForm.setData('amount', e.target.value)}
                                        required
                                    />
                                </div>
                                <div className="grid grid-cols-2 gap-3">
                                    <div className="space-y-1">
                                        <Label>{locale === 'bn' ? 'মাধ্যম' : 'Method'}</Label>
                                        <select
                                            value={payForm.data.payment_method_id}
                                            onChange={(e) => payForm.setData('payment_method_id', e.target.value)}
                                            className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                        >
                                            {paymentMethods.map((pm) => (
                                                <option key={pm.id} value={pm.id}>
                                                    {localized(pm, 'name')}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                    <div className="space-y-1">
                                        <Label>{locale === 'bn' ? 'তারিখ' : 'Date'}</Label>
                                        <Input
                                            type="date"
                                            value={payForm.data.payment_date}
                                            onChange={(e) => payForm.setData('payment_date', e.target.value)}
                                        />
                                    </div>
                                </div>
                                <label className="flex items-center gap-2 text-sm">
                                    <input
                                        type="checkbox"
                                        checked={payForm.data.send_whatsapp}
                                        onChange={(e) => payForm.setData('send_whatsapp', e.target.checked)}
                                        className="h-4 w-4 accent-primary"
                                    />
                                    <span>{locale === 'bn' ? 'হোয়াটসঅ্যাপ রসিদ পাঠান' : 'Send WhatsApp confirmation'}</span>
                                </label>
                                <Button type="submit" disabled={payForm.processing} className="w-full">
                                    {locale === 'bn' ? 'পেমেন্ট সংরক্ষণ করুন' : 'Save Payment'}
                                </Button>
                            </form>
                        </div>
                    )}

                    <div className="minimal-card p-6">
                        <h3 className="mb-3 font-semibold">{locale === 'bn' ? 'পেমেন্ট ইতিহাস' : 'Payment History'}</h3>
                        <div className="space-y-2">
                            {invoice.allocations.length === 0 ? (
                                <p className="text-sm text-muted-foreground">
                                    {locale === 'bn' ? 'এখনো কোনো পেমেন্ট হয়নি।' : 'No payments recorded yet.'}
                                </p>
                            ) : (
                                invoice.allocations.map((alloc) => (
                                    <div key={alloc.id} className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
                                        <div>
                                            <p className="font-medium">{alloc.payment?.receipt_number}</p>
                                            <p className="text-xs text-muted-foreground">
                                                {alloc.payment?.payment_date} · {localized(alloc.payment?.payment_method, 'name')}
                                            </p>
                                        </div>
                                        <div className="flex items-center gap-2">
                                            <span className="font-semibold text-emerald-600">
                                                ৳{Number(alloc.allocated_amount).toLocaleString()}
                                            </span>
                                            {alloc.payment && (
                                                <Button size="sm" variant="ghost" asChild title="Download Receipt PDF">
                                                    <a href={InvoiceController.downloadPaymentReceipt(alloc.payment.id).url} target="_blank" rel="noreferrer">
                                                        <Download className="h-3.5 w-3.5" />
                                                    </a>
                                                </Button>
                                            )}
                                            {alloc.payment && alloc.payment.status !== 'reversed' && (
                                                <Button
                                                    size="sm"
                                                    variant="ghost"
                                                    onClick={() => router.post(InvoiceController.reversePayment(alloc.payment!.id).url)}
                                                    title="Reverse Payment"
                                                >
                                                    <RotateCcw className="h-3.5 w-3.5 text-rose-500" />
                                                </Button>
                                            )}
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}
