import { Head, Link, router } from '@inertiajs/react';
import { ClipboardList, Plus, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { DeleteConfirmModal } from '@/components/delete-confirm-modal';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type AssignedTask = {
    id: number;
    title: string;
    description: string | null;
    scheduled_date: string | null;
    course: { id: number; title: string } | null;
    created_at: string;
    is_recurring: boolean;
    interval_days: number | null;
    recurring_count: number | null;
};

type Props = {
    tasks: {
        data: AssignedTask[];
        total: number;
    };
};

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Instructor', href: '/instructor/courses' },
    { title: 'Assigned Tasks', href: '/instructor/assigned-tasks' },
];

function formatDate(d: string) {
    return new Intl.DateTimeFormat('id-ID', { day: 'numeric', month: 'short', year: 'numeric' }).format(new Date(d));
}

export default function InstructorAssignedTasksIndex({ tasks }: Props) {
    const [deleteModal, setDeleteModal] = useState<{ open: boolean; id: number | null; title: string }>({
        open: false,
        id: null,
        title: '',
    });

    function confirmDelete() {
        if (!deleteModal.id) return;
        router.delete(`/instructor/assigned-tasks/${deleteModal.id}`, {
            onSuccess: () => setDeleteModal({ open: false, id: null, title: '' }),
        });
    }

    return (
        <>
            <Head title="Assigned Tasks" />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-100 dark:bg-blue-800/60">
                            <ClipboardList className="h-5 w-5 text-blue-600 dark:text-blue-300" />
                        </div>
                        <div>
                            <h1 className="text-xl font-bold">Assigned Tasks</h1>
                            <p className="text-sm text-muted-foreground">{tasks.total} task dikirim ke siswa</p>
                        </div>
                    </div>
                    <Link href="/instructor/assigned-tasks/create">
                        <Button size="sm" className="gap-1.5 bg-blue-600 hover:bg-blue-700">
                            <Plus className="h-4 w-4" />
                            Buat Task
                        </Button>
                    </Link>
                </div>

                {tasks.data.length === 0 ? (
                    <div className="rounded-2xl border border-dashed p-12 text-center">
                        <ClipboardList className="mx-auto mb-3 h-10 w-10 text-muted-foreground/40" />
                        <p className="font-medium text-muted-foreground">Belum ada assigned task</p>
                        <p className="mt-1 text-sm text-muted-foreground">Buat task untuk menambah to-do list siswa di kelas Anda.</p>
                    </div>
                ) : (
                    <div className="overflow-hidden rounded-2xl border bg-card">
                        <table className="w-full text-sm">
                            <thead>
                                <tr className="border-b bg-muted/40">
                                    <th className="px-4 py-3 text-left font-semibold">Task</th>
                                    <th className="w-48 px-4 py-3 text-left font-semibold">Kelas</th>
                                    <th className="w-32 px-4 py-3 text-left font-semibold">Jadwal</th>
                                    <th className="w-16 px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y">
                                {tasks.data.map((task) => (
                                    <tr key={task.id} className="hover:bg-muted/20">
                                        <td className="px-4 py-3">
                                            <p className="font-medium">{task.title}</p>
                                            {task.description && (
                                                <p className="mt-0.5 max-w-sm truncate text-xs text-muted-foreground">{task.description}</p>
                                            )}
                                        </td>
                                        <td className="px-4 py-3 text-sm text-muted-foreground">{task.course?.title ?? '—'}</td>
                                        <td className="px-4 py-3 text-xs text-muted-foreground">
                                            {task.scheduled_date ? formatDate(task.scheduled_date) : '—'}
                                            {task.is_recurring && (
                                                <p className="mt-0.5 font-semibold text-emerald-600 dark:text-emerald-400">
                                                    Repeat: {task.interval_days} hari ({task.recurring_count}x)
                                                </p>
                                            )}
                                        </td>
                                        <td className="px-4 py-3">
                                            <button
                                                onClick={() => setDeleteModal({ open: true, id: task.id, title: task.title })}
                                                className="flex h-8 w-8 items-center justify-center rounded-xl bg-red-100 text-red-700 hover:bg-red-200 transition-colors dark:bg-red-900/30 dark:text-red-400"
                                            >
                                                <Trash2 className="h-3.5 w-3.5" />
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            <DeleteConfirmModal
                open={deleteModal.open}
                onClose={() => setDeleteModal({ open: false, id: null, title: '' })}
                onConfirm={confirmDelete}
                title={`Hapus task "${deleteModal.title}"?`}
                description="Task yang dihapus tidak dapat dikembalikan. Planner siswa yang sudah menerima task ini tidak akan terpengaruh."
            />
        </>
    );
}

InstructorAssignedTasksIndex.layout = (page: React.ReactNode) => <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>;
