import { Head, router, useForm } from '@inertiajs/react';
import { Pencil, Plus, Receipt, Trash2 } from 'lucide-react';
import { useState } from 'react';
import ExpenseController from '@/actions/App/Http/Controllers/ExpenseController';
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 CategoryItem = { id: number; name_bn: string; name_en: string | null };
type FundItem = { id: number; name_bn: string; name_en: string | null };
type MethodItem = { id: number; name_bn: string; name_en: string | null };

type ExpenseRow = {
    id: number;
    expense_category_id: number;
    donation_fund_id: number | null;
    payment_method_id: number;
    title_bn: string;
    title_en: string | null;
    amount: string | number;
    expense_date: string;
    remarks: string | null;
    category?: { name_bn: string; name_en: string | null } | null;
    donation_fund?: { name_bn: string; name_en: string | null } | null;
    payment_method?: { name_bn: string; name_en: string | null } | null;
};

export default function ExpensesIndex({
    categories,
    funds,
    paymentMethods,
    expenses,
    totalExpense,
}: {
    categories: CategoryItem[];
    funds: FundItem[];
    paymentMethods: MethodItem[];
    expenses: { data: ExpenseRow[] };
    totalExpense: number;
}) {
    const { locale, t, localized } = useI18n();
    const [editingExpenseId, setEditingExpenseId] = useState<number | null>(null);

    const catForm = useForm({ name_bn: '', name_en: '' });
    const expForm = useForm({
        expense_category_id: categories[0]?.id ? String(categories[0].id) : '',
        donation_fund_id: '',
        title_bn: '',
        title_en: '',
        amount: '',
        expense_date: new Date().toISOString().slice(0, 10),
        payment_method_id: paymentMethods[0]?.id ? String(paymentMethods[0].id) : '',
        remarks: '',
    });

    return (
        <>
            <Head title={t('nav.expenses', 'Expenses')} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight">{t('nav.expenses', 'Expenses')}</h1>
                        <p className="text-sm text-muted-foreground">
                            {locale === 'bn' ? 'মাদ্রাসার দৈনন্দিন ও ফান্ডভিত্তিক ব্যয় লিপিবদ্ধ করুন।' : 'Record daily and fund-specific expenses.'}
                        </p>
                    </div>
                    <div className="minimal-card px-5 py-3 text-right">
                        <p className="text-xs text-muted-foreground">{locale === 'bn' ? 'মোট ব্যয়' : 'Total Expense'}</p>
                        <p className="text-xl font-bold text-rose-600">৳{totalExpense.toLocaleString()}</p>
                    </div>
                </div>

                <div className="grid gap-6 lg:grid-cols-3">
                    <div className="minimal-card p-6">
                        <h2 className="mb-4 font-semibold">{locale === 'bn' ? 'ব্যয়ের খাত যোগ করুন' : 'Add Expense Category'}</h2>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                catForm.submit(ExpenseController.storeCategory(), {
                                    onSuccess: () => catForm.reset('name_bn', 'name_en'),
                                });
                            }}
                            className="space-y-3"
                        >
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'খাতের নাম (বাংলা)' : 'Category (Bangla)'}</Label>
                                <Input value={catForm.data.name_bn} onChange={(e) => catForm.setData('name_bn', e.target.value)} required />
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'খাতের নাম (ইংরেজি)' : 'Category (English)'}</Label>
                                <Input value={catForm.data.name_en} onChange={(e) => catForm.setData('name_en', e.target.value)} />
                            </div>
                            <Button type="submit" disabled={catForm.processing} className="w-full">
                                <Plus className="mr-1.5 h-4 w-4" />
                                {locale === 'bn' ? 'খাত যোগ করুন' : 'Save Category'}
                            </Button>
                        </form>
                    </div>

                    <div className="minimal-card p-6 lg:col-span-2">
                        <div className="mb-4 flex items-center gap-2">
                            <Receipt className="h-5 w-5 text-primary" />
                            <h2 className="font-semibold">
                                {editingExpenseId !== null
                                    ? locale === 'bn'
                                        ? 'ব্যয় সম্পাদনা'
                                        : 'Edit Expense'
                                    : locale === 'bn'
                                      ? 'নতুন ব্যয় লিপিবদ্ধ'
                                      : 'Record New Expense'}
                            </h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                if (editingExpenseId !== null) {
                                    expForm.put(ExpenseController.update.url(editingExpenseId), {
                                        onSuccess: () => {
                                            setEditingExpenseId(null);
                                            expForm.reset('title_bn', 'title_en', 'amount', 'remarks');
                                        },
                                    });
                                } else {
                                    expForm.submit(ExpenseController.store(), {
                                        onSuccess: () => expForm.reset('title_bn', 'title_en', 'amount', 'remarks'),
                                    });
                                }
                            }}
                            className="grid gap-4 sm:grid-cols-2"
                        >
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'খাত' : 'Category'}</Label>
                                <select
                                    value={expForm.data.expense_category_id}
                                    onChange={(e) => expForm.setData('expense_category_id', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                    required
                                >
                                    <option value="">{locale === 'bn' ? 'নির্বাচন করুন' : 'Select'}</option>
                                    {categories.map((c) => (
                                        <option key={c.id} value={c.id}>
                                            {localized(c, 'name')}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'ফান্ড (ঐচ্ছিক)' : 'Fund (Optional)'}</Label>
                                <select
                                    value={expForm.data.donation_fund_id}
                                    onChange={(e) => expForm.setData('donation_fund_id', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                >
                                    <option value="">{locale === 'bn' ? 'সাধারণ তহবিল' : 'General Fund'}</option>
                                    {funds.map((f) => (
                                        <option key={f.id} value={f.id}>
                                            {localized(f, 'name')}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="space-y-1 sm:col-span-2">
                                <Label>{locale === 'bn' ? 'বিবরণ (বাংলা)' : 'Title (Bangla)'}</Label>
                                <Input value={expForm.data.title_bn} onChange={(e) => expForm.setData('title_bn', e.target.value)} required />
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'পরিমাণ (৳)' : 'Amount'}</Label>
                                <Input
                                    type="number"
                                    step="0.01"
                                    min="0.01"
                                    value={expForm.data.amount}
                                    onChange={(e) => expForm.setData('amount', e.target.value)}
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'তারিখ ও মাধ্যম' : 'Date & Method'}</Label>
                                <div className="grid grid-cols-2 gap-2">
                                    <Input
                                        type="date"
                                        value={expForm.data.expense_date}
                                        onChange={(e) => expForm.setData('expense_date', e.target.value)}
                                        required
                                    />
                                    <select
                                        value={expForm.data.payment_method_id}
                                        onChange={(e) => expForm.setData('payment_method_id', e.target.value)}
                                        className="h-9 rounded-md border border-input bg-background px-2 text-sm"
                                    >
                                        {paymentMethods.map((pm) => (
                                            <option key={pm.id} value={pm.id}>
                                                {localized(pm, 'name')}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                            </div>
                            <div className="flex gap-2 sm:col-span-2">
                                <Button type="submit" disabled={expForm.processing}>
                                    <Plus className="mr-1.5 h-4 w-4" />
                                    {editingExpenseId !== null
                                        ? locale === 'bn'
                                            ? 'আপডেট করুন'
                                            : 'Update Expense'
                                        : locale === 'bn'
                                          ? 'ব্যয় সংরক্ষণ করুন'
                                          : 'Save Expense'}
                                </Button>
                                {editingExpenseId !== null && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={() => {
                                            setEditingExpenseId(null);
                                            expForm.reset('title_bn', 'title_en', 'amount', 'remarks');
                                        }}
                                    >
                                        {t('common.cancel', 'Cancel')}
                                    </Button>
                                )}
                            </div>
                        </form>
                    </div>
                </div>

                <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' ? 'তারিখ' : 'Date'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'বিবরণ' : 'Title'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'খাত' : 'Category'}</th>
                                <th className="px-4 py-3">{locale === 'bn' ? 'ফান্ড' : 'Fund'}</th>
                                <th className="px-4 py-3 text-right">{locale === 'bn' ? 'পরিমাণ' : 'Amount'}</th>
                                <th className="px-4 py-3 text-right">{locale === 'bn' ? 'অ্যাকশন' : 'Actions'}</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y">
                            {expenses.data.map((exp) => (
                                <tr key={exp.id}>
                                    <td className="px-4 py-3 text-muted-foreground">{exp.expense_date.slice(0, 10)}</td>
                                    <td className="px-4 py-3 font-medium">{localized(exp, 'title')}</td>
                                    <td className="px-4 py-3">{localized(exp.category, 'name')}</td>
                                    <td className="px-4 py-3">{exp.donation_fund ? localized(exp.donation_fund, 'name') : '—'}</td>
                                    <td className="px-4 py-3 text-right font-semibold text-rose-600">৳{Number(exp.amount).toLocaleString()}</td>
                                    <td className="px-4 py-3 text-right">
                                        <div className="inline-flex items-center gap-1">
                                            <Button
                                                type="button"
                                                size="icon"
                                                variant="ghost"
                                                title={locale === 'bn' ? 'সম্পাদনা' : 'Edit'}
                                                onClick={() => {
                                                    setEditingExpenseId(exp.id);
                                                    expForm.setData({
                                                        expense_category_id: String(exp.expense_category_id),
                                                        donation_fund_id: exp.donation_fund_id ? String(exp.donation_fund_id) : '',
                                                        title_bn: exp.title_bn,
                                                        title_en: exp.title_en ?? '',
                                                        amount: String(exp.amount),
                                                        expense_date: exp.expense_date.slice(0, 10),
                                                        payment_method_id: String(exp.payment_method_id),
                                                        remarks: exp.remarks ?? '',
                                                    });
                                                }}
                                            >
                                                <Pencil className="size-4" />
                                            </Button>
                                            <Button
                                                type="button"
                                                size="icon"
                                                variant="ghost"
                                                className="text-destructive hover:text-destructive"
                                                title={locale === 'bn' ? 'মুছে ফেলুন' : 'Delete'}
                                                onClick={() => {
                                                    if (confirm(locale === 'bn' ? 'আপনি কি নিশ্চিতভাবে এটি মুছে ফেলতে চান?' : 'Delete this expense?')) {
                                                        router.delete(ExpenseController.destroy.url(exp.id));
                                                    }
                                                }}
                                            >
                                                <Trash2 className="size-4" />
                                            </Button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}
