import { Head, Link, router } from '@inertiajs/react';
import { Eye, Plus, Search } from 'lucide-react';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useI18n } from '@/hooks/use-i18n';
import { dashboard } from '@/routes';
import { create as createStudent, index as studentsIndex, show as showStudent } from '@/routes/students';

type StudentRow = {
    id: number;
    student_code: string;
    name_bn: string;
    name_en: string | null;
    guardian_phone: string;
    status: string;
    current_enrollment?: {
        roll_no: string | null;
        department?: { name_bn: string; name_en: string | null } | null;
        academic_class?: { name_bn: string; name_en: string | null } | null;
        academic_session?: { name_bn: string; name_en: string | null } | null;
    } | null;
};

type PaginatedStudents = {
    data: StudentRow[];
    current_page: number;
    last_page: number;
    total: number;
};

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

const statusColors: Record<string, string> = {
    active: 'bg-[#22C55E]/15 text-[#118D57] dark:text-[#77ED8B]',
    graduated: 'bg-[#00B8D9]/15 text-[#006C9C] dark:text-[#61F3F3]',
    transferred: 'bg-[#FFAB00]/15 text-[#B76E00] dark:text-[#FFD666]',
};

export default function StudentsIndex({
    students,
    counts,
    departments,
    filters,
}: {
    students: PaginatedStudents;
    counts: Record<string, number>;
    departments: DepartmentOption[];
    filters: { status: string; department_id: number | null; search: string };
}) {
    const { locale, t, localized } = useI18n();
    const [search, setSearch] = useState(filters.search);

    const applyFilter = (next: Partial<typeof filters>): void => {
        router.get(
            studentsIndex.url(),
            {
                status: next.status ?? filters.status,
                department_id: next.department_id !== undefined ? next.department_id : filters.department_id,
                search: next.search !== undefined ? next.search : search,
            },
            { preserveState: true, replace: true },
        );
    };

    const statusTabs = [
        { key: 'all', label: locale === 'bn' ? 'সকল' : 'All', count: counts.all ?? 0 },
        { key: 'active', label: locale === 'bn' ? 'সক্রিয়' : 'Active', count: counts.active ?? 0 },
        { key: 'graduated', label: locale === 'bn' ? 'সম্পন্ন' : 'Graduated', count: counts.graduated ?? 0 },
        { key: 'transferred', label: locale === 'bn' ? 'টিসি/বিদায়' : 'Transferred', count: counts.transferred ?? 0 },
    ];

    return (
        <>
            <Head title={t('nav.students', 'Students')} />
            <div className="flex w-full flex-1 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 text-foreground">
                            {t('nav.students', 'Students')}
                        </h1>
                        <p className="text-sm text-muted-foreground">
                            {locale === 'bn'
                                ? 'মাদ্রাসার সকল শিক্ষার্থীর প্রোফাইল ও শ্রেণি তালিকা'
                                : 'Manage enrolled students across sessions and departments'}
                        </p>
                    </div>
                    <Button asChild>
                        <Link href={createStudent()}>
                            <Plus className="mr-1.5 size-4" />
                            {locale === 'bn' ? 'নতুন ভর্তি' : 'Add Student'}
                        </Link>
                    </Button>
                </div>

                <div className="minimal-card overflow-hidden">
                    {/* Status Tabs (Minimal User_List pattern) */}
                    <div className="flex flex-wrap gap-2 border-b border-border px-5 pt-4">
                        {statusTabs.map((item) => {
                            const active = filters.status === item.key;
                            return (
                                <button
                                    key={item.key}
                                    type="button"
                                    onClick={() => applyFilter({ status: item.key })}
                                    className={`inline-flex items-center gap-2 border-b-2 px-3 pb-3 text-sm font-semibold transition ${
                                        active
                                            ? 'border-primary text-primary'
                                            : 'border-transparent text-muted-foreground hover:text-foreground'
                                    }`}
                                >
                                    <span>{item.label}</span>
                                    <span className="rounded-md bg-muted px-2 py-0.5 text-xs tabular-nums">
                                        {item.count}
                                    </span>
                                </button>
                            );
                        })}
                    </div>

                    {/* Filter Toolbar */}
                    <div className="flex flex-col gap-3 border-b border-border p-4 md:flex-row md:items-center">
                        <select
                            value={filters.department_id ?? ''}
                            onChange={(e) =>
                                applyFilter({
                                    department_id: e.target.value ? Number(e.target.value) : null,
                                })
                            }
                            className="h-9 rounded-lg border border-input bg-background px-3 text-sm md:w-56"
                        >
                            <option value="">{locale === 'bn' ? 'সকল বিভাগ' : 'All Departments'}</option>
                            {departments.map((d) => (
                                <option key={d.id} value={d.id}>{localized(d, 'name')}</option>
                            ))}
                        </select>

                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                applyFilter({ search });
                            }}
                            className="relative flex-1"
                        >
                            <Search className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                            <Input
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder={locale === 'bn' ? 'নাম, কোড বা মোবাইল দিয়ে খুঁজুন...' : 'Search by name, code or phone...'}
                                className="pl-9"
                            />
                        </form>
                    </div>

                    {/* Data Table */}
                    <div className="overflow-x-auto">
                        <table className="w-full text-left text-sm">
                            <thead className="bg-muted/60 text-xs font-semibold text-muted-foreground">
                                <tr>
                                    <th className="px-5 py-3">{locale === 'bn' ? 'শিক্ষার্থী' : 'Student'}</th>
                                    <th className="px-5 py-3">{locale === 'bn' ? 'অভিভাবকের মোবাইল' : 'Guardian Phone'}</th>
                                    <th className="px-5 py-3">{t('nav.departments', 'Department')}</th>
                                    <th className="px-5 py-3">{t('nav.classes', 'Class')}</th>
                                    <th className="px-5 py-3">{t('common.status', 'Status')}</th>
                                    <th className="px-5 py-3 text-right">{locale === 'bn' ? 'অ্যাকশন' : 'Action'}</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border">
                                {students.data.length === 0 ? (
                                    <tr>
                                        <td colSpan={6} className="px-5 py-10 text-center text-muted-foreground">
                                            {locale === 'bn' ? 'কোনো শিক্ষার্থী পাওয়া যায়নি' : 'No students found'}
                                        </td>
                                    </tr>
                                ) : (
                                    students.data.map((student) => (
                                        <tr key={student.id} className="hover:bg-muted/30">
                                            <td className="px-5 py-3">
                                                <p className="font-semibold text-foreground">{localized(student, 'name')}</p>
                                                <p className="text-xs text-muted-foreground">{student.student_code}</p>
                                            </td>
                                            <td className="px-5 py-3 tabular-nums">{student.guardian_phone}</td>
                                            <td className="px-5 py-3 text-muted-foreground">
                                                {localized(student.current_enrollment?.department, 'name') || '—'}
                                            </td>
                                            <td className="px-5 py-3 text-muted-foreground">
                                                {localized(student.current_enrollment?.academic_class, 'name') || '—'}
                                            </td>
                                            <td className="px-5 py-3">
                                                <span
                                                    className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${
                                                        statusColors[student.status] ?? 'bg-muted text-muted-foreground'
                                                    }`}
                                                >
                                                    {student.status}
                                                </span>
                                            </td>
                                            <td className="px-5 py-3 text-right">
                                                <Button asChild size="sm" variant="ghost">
                                                    <Link href={showStudent(student.id)}>
                                                        <Eye className="size-4" />
                                                    </Link>
                                                </Button>
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </>
    );
}

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