import { Head, router, useForm, usePage } from '@inertiajs/react';
import { Banknote, Layers, Pencil, Plus, Trash2 } from 'lucide-react';
import { useState } from 'react';
import FeeController from '@/actions/App/Http/Controllers/FeeController';
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 FeeCategoryItem = {
    id: number;
    name_bn: string;
    name_en: string | null;
    frequency: string;
    billing_basis: string;
    is_active: boolean;
};

type FeeStructureItem = {
    id: number;
    fee_category_id: number;
    department_id: number | null;
    academic_class_id: number | null;
    amount: string | number;
    effective_from: string;
    fee_category?: { name_bn: string; name_en: string | null; frequency: string } | null;
    department?: { name_bn: string; name_en: string | null } | null;
    academic_class?: { name_bn: string; name_en: string | null } | null;
};

type DeptItem = { id: number; name_bn: string; name_en: string | null };
type ClassItem = { id: number; department_id: number; name_bn: string; name_en: string | null };

export default function FeesIndex({
    categories,
    structures,
    departments,
    classes,
}: {
    categories: FeeCategoryItem[];
    structures: FeeStructureItem[];
    departments: DeptItem[];
    classes: ClassItem[];
}) {
    const { locale, t, localized } = useI18n();
    const { errors } = usePage<{ errors: Record<string, string> }>().props;
    const [editingCategoryId, setEditingCategoryId] = useState<number | null>(null);
    const [editingStructureId, setEditingStructureId] = useState<number | null>(null);

    const categoryForm = useForm({
        name_bn: '',
        name_en: '',
        frequency: 'monthly',
        billing_basis: 'fixed',
    });

    const structureForm = useForm({
        fee_category_id: categories[0]?.id ? String(categories[0].id) : '',
        department_id: '',
        academic_class_id: '',
        amount: '',
        effective_from: new Date().toISOString().slice(0, 10),
    });

    const filteredClasses = structureForm.data.department_id
        ? classes.filter((c) => String(c.department_id) === structureForm.data.department_id)
        : classes;

    return (
        <>
            <Head title={t('nav.fee_categories', 'Fee Categories & Structures')} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">
                        {locale === 'bn' ? 'ফি ক্যাটাগরি ও স্ট্রাকচার' : 'Fee Categories & Structures'}
                    </h1>
                    <p className="text-sm text-muted-foreground">
                        {locale === 'bn'
                            ? 'বিভাগ ও শ্রেণি অনুযায়ী মাসিক ও এককালীন ফি নির্ধারণ করুন।'
                            : 'Configure recurring monthly and one-time fees by department and class.'}
                    </p>
                </div>

                {errors.delete && (
                    <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-2.5 text-sm text-destructive">
                        {errors.delete}
                    </div>
                )}

                <div className="grid gap-6 lg:grid-cols-2">
                    <div className="minimal-card p-6">
                        <div className="mb-4 flex items-center gap-2">
                            <Layers className="h-5 w-5 text-primary" />
                            <h2 className="text-base font-semibold">
                                {editingCategoryId !== null
                                    ? locale === 'bn'
                                        ? 'ফি ক্যাটাগরি সম্পাদনা'
                                        : 'Edit Fee Category'
                                    : locale === 'bn'
                                      ? 'নতুন ফি ক্যাটাগরি'
                                      : 'New Fee Category'}
                            </h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                if (editingCategoryId !== null) {
                                    categoryForm.put(FeeController.updateCategory.url(editingCategoryId), {
                                        onSuccess: () => {
                                            setEditingCategoryId(null);
                                            categoryForm.reset('name_bn', 'name_en');
                                        },
                                    });
                                } else {
                                    categoryForm.submit(FeeController.storeCategory(), {
                                        onSuccess: () => categoryForm.reset('name_bn', 'name_en'),
                                    });
                                }
                            }}
                            className="grid gap-4 sm:grid-cols-2"
                        >
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'নাম (বাংলা)' : 'Name (Bangla)'}</Label>
                                <Input
                                    value={categoryForm.data.name_bn}
                                    onChange={(e) => categoryForm.setData('name_bn', e.target.value)}
                                    placeholder="মাসিক বেতন"
                                    required
                                />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'নাম (ইংরেজি)' : 'Name (English)'}</Label>
                                <Input
                                    value={categoryForm.data.name_en}
                                    onChange={(e) => categoryForm.setData('name_en', e.target.value)}
                                    placeholder="Monthly Tuition"
                                />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'সময়কাল' : 'Frequency'}</Label>
                                <select
                                    value={categoryForm.data.frequency}
                                    onChange={(e) => categoryForm.setData('frequency', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                                >
                                    <option value="monthly">{locale === 'bn' ? 'মাসিক' : 'Monthly'}</option>
                                    <option value="one_time">{locale === 'bn' ? 'এককালীন' : 'One Time'}</option>
                                    <option value="annual">{locale === 'bn' ? 'বার্ষিক' : 'Annual'}</option>
                                    <option value="custom">{locale === 'bn' ? 'কাস্টম' : 'Custom'}</option>
                                </select>
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'বিলিং ধরন' : 'Billing Basis'}</Label>
                                <select
                                    value={categoryForm.data.billing_basis}
                                    onChange={(e) => categoryForm.setData('billing_basis', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                                >
                                    <option value="fixed">
                                        {locale === 'bn' ? 'নির্ধারিত (ফিক্সড)' : 'Fixed'}
                                    </option>
                                    <option value="attendance">
                                        {locale === 'bn' ? 'উপস্থিতি ভিত্তিক' : 'Attendance Based'}
                                    </option>
                                    <option value="manual">
                                        {locale === 'bn' ? 'ম্যানুয়াল চার্জ' : 'Manual Charge'}
                                    </option>
                                </select>
                            </div>
                            <div className="flex gap-2 sm:col-span-2">
                                <Button type="submit" disabled={categoryForm.processing}>
                                    <Plus className="mr-1.5 h-4 w-4" />
                                    {editingCategoryId !== null
                                        ? locale === 'bn'
                                            ? 'আপডেট করুন'
                                            : 'Update Category'
                                        : locale === 'bn'
                                          ? 'ক্যাটাগরি যোগ করুন'
                                          : 'Add Category'}
                                </Button>
                                {editingCategoryId !== null && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={() => {
                                            setEditingCategoryId(null);
                                            categoryForm.reset('name_bn', 'name_en');
                                        }}
                                    >
                                        {t('common.cancel', 'Cancel')}
                                    </Button>
                                )}
                            </div>
                        </form>

                        <div className="mt-6 space-y-2 border-t pt-4">
                            {categories.map((cat) => (
                                <div key={cat.id} className="flex items-center justify-between gap-2 rounded-lg border px-3 py-2 text-sm">
                                    <div className="flex items-center gap-2">
                                        <span className="font-medium">{localized(cat, 'name')}</span>
                                        <span className="rounded bg-muted px-2 py-0.5 text-xs uppercase text-muted-foreground">
                                            {cat.frequency}
                                        </span>
                                    </div>
                                    <div className="inline-flex items-center gap-1">
                                        <Button
                                            type="button"
                                            size="icon"
                                            variant="ghost"
                                            title={locale === 'bn' ? 'সম্পাদনা' : 'Edit'}
                                            onClick={() => {
                                                setEditingCategoryId(cat.id);
                                                categoryForm.setData({
                                                    name_bn: cat.name_bn,
                                                    name_en: cat.name_en ?? '',
                                                    frequency: cat.frequency,
                                                    billing_basis: cat.billing_basis,
                                                });
                                            }}
                                        >
                                            <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 category?')) {
                                                    router.delete(FeeController.destroyCategory.url(cat.id));
                                                }
                                            }}
                                        >
                                            <Trash2 className="size-4" />
                                        </Button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className="minimal-card p-6">
                        <div className="mb-4 flex items-center gap-2">
                            <Banknote className="h-5 w-5 text-primary" />
                            <h2 className="text-base font-semibold">
                                {editingStructureId !== null
                                    ? locale === 'bn'
                                        ? 'ফি স্ট্রাকচার সম্পাদনা'
                                        : 'Edit Fee Structure'
                                    : locale === 'bn'
                                      ? 'ফি স্ট্রাকচার নির্ধারণ'
                                      : 'Set Fee Structure'}
                            </h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                if (editingStructureId !== null) {
                                    structureForm.put(FeeController.updateStructure.url(editingStructureId), {
                                        onSuccess: () => {
                                            setEditingStructureId(null);
                                            structureForm.reset('amount');
                                        },
                                    });
                                } else {
                                    structureForm.submit(FeeController.storeStructure(), {
                                        onSuccess: () => structureForm.reset('amount'),
                                    });
                                }
                            }}
                            className="grid gap-4 sm:grid-cols-2"
                        >
                            <div className="space-y-1.5 sm:col-span-2">
                                <Label>{locale === 'bn' ? 'ফি ক্যাটাগরি' : 'Fee Category'}</Label>
                                <select
                                    value={structureForm.data.fee_category_id}
                                    onChange={(e) => structureForm.setData('fee_category_id', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                                    required
                                >
                                    <option value="">{locale === 'bn' ? 'নির্বাচন করুন' : 'Select category'}</option>
                                    {categories.map((c) => (
                                        <option key={c.id} value={c.id}>
                                            {localized(c, 'name')}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'বিভাগ (ঐচ্ছিক)' : 'Department (Optional)'}</Label>
                                <select
                                    value={structureForm.data.department_id}
                                    onChange={(e) => {
                                        structureForm.setData('department_id', e.target.value);
                                        structureForm.setData('academic_class_id', '');
                                    }}
                                    className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                                >
                                    <option value="">{locale === 'bn' ? 'সকল বিভাগ' : 'All Departments'}</option>
                                    {departments.map((d) => (
                                        <option key={d.id} value={d.id}>
                                            {localized(d, 'name')}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'শ্রেণি (ঐচ্ছিক)' : 'Class (Optional)'}</Label>
                                <select
                                    value={structureForm.data.academic_class_id}
                                    onChange={(e) => structureForm.setData('academic_class_id', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                                >
                                    <option value="">{locale === 'bn' ? 'সকল শ্রেণি' : 'All Classes'}</option>
                                    {filteredClasses.map((c) => (
                                        <option key={c.id} value={c.id}>
                                            {localized(c, 'name')}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'পরিমাণ (৳)' : 'Amount (BDT)'}</Label>
                                <Input
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    value={structureForm.data.amount}
                                    onChange={(e) => structureForm.setData('amount', e.target.value)}
                                    required
                                />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'কার্যকর তারিখ' : 'Effective From'}</Label>
                                <Input
                                    type="date"
                                    value={structureForm.data.effective_from}
                                    onChange={(e) => structureForm.setData('effective_from', e.target.value)}
                                    required
                                />
                            </div>
                            <div className="flex gap-2 sm:col-span-2">
                                <Button type="submit" disabled={structureForm.processing}>
                                    <Plus className="mr-1.5 h-4 w-4" />
                                    {editingStructureId !== null
                                        ? locale === 'bn'
                                            ? 'আপডেট করুন'
                                            : 'Update Structure'
                                        : locale === 'bn'
                                          ? 'স্ট্রাকচার সংরক্ষণ করুন'
                                          : 'Save Structure'}
                                </Button>
                                {editingStructureId !== null && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={() => {
                                            setEditingStructureId(null);
                                            structureForm.reset('amount');
                                        }}
                                    >
                                        {t('common.cancel', 'Cancel')}
                                    </Button>
                                )}
                            </div>
                        </form>

                        <div className="mt-6 space-y-2 border-t pt-4">
                            {structures.map((st) => (
                                <div key={st.id} className="flex items-center justify-between gap-2 rounded-lg border px-3 py-2 text-sm">
                                    <div>
                                        <p className="font-medium">{localized(st.fee_category, 'name')}</p>
                                        <p className="text-xs text-muted-foreground">
                                            {st.department ? localized(st.department, 'name') : locale === 'bn' ? 'সকল বিভাগ' : 'All Depts'} ·{' '}
                                            {st.academic_class ? localized(st.academic_class, 'name') : locale === 'bn' ? 'সকল শ্রেণি' : 'All Classes'}
                                        </p>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <span className="font-semibold text-primary">৳{Number(st.amount).toLocaleString()}</span>
                                        <Button
                                            type="button"
                                            size="icon"
                                            variant="ghost"
                                            title={locale === 'bn' ? 'সম্পাদনা' : 'Edit'}
                                            onClick={() => {
                                                setEditingStructureId(st.id);
                                                structureForm.setData({
                                                    fee_category_id: String(st.fee_category_id),
                                                    department_id: st.department_id ? String(st.department_id) : '',
                                                    academic_class_id: st.academic_class_id ? String(st.academic_class_id) : '',
                                                    amount: String(st.amount),
                                                    effective_from: st.effective_from.slice(0, 10),
                                                });
                                            }}
                                        >
                                            <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 structure?')) {
                                                    router.delete(FeeController.destroyStructure.url(st.id));
                                                }
                                            }}
                                        >
                                            <Trash2 className="size-4" />
                                        </Button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}
