import { Head, Link, router, useForm } from '@inertiajs/react';
import { CalendarPlus, Eye, FileText, Search, Wallet } from 'lucide-react';
import { useState } from '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';
import { index as invoicesIndex, show as invoiceShow } from '@/routes/invoices';

type InvoiceRow = {
    id: number;
    invoice_number: string;
    billing_year: number | null;
    billing_month: number | null;
    invoice_date: string;
    due_date: string;
    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_phone: string | null;
    } | null;
};

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

type Summary = {
    total_amount: number;
    total_count: number;
    paid_amount: number;
    paid_count: number;
    partial_amount: number;
    partial_count: number;
    unpaid_amount: number;
    unpaid_count: number;
    overdue_amount: number;
    overdue_count: number;
};

const statusBadge: Record<string, string> = {
    paid: 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400',
    partial: 'bg-amber-500/15 text-amber-600 dark:text-amber-400',
    unpaid: 'bg-slate-500/15 text-slate-600 dark:text-slate-300',
    overdue: 'bg-rose-500/15 text-rose-600 dark:text-rose-400',
};

export default function InvoicesIndex({
    invoices,
    summary,
    paymentMethods,
    filters,
}: {
    invoices: { data: InvoiceRow[] };
    summary: Summary;
    paymentMethods: PaymentMethodItem[];
    filters: { status: string; search: string };
}) {
    const { locale, t, localized } = useI18n();
    const [search, setSearch] = useState(filters.search);
    const [payingInvoice, setPayingInvoice] = useState<InvoiceRow | null>(null);

    const now = new Date();
    const generateForm = useForm({
        year: now.getFullYear(),
        month: now.getMonth() + 1,
    });

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

    const openQuickPay = (inv: InvoiceRow) => {
        setPayingInvoice(inv);
        payForm.setData({
            amount: String(inv.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,
        });
    };

    const kpis = [
        { key: 'all', label: locale === 'bn' ? 'মোট' : 'Total', amount: summary.total_amount, count: summary.total_count },
        { key: 'paid', label: locale === 'bn' ? 'পরিশোধিত' : 'Paid', amount: summary.paid_amount, count: summary.paid_count },
        { key: 'partial', label: locale === 'bn' ? 'আংশিক' : 'Partial', amount: summary.partial_amount, count: summary.partial_count },
        { key: 'unpaid', label: locale === 'bn' ? 'অপরিশোধিত' : 'Unpaid', amount: summary.unpaid_amount, count: summary.unpaid_count },
        { key: 'overdue', label: locale === 'bn' ? 'বকেয়া মেয়াদোত্তীর্ণ' : 'Overdue', amount: summary.overdue_amount, count: summary.overdue_count },
    ];

    return (
        <>
            <Head title={t('nav.invoices', 'Monthly Invoices')} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div className="flex flex-wrap items-center justify-between gap-4">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight">
                            {t('nav.invoices', 'Monthly Invoices')}
                        </h1>
                        <p className="text-sm text-muted-foreground">
                            {locale === 'bn'
                                ? 'মাসিক ইনভয়েস তৈরি, পূর্বের বকেয়া সমন্বয় এবং ম্যানুয়াল পেমেন্ট সংগ্রহ করুন।'
                                : 'Generate monthly invoices, carry forward dues, and collect manual payments.'}
                        </p>
                    </div>

                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            generateForm.submit(InvoiceController.generate());
                        }}
                        className="flex flex-wrap items-center gap-2"
                    >
                        <select
                            value={generateForm.data.month}
                            onChange={(e) => generateForm.setData('month', Number(e.target.value))}
                            className="h-9 rounded-md border border-input bg-background px-2.5 text-sm"
                        >
                            {Array.from({ length: 12 }, (_, i) => i + 1).map((m) => (
                                <option key={m} value={m}>
                                    {m}
                                </option>
                            ))}
                        </select>
                        <Input
                            type="number"
                            value={generateForm.data.year}
                            onChange={(e) => generateForm.setData('year', Number(e.target.value))}
                            className="w-24"
                        />
                        <Button type="submit" disabled={generateForm.processing}>
                            <CalendarPlus className="mr-1.5 h-4 w-4" />
                            {locale === 'bn' ? 'ইনভয়েস তৈরি করুন' : 'Generate Monthly'}
                        </Button>
                    </form>
                </div>

                {/* 5-Card KPI Bar */}
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                    {kpis.map((kpi) => (
                        <button
                            key={kpi.key}
                            type="button"
                            onClick={() => router.get(invoicesIndex().url, { status: kpi.key, search }, { preserveState: true })}
                            className={`minimal-card p-4 text-left transition ${
                                filters.status === kpi.key ? 'ring-2 ring-primary' : ''
                            }`}
                        >
                            <p className="text-xs font-medium text-muted-foreground">{kpi.label}</p>
                            <p className="mt-1 text-xl font-bold">৳{kpi.amount.toLocaleString()}</p>
                            <p className="mt-0.5 text-xs text-muted-foreground">
                                {kpi.count} {locale === 'bn' ? 'টি ইনভয়েস' : 'invoices'}
                            </p>
                        </button>
                    ))}
                </div>

                {/* Search */}
                <div className="minimal-card p-4">
                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            router.get(invoicesIndex().url, { status: filters.status, search }, { preserveState: true });
                        }}
                        className="flex flex-wrap items-center gap-3"
                    >
                        <div className="relative flex-1 min-w-[220px]">
                            <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                            <Input
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder={locale === 'bn' ? 'ইনভয়েস নং বা শিক্ষার্থীর নাম...' : 'Search invoice # or student...'}
                                className="pl-9"
                            />
                        </div>
                        <Button type="submit" variant="secondary">
                            {t('common.search', 'Search')}
                        </Button>
                    </form>
                </div>

                {/* Table */}
                <div className="minimal-card overflow-x-auto">
                    <table className="w-full text-left text-sm">
                        <thead className="border-b bg-muted/40 text-xs uppercase text-muted-foreground">
                            <tr>
                                <th className="px-4 py-3">{locale === 'bn' ? 'ইনভয়েস' : 'Invoice'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'শিক্ষার্থী' : 'Student'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'মাস' : 'Period'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'মোট' : 'Total'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'জমা' : 'Paid'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'বকেয়া' : 'Due'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'অবস্থা' : 'Status'}</th>
                                <th className="px-4 py-3 text-right">{locale === 'bn' ? 'অ্যাকশন' : 'Actions'}</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y">
                            {invoices.data.length === 0 ? (
                                <tr>
                                    <td colSpan={8} className="px-4 py-8 text-center text-muted-foreground">
                                        {locale === 'bn' ? 'কোনো ইনভয়েস পাওয়া যায়নি।' : 'No invoices found.'}
                                    </td>
                                </tr>
                            ) : (
                                invoices.data.map((inv) => (
                                    <tr key={inv.id} className="hover:bg-muted/30">
                                        <td className="px-4 py-3 font-medium">
                                            <Link href={invoiceShow(inv.id).url} className="flex items-center gap-1.5 text-primary hover:underline">
                                                <FileText className="h-4 w-4" />
                                                {inv.invoice_number}
                                            </Link>
                                        </td>
                                        <td className="px-4 py-3">
                                            <div className="font-medium">{localized(inv.student, 'name')}</div>
                                            <div className="text-xs text-muted-foreground">{inv.student?.student_code}</div>
                                        </td>
                                        <td className="px-4 py-3 text-muted-foreground">
                                            {inv.billing_month && inv.billing_year ? `${inv.billing_month}/${inv.billing_year}` : inv.invoice_date}
                                        </td>
                                        <td className="px-4 py-3 font-medium">৳{Number(inv.total_amount).toLocaleString()}</td>
                                        <td className="px-4 py-3 text-emerald-600">৳{Number(inv.paid_amount).toLocaleString()}</td>
                                        <td className="px-4 py-3 font-semibold text-rose-600">৳{Number(inv.due_amount).toLocaleString()}</td>
                                        <td className="px-4 py-3">
                                            <span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${statusBadge[inv.status] ?? ''}`}>
                                                {inv.status}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <div className="flex justify-end gap-2">
                                                {Number(inv.due_amount) > 0 && (
                                                    <Button size="sm" onClick={() => openQuickPay(inv)}>
                                                        <Wallet className="mr-1 h-3.5 w-3.5" />
                                                        {locale === 'bn' ? 'পেমেন্ট' : 'Pay'}
                                                    </Button>
                                                )}
                                                <Button size="sm" variant="outline" asChild>
                                                    <Link href={invoiceShow(inv.id).url}>
                                                        <Eye className="h-3.5 w-3.5" />
                                                    </Link>
                                                </Button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Quick Payment Modal */}
            {payingInvoice && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
                    <div className="minimal-card w-full max-w-md bg-background p-6 shadow-xl">
                        <h3 className="text-lg font-semibold">
                            {locale === 'bn' ? 'ম্যানুয়াল পেমেন্ট গ্রহণ' : 'Record Manual Payment'} — {payingInvoice.invoice_number}
                        </h3>
                        <p className="mt-1 text-xs text-muted-foreground">
                            {localized(payingInvoice.student, 'name')} · {locale === 'bn' ? 'বকেয়া' : 'Due'}: ৳{Number(payingInvoice.due_amount).toLocaleString()}
                        </p>

                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                payForm.submit(InvoiceController.recordPayment(payingInvoice.id), {
                                    onSuccess: () => setPayingInvoice(null),
                                });
                            }}
                            className="mt-4 space-y-4"
                        >
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'জমার পরিমাণ (৳)' : 'Amount (BDT)'}</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.5">
                                    <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"
                                        required
                                    >
                                        {paymentMethods.map((pm) => (
                                            <option key={pm.id} value={pm.id}>
                                                {localized(pm, 'name')}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                                <div className="space-y-1.5">
                                    <Label>{locale === 'bn' ? 'তারিখ' : 'Date'}</Label>
                                    <Input
                                        type="date"
                                        value={payForm.data.payment_date}
                                        onChange={(e) => payForm.setData('payment_date', e.target.value)}
                                        required
                                    />
                                </div>
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'ট্রানজেকশন রেফারেন্স (ঐচ্ছিক)' : 'Transaction Reference (Optional)'}</Label>
                                <Input
                                    value={payForm.data.transaction_reference}
                                    onChange={(e) => payForm.setData('transaction_reference', e.target.value)}
                                    placeholder="bKash / Nagad TrxID"
                                />
                            </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 rounded border-input accent-primary"
                                />
                                <span>
                                    {locale === 'bn'
                                        ? 'অভিভাবককে হোয়াটসঅ্যাপ রসিদ পাঠান'
                                        : 'Send WhatsApp confirmation to guardian'}
                                </span>
                            </label>
                            <div className="flex justify-end gap-2 pt-2">
                                <Button type="button" variant="outline" onClick={() => setPayingInvoice(null)}>
                                    {locale === 'bn' ? 'বাতিল' : 'Cancel'}
                                </Button>
                                <Button type="submit" disabled={payForm.processing}>
                                    {locale === 'bn' ? 'পেমেন্ট নিশ্চিত করুন' : 'Confirm Payment'}
                                </Button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </>
    );
}
