import { Form, Head, Link, router } from '@inertiajs/react';
import { ChevronRight, ClipboardList, ListChecks, Plus, Trash2, Edit2, X, Save, Pencil } from 'lucide-react';
import { useState } from 'react';
import { DeleteConfirmModal } from '@/components/delete-confirm-modal';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import InputError from '@/components/input-error';
import AppLayout from '@/layouts/app-layout';
import { cn } from '@/lib/utils';
import type { BreadcrumbItem } from '@/types';

type Course = { id: number; title: string };
type LearningPath = { id: number; title: string };

type AssignedTask = {
    id: number;
    title: string;
    description: string | null;
    type: 'course' | 'learning_path' | 'optional';
    course: { id: number; title: string } | null;
    learning_path: { id: number; title: string } | null;
    created_by: { id: number; name: string };
    created_at: string;
    items_count: number;
};

type Props = {
    tasks: {
        data: AssignedTask[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    courses: Course[];
    learningPaths: LearningPath[];
};

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Admin', href: '/admin' },
    { title: 'To Do List Siswa', href: '/admin/assigned-tasks' },
];

const typeLabels: Record<AssignedTask['type'], string> = {
    course: 'Per Kelas',
    learning_path: 'Per Paket Belajar',
    optional: 'Opsional',
};

const typeColors: Record<AssignedTask['type'], string> = {
    course: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400',
    learning_path: 'bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-400',
    optional: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400',
};

const textareaCls = 'border-input bg-background focus-visible:border-ring focus-visible:ring-ring/50 w-full rounded-md border px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] placeholder:text-muted-foreground';

// Modal component for editing task group from list
function EditGroupModal({ task, courses, learningPaths }: { task: AssignedTask; courses: Course[]; learningPaths: Course[] }) {
    const [open, setOpen] = useState(false);
    const [editGroupType, setEditGroupType] = useState<AssignedTask['type']>(task.type);

    function handleOpenChange(val: boolean) {
        if (!val) {
            setEditGroupType(task.type);
        }
        setOpen(val);
    }

    return (
        <Dialog open={open} onOpenChange={handleOpenChange}>
            <DialogTrigger asChild>
                <button
                    onClick={(e) => {
                        e.stopPropagation();
                    }}
                    className="flex h-8 w-8 items-center justify-center rounded-xl bg-amber-100 text-amber-700 opacity-0 scale-75 group-hover:scale-100 group-hover:opacity-100 transition-all duration-200 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400"
                    title="Edit group"
                >
                    <Edit2 className="h-3.5 w-3.5" />
                </button>
            </DialogTrigger>
            <DialogContent className="max-h-[90vh] max-w-md overflow-y-auto" onClick={(e) => e.stopPropagation()}>
                <DialogTitle>Edit Informasi Group</DialogTitle>
                <Form
                    action={`/admin/assigned-tasks/${task.id}`}
                    method="patch"
                    onSuccess={() => { setOpen(false); router.reload({ preserveScroll: true }); }}
                    className="mt-3 flex flex-col gap-4"
                >
                    {({ errors, processing }) => (
                        <>
                            <div className="grid gap-1.5">
                                <Label htmlFor={`edit-title-${task.id}`}>Nama Group</Label>
                                <Input id={`edit-title-${task.id}`} name="title" defaultValue={task.title} required />
                                <InputError message={errors.title} />
                            </div>
                            <div className="grid gap-1.5">
                                <Label htmlFor={`edit-description-${task.id}`}>Deskripsi</Label>
                                <textarea id={`edit-description-${task.id}`} name="description" rows={3} defaultValue={task.description ?? ''} className={textareaCls} />
                                <InputError message={errors.description} />
                            </div>

                            <div className="grid gap-1.5">
                                <Label>Target Siswa</Label>
                                <input type="hidden" name="type" value={editGroupType} />
                                <div className="grid grid-cols-3 gap-2">
                                    {(['course', 'learning_path', 'optional'] as const).map((t) => (
                                        <button
                                            key={t}
                                            type="button"
                                            onClick={() => setEditGroupType(t)}
                                            className={`rounded-lg border p-2 text-center text-xs transition-colors ${
                                                editGroupType === t
                                                    ? 'border-blue-500 bg-blue-50 dark:border-blue-600 dark:bg-blue-950/40 text-blue-700 dark:text-blue-400 font-medium'
                                                    : 'border-border hover:bg-muted/50 text-muted-foreground'
                                            }`}
                                        >
                                            {typeLabels[t]}
                                        </button>
                                    ))}
                                </div>
                                <InputError message={errors.type} />
                            </div>

                            {editGroupType === 'course' && (
                                <div className="grid gap-1.5">
                                    <Label htmlFor={`edit-course_id-${task.id}`}>Pilih Kelas</Label>
                                    <Select name="course_id" defaultValue={String(task.course?.id || '')} required>
                                        <SelectTrigger className="w-full">
                                            <SelectValue placeholder="Pilih kelas..." />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {courses.map((c) => (
                                                <SelectItem key={c.id} value={String(c.id)}>{c.title}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    <InputError message={errors.course_id} />
                                </div>
                            )}

                            {editGroupType === 'learning_path' && (
                                <div className="grid gap-1.5">
                                    <Label htmlFor={`edit-learning_path_id-${task.id}`}>Pilih Paket Belajar</Label>
                                    <Select name="learning_path_id" defaultValue={String(task.learning_path?.id || '')} required>
                                        <SelectTrigger className="w-full">
                                            <SelectValue placeholder="Pilih paket belajar..." />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {learningPaths.map((lp) => (
                                                <SelectItem key={lp.id} value={String(lp.id)}>{lp.title}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    <InputError message={errors.learning_path_id} />
                                </div>
                            )}

                            <div className="flex justify-end gap-2 pt-2 border-t mt-2">
                                <Button type="button" variant="outline" onClick={() => setOpen(false)}>
                                    Batal
                                </Button>
                                <Button type="submit" disabled={processing} className="bg-blue-600 hover:bg-blue-700">
                                    {processing && <Spinner className="mr-1" />}
                                    Simpan Perubahan
                                </Button>
                            </div>
                        </>
                    )}
                </Form>
            </DialogContent>
        </Dialog>
    );
}

export default function AdminAssignedTasksIndex({ tasks, courses, learningPaths }: 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(`/admin/assigned-tasks/${deleteModal.id}`, {
            onSuccess: () => setDeleteModal({ open: false, id: null, title: '' }),
        });
    }

    return (
        <>
            <Head title="To Do List Siswa" />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                {/* Header */}
                <div className="relative overflow-hidden rounded-2xl border border-blue-100 bg-gradient-to-br from-blue-50 via-white to-blue-50 p-5 shadow-sm dark:border-blue-800/30 dark:from-blue-950/40 dark:via-card dark:to-blue-950/30">
                    <div className="relative z-10 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 text-blue-900 dark:text-blue-100">To Do List Siswa</h1>
                                <p className="text-sm text-blue-600 dark:text-blue-400">
                                    <span className="font-semibold">{tasks.total}</span> group
                                </p>
                            </div>
                        </div>
                        <Link href="/admin/assigned-tasks/create">
                            <Button size="sm" className="gap-1.5 bg-blue-600 hover:bg-blue-700 shadow-sm">
                                <Plus className="h-4 w-4" />
                                Buat Group
                            </Button>
                        </Link>
                    </div>
                    <div className="absolute -right-4 -top-4 h-20 w-20 rounded-full bg-blue-100/40 dark:bg-blue-700/10" />
                </div>

                {/* List */}
                {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 group to-do list</p>
                        <p className="mt-1 text-sm text-muted-foreground">
                            Buat group dan tambahkan item to-do untuk dikirim ke siswa.
                        </p>
                    </div>
                ) : (
                    <div className="flex flex-col gap-2">
                        {tasks.data.map((task) => (
                            <div
                                key={task.id}
                                className="group rounded-2xl border bg-card transition-shadow hover:shadow-md"
                            >
                                <div className="flex items-center gap-4 p-4">
                                    <Link href={`/admin/assigned-tasks/${task.id}`} className="flex flex-1 items-center gap-4 min-w-0">
                                        <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-blue-50 dark:bg-blue-900/30">
                                            <ListChecks className="h-5 w-5 text-blue-600 dark:text-blue-400" />
                                        </div>

                                        <div className="min-w-0 flex-1">
                                            <div className="flex flex-wrap items-center gap-2">
                                                <p className="font-semibold text-gray-900 dark:text-gray-100">{task.title}</p>
                                                <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${typeColors[task.type]}`}>
                                                    {typeLabels[task.type]}
                                                </span>
                                            </div>
                                            <p className="mt-0.5 text-sm text-muted-foreground">
                                                {task.course?.title ?? task.learning_path?.title ?? '—'}
                                            </p>
                                        </div>

                                        <div className="flex shrink-0 items-center gap-3">
                                            <div className="text-right">
                                                <p className="text-lg font-bold text-gray-900 dark:text-gray-100">{task.items_count}</p>
                                                <p className="text-xs text-muted-foreground">item</p>
                                            </div>
                                            <div className="relative w-18 h-8 flex items-center justify-end gap-1.5">
                                                <ChevronRight className="h-4 w-4 text-muted-foreground transition-opacity group-hover:opacity-0" />
                                                <div className="absolute right-0 flex items-center gap-1.5">
                                                    <EditGroupModal task={task} courses={courses} learningPaths={learningPaths} />
                                                    <button
                                                        onClick={(e) => {
                                                            e.preventDefault();
                                                            e.stopPropagation();
                                                            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 opacity-0 scale-75 group-hover:scale-100 group-hover:opacity-100 transition-all duration-200 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400"
                                                        title="Hapus group"
                                                    >
                                                        <Trash2 className="h-3.5 w-3.5" />
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </Link>
                                </div>
                            </div>
                        ))}

                    </div>
                )}
            </div>

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

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