import { Head, useForm } from '@inertiajs/react';
import StudentController from '@/actions/App/Http/Controllers/StudentController';
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 { dashboard } from '@/routes';
import { create as createStudent, index as studentsIndex } from '@/routes/students';

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

type ClassOption = OptionItem & { department_id: number; level: number };

type FeeStructureOption = {
    id: number;
    amount: string;
    fee_category?: { name_bn: string; name_en: string | null; frequency: string } | null;
};

export default function StudentCreate({
    sessions,
    departments,
    classes,
    feeStructures,
}: {
    sessions: OptionItem[];
    departments: OptionItem[];
    classes: ClassOption[];
    feeStructures: FeeStructureOption[];
}) {
    const { locale, t, localized } = useI18n();

    const defaultDeptId = departments[0]?.id ? String(departments[0].id) : '';
    const defaultClassId = classes.find((c) => String(c.department_id) === defaultDeptId)?.id
        ? String(classes.find((c) => String(c.department_id) === defaultDeptId)?.id)
        : '';

    const form = useForm({
        name_bn: '',
        name_en: '',
        father_name_bn: '',
        father_name_en: '',
        guardian_phone: '',
        whatsapp_number: '',
        address_bn: '',
        dob: '',
        gender: 'male',
        admission_date: new Date().toISOString().slice(0, 10),
        academic_session_id: sessions[0]?.id ? String(sessions[0].id) : '',
        department_id: defaultDeptId,
        academic_class_id: defaultClassId,
        roll_no: '',
        fee_structure_ids: feeStructures.map((f) => f.id),
    });

    const filteredClasses = classes.filter((c) => String(c.department_id) === form.data.department_id);

    const toggleFeeStructure = (id: number): void => {
        const exists = form.data.fee_structure_ids.includes(id);
        form.setData(
            'fee_structure_ids',
            exists ? form.data.fee_structure_ids.filter((item) => item !== id) : [...form.data.fee_structure_ids, id],
        );
    };

    return (
        <>
            <Head title={locale === 'bn' ? 'নতুন শিক্ষার্থী ভর্তি' : 'New Student Admission'} />
            <div className="flex w-full flex-1 flex-col gap-6 p-4 md:p-6">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight text-foreground">
                        {locale === 'bn' ? 'নতুন শিক্ষার্থী ভর্তি' : 'Create a New Student'}
                    </h1>
                    <p className="text-sm text-muted-foreground">
                        {locale === 'bn'
                            ? 'শিক্ষার্থীর তথ্য, শ্রেণি ও নির্ধারিত ফি খাত নির্বাচন করুন'
                            : 'Enter student profile, enrollment placement, and assigned fee structures'}
                    </p>
                </div>

                <form
                    onSubmit={(e) => {
                        e.preventDefault();
                        form.post(StudentController.store.url());
                    }}
                    className="grid gap-6 lg:grid-cols-3"
                >
                    {/* Left Card (1/3 — Enrollment & Fee Assignment) */}
                    <div className="minimal-card space-y-5 p-6">
                        <h2 className="text-base font-bold">
                            {locale === 'bn' ? 'একাডেমিক ও ফি নির্ধারণ' : 'Enrollment & Fees'}
                        </h2>
                        <div className="space-y-1.5">
                            <Label>{t('nav.sessions', 'Academic Session')}</Label>
                            <select
                                value={form.data.academic_session_id}
                                onChange={(e) => form.setData('academic_session_id', e.target.value)}
                                className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                            >
                                {sessions.map((s) => (
                                    <option key={s.id} value={s.id}>{localized(s, 'name')}</option>
                                ))}
                            </select>
                        </div>

                        <div className="space-y-1.5">
                            <Label>{t('nav.departments', 'Department')}</Label>
                            <select
                                value={form.data.department_id}
                                onChange={(e) => {
                                    const deptId = e.target.value;
                                    const firstClass = classes.find((c) => String(c.department_id) === deptId);
                                    form.setData((prev) => ({
                                        ...prev,
                                        department_id: deptId,
                                        academic_class_id: firstClass ? String(firstClass.id) : '',
                                    }));
                                }}
                                className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                            >
                                {departments.map((d) => (
                                    <option key={d.id} value={d.id}>{localized(d, 'name')}</option>
                                ))}
                            </select>
                        </div>

                        <div className="space-y-1.5">
                            <Label>{t('nav.classes', 'Class')}</Label>
                            <select
                                value={form.data.academic_class_id}
                                onChange={(e) => form.setData('academic_class_id', e.target.value)}
                                className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                            >
                                {filteredClasses.map((c) => (
                                    <option key={c.id} value={c.id}>{localized(c, 'name')}</option>
                                ))}
                            </select>
                        </div>

                        <div className="grid grid-cols-2 gap-3">
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'রোল নং' : 'Roll No'}</Label>
                                <Input value={form.data.roll_no} onChange={(e) => form.setData('roll_no', e.target.value)} />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'ভর্তির তারিখ' : 'Admission Date'}</Label>
                                <Input type="date" value={form.data.admission_date} onChange={(e) => form.setData('admission_date', e.target.value)} required />
                            </div>
                        </div>

                        <div className="space-y-2 pt-2">
                            <Label>{t('nav.fee_categories', 'Assigned Fees')}</Label>
                            <div className="space-y-2 rounded-xl border border-border p-3">
                                {feeStructures.map((fs) => (
                                    <label key={fs.id} className="flex items-center justify-between text-sm">
                                        <span className="flex items-center gap-2">
                                            <input
                                                type="checkbox"
                                                checked={form.data.fee_structure_ids.includes(fs.id)}
                                                onChange={() => toggleFeeStructure(fs.id)}
                                            />
                                            <span>{localized(fs.fee_category, 'name')}</span>
                                        </span>
                                        <span className="font-semibold tabular-nums">৳{Number(fs.amount)}</span>
                                    </label>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Right Card (2/3 — Student & Guardian Info) */}
                    <div className="minimal-card flex flex-col justify-between gap-6 p-6 lg:col-span-2">
                        <div className="grid gap-4 sm:grid-cols-2">
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'শিক্ষার্থীর নাম (বাংলা) *' : 'Student Name (Bangla) *'}</Label>
                                <Input value={form.data.name_bn} onChange={(e) => form.setData('name_bn', e.target.value)} required />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'শিক্ষার্থীর নাম (ইংরেজি)' : 'Student Name (English)'}</Label>
                                <Input value={form.data.name_en} onChange={(e) => form.setData('name_en', e.target.value)} />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'পিতার নাম (বাংলা)' : 'Father Name (Bangla)'}</Label>
                                <Input value={form.data.father_name_bn} onChange={(e) => form.setData('father_name_bn', e.target.value)} />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'পিতার নাম (ইংরেজি)' : 'Father Name (English)'}</Label>
                                <Input value={form.data.father_name_en} onChange={(e) => form.setData('father_name_en', e.target.value)} />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'অভিভাবকের মোবাইল *' : 'Guardian Phone *'}</Label>
                                <Input value={form.data.guardian_phone} onChange={(e) => form.setData('guardian_phone', e.target.value)} required />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'WhatsApp নম্বর' : 'WhatsApp Number'}</Label>
                                <Input value={form.data.whatsapp_number} onChange={(e) => form.setData('whatsapp_number', e.target.value)} />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'জন্ম তারিখ' : 'Date of Birth'}</Label>
                                <Input type="date" value={form.data.dob} onChange={(e) => form.setData('dob', e.target.value)} />
                            </div>
                            <div className="space-y-1.5">
                                <Label>{locale === 'bn' ? 'লিঙ্গ' : 'Gender'}</Label>
                                <select
                                    value={form.data.gender}
                                    onChange={(e) => form.setData('gender', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                                >
                                    <option value="male">{locale === 'bn' ? 'ছাত্র (পুরুষ)' : 'Male'}</option>
                                    <option value="female">{locale === 'bn' ? 'ছাত্রী (মহিলা)' : 'Female'}</option>
                                </select>
                            </div>
                            <div className="space-y-1.5 sm:col-span-2">
                                <Label>{locale === 'bn' ? 'ঠিকানা (বাংলা)' : 'Address (Bangla)'}</Label>
                                <Input value={form.data.address_bn} onChange={(e) => form.setData('address_bn', e.target.value)} />
                            </div>
                        </div>

                        <div className="flex justify-end">
                            <Button type="submit" disabled={form.processing}>
                                {locale === 'bn' ? 'ভর্তি সম্পন্ন করুন' : 'Create Student'}
                            </Button>
                        </div>
                    </div>
                </form>
            </div>
        </>
    );
}

StudentCreate.layout = {
    breadcrumbs: [
        { title: 'Dashboard', href: dashboard() },
        { title: 'Students', href: studentsIndex() },
        { title: 'New Admission', href: createStudent() },
    ],
};
