import { Head, router } from '@inertiajs/react';
import { CalendarCheck, Save } from 'lucide-react';
import { useState } from 'react';
import AttendanceController from '@/actions/App/Http/Controllers/AttendanceController';
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 attendanceIndex } from '@/routes/attendance';

type ClassItem = { id: number; department_id: number; name_bn: string; name_en: string | null };
type SessionItem = { id: number; name_bn: string; name_en: string | null; is_current: boolean };

type EnrollmentRow = {
    id: number;
    student_id: number;
    academic_session_id: number;
    department_id: number;
    roll_no: string | null;
    student?: { id: number; student_code: string; name_bn: string; name_en: string | null } | null;
};

type RecentSession = {
    id: number;
    attendance_date: string;
    attendances_count: number;
    department?: { name_bn: string; name_en: string | null } | null;
    academic_class?: { name_bn: string; name_en: string | null } | null;
};

export default function AttendanceIndex({
    sessions,
    classes,
    enrollments,
    existingStatuses,
    recentSessions,
    filters,
}: {
    sessions: SessionItem[];
    classes: ClassItem[];
    enrollments: EnrollmentRow[];
    existingStatuses: Record<number, string>;
    recentSessions: RecentSession[];
    filters: { academic_class_id: number | null; date: string };
}) {
    const { locale, t, localized } = useI18n();
    const [classId, setClassId] = useState(filters.academic_class_id ? String(filters.academic_class_id) : '');
    const [date, setDate] = useState(filters.date);
    const [statuses, setStatuses] = useState<Record<number, string>>(existingStatuses);
    const [saving, setSaving] = useState(false);

    const loadStudents = () => {
        if (!classId) {
            return;
        }
        router.get(attendanceIndex().url, { academic_class_id: classId, date });
    };

    const getStatus = (studentId: number) => statuses[studentId] ?? existingStatuses[studentId] ?? 'present';

    const saveAttendance = () => {
        if (enrollments.length === 0) {
            return;
        }
        const first = enrollments[0];
        const fallbackSession = sessions.find((s) => s.is_current)?.id ?? sessions[0]?.id;
        setSaving(true);
        router.post(
            AttendanceController.store().url,
            {
                academic_session_id: first.academic_session_id || fallbackSession,
                department_id: first.department_id,
                academic_class_id: Number(classId),
                attendance_date: date,
                records: enrollments.map((e) => ({
                    student_id: e.student_id,
                    status: getStatus(e.student_id),
                })),
            },
            { onFinish: () => setSaving(false) },
        );
    };

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

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">{t('nav.attendance', 'Attendance')}</h1>
                    <p className="text-sm text-muted-foreground">
                        {locale === 'bn' ? 'শ্রেণি ও তারিখ অনুযায়ী দৈনিক হাজিরা নিন।' : 'Take daily class attendance by date.'}
                    </p>
                </div>

                <div className="minimal-card grid gap-4 p-6 md:grid-cols-3">
                    <div className="space-y-1.5">
                        <Label>{locale === 'bn' ? 'শ্রেণি' : 'Class'}</Label>
                        <select
                            value={classId}
                            onChange={(e) => setClassId(e.target.value)}
                            className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                        >
                            <option value="">{locale === 'bn' ? 'শ্রেণি নির্বাচন করুন' : 'Select class'}</option>
                            {classes.map((c) => (
                                <option key={c.id} value={c.id}>
                                    {localized(c, 'name')}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div className="space-y-1.5">
                        <Label>{locale === 'bn' ? 'তারিখ' : 'Date'}</Label>
                        <Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
                    </div>
                    <div className="flex items-end">
                        <Button type="button" onClick={loadStudents} className="w-full" variant="secondary">
                            <CalendarCheck className="mr-1.5 h-4 w-4" />
                            {locale === 'bn' ? 'তালিকা লোড করুন' : 'Load Roster'}
                        </Button>
                    </div>
                </div>

                {enrollments.length > 0 && (
                    <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' ? 'রোল' : 'Roll'}</th>
                                    <th className="px-4 py-3">{locale === 'bn' ? 'শিক্ষার্থী' : 'Student'}</th>
                                    <th className="px-4 py-3">{locale === 'bn' ? 'উপস্থিতি' : 'Status'}</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y">
                                {enrollments.map((row) => {
                                    const current = getStatus(row.student_id);
                                    return (
                                        <tr key={row.id}>
                                            <td className="px-4 py-3 font-medium">{row.roll_no ?? '—'}</td>
                                            <td className="px-4 py-3">
                                                <div className="font-medium">{localized(row.student, 'name')}</div>
                                                <div className="text-xs text-muted-foreground">{row.student?.student_code}</div>
                                            </td>
                                            <td className="px-4 py-3">
                                                <div className="flex flex-wrap gap-2">
                                                    {[
                                                        { key: 'present', bn: 'উপস্থিত', en: 'Present' },
                                                        { key: 'absent', bn: 'অনুপস্থিত', en: 'Absent' },
                                                        { key: 'late', bn: 'বিলম্ব', en: 'Late' },
                                                        { key: 'leave', bn: 'ছুটি', en: 'Leave' },
                                                    ].map((st) => (
                                                        <button
                                                            key={st.key}
                                                            type="button"
                                                            onClick={() => setStatuses((p) => ({ ...p, [row.student_id]: st.key }))}
                                                            className={`rounded-full px-3 py-1 text-xs font-medium transition ${
                                                                current === st.key
                                                                    ? 'bg-primary text-primary-foreground'
                                                                    : 'bg-muted text-muted-foreground hover:bg-muted/80'
                                                            }`}
                                                        >
                                                            {locale === 'bn' ? st.bn : st.en}
                                                        </button>
                                                    ))}
                                                </div>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                        <div className="flex justify-end border-t p-4">
                            <Button onClick={saveAttendance} disabled={saving}>
                                <Save className="mr-1.5 h-4 w-4" />
                                {locale === 'bn' ? 'হাজিরা সংরক্ষণ করুন' : 'Save Attendance'}
                            </Button>
                        </div>
                    </div>
                )}

                <div className="minimal-card p-6">
                    <h2 className="mb-3 font-semibold">{locale === 'bn' ? 'সাম্প্রতিক হাজিরা' : 'Recent Attendance Sessions'}</h2>
                    <div className="space-y-2">
                        {recentSessions.map((s) => (
                            <div key={s.id} className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
                                <span>
                                    {s.attendance_date} · {localized(s.department, 'name')} — {localized(s.academic_class, 'name')}
                                </span>
                                <span className="text-xs text-muted-foreground">
                                    {s.attendances_count} {locale === 'bn' ? 'জন শিক্ষার্থী' : 'students'}
                                </span>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </>
    );
}
