import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import type { PaginationState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import { DateTimeField } from '@/components/datetime-field';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import { FileUploadField } from '@/components/file-upload-field';
import type { FilterField } from '@/components/filter-dialog';
import { FilterDialog } from '@/components/filter-dialog';
import { FormDialog } from '@/components/form-dialog';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
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 { Textarea } from '@/components/ui/textarea';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as assignmentIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/academic-classes/assignments';
import type { Assignment } from '@/types/assignment';
import { createAssignmentColumns } from './columns';

type CourseClassOption = {
    id: number;
    class_name: string | null;
    course: { id: number; code: string; name: string } | null;
};

type Props = {
    assignments: {
        data: Assignment[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    courseClasses: CourseClassOption[];
    highlight?: number;
    filters: {
        course_class_id?: string;
    };
};

function courseClassLabel(courseClass: CourseClassOption): string {
    const namePart = courseClass.class_name
        ? `${courseClass.class_name} - `
        : '';

    return `${namePart}${courseClass.course?.code ?? ''} ${courseClass.course?.name ?? ''}`;
}

export default function AssignmentIndex({
    assignments,
    courseClasses,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Assignment | null>(null);
    const [deleting, setDeleting] = useState<Assignment | null>(null);

    const filterFields: FilterField[] = [
        {
            key: 'course_class_id',
            label: 'Kelas',
            options: courseClasses.map((courseClass) => ({
                value: String(courseClass.id),
                label: courseClassLabel(courseClass),
            })),
        },
    ];

    const pagination: PaginationState = {
        current_page: assignments.current_page,
        last_page: assignments.last_page,
        per_page: assignments.per_page,
        total: assignments.total,
    };

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilters,
    } = useServerTable({
        route: () => assignmentIndex.url(),
        pagination,
        filters,
    });

    function handleDelete() {
        if (!deleting) {
            return;
        }

        router.delete(destroy(deleting.id), {
            onSuccess: () => setDeleting(null),
        });
    }

    const columns = createAssignmentColumns({
        handleEdit: (assignment) => setEditing(assignment),
        handleDeleteClick: (assignment) => setDeleting(assignment),
    });

    return (
        <>
            <Head title="Tugas" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Tugas"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan tugas dari notifikasi.
                                <button
                                    onClick={() => {
                                        router.get(
                                            assignmentIndex.url(),
                                            {},
                                            {
                                                replace: true,
                                                preserveState: true,
                                            },
                                        );
                                    }}
                                    className="ml-1 text-primary underline underline-offset-4 hover:text-primary/80"
                                >
                                    Tampilkan semua
                                </button>
                            </p>
                        )
                    }
                    actions={
                        <Button asChild>
                            <button
                                type="button"
                                onClick={() => setCreateOpen(true)}
                            >
                                <Plus className="h-4 w-4" />
                                Tambah
                            </button>
                        </Button>
                    }
                />

                <CreateForm
                    open={createOpen}
                    onOpenChange={setCreateOpen}
                    courseClasses={courseClasses}
                />

                <EditForm
                    key={editing?.id}
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                        }
                    }}
                    editing={editing}
                    courseClasses={courseClasses}
                />

                <DataTable
                    columns={columns}
                    data={assignments.data}
                    searchKey="title"
                    searchPlaceholder="Cari tugas..."
                    emptyText="Belum ada data tugas."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Tugas"
                    description={(assignment) =>
                        `Apakah Anda yakin ingin menghapus tugas "${assignment.title}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    courseClasses,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    courseClasses: CourseClassOption[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Tugas"
            action={store()}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <div className="grid gap-2">
                        <Label>
                            Kelas <span className="text-destructive">*</span>
                        </Label>
                        <input type="hidden" name="course_class_id" />
                        <Select name="course_class_id">
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Pilih kelas" />
                            </SelectTrigger>
                            <SelectContent>
                                {courseClasses.map((courseClass) => (
                                    <SelectItem
                                        key={courseClass.id}
                                        value={String(courseClass.id)}
                                    >
                                        {courseClassLabel(courseClass)}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.course_class_id} />
                    </div>
                    <div className="grid gap-2">
                        <Label htmlFor="title">
                            Judul <span className="text-destructive">*</span>
                        </Label>
                        <Input
                            id="title"
                            name="title"
                            placeholder="Masukkan judul tugas"
                        />
                        <InputError message={errors.title} />
                    </div>
                    <div className="grid gap-2">
                        <Label htmlFor="description">Deskripsi</Label>
                        <Textarea
                            id="description"
                            name="description"
                            placeholder="Masukkan deskripsi tugas"
                        />
                        <InputError message={errors.description} />
                    </div>
                    <DateTimeField
                        label="Batas Waktu"
                        name="deadline"
                        required
                        placeholder="Pilih tanggal batas waktu"
                        error={errors.deadline}
                    />
                    <FileUploadField
                        key={open ? 'open' : 'closed'}
                        name="attachment"
                        label="Lampiran"
                        error={errors.attachment}
                    />
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    courseClasses,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: Assignment | null;
    courseClasses: CourseClassOption[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Tugas"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <div className="grid gap-2">
                            <Label>
                                Kelas{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <Select
                                name="course_class_id"
                                defaultValue={String(editing.course_class_id)}
                            >
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih kelas" />
                                </SelectTrigger>
                                <SelectContent>
                                    {courseClasses.map((courseClass) => (
                                        <SelectItem
                                            key={courseClass.id}
                                            value={String(courseClass.id)}
                                        >
                                            {courseClassLabel(courseClass)}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.course_class_id} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-title">
                                Judul{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="edit-title"
                                name="title"
                                placeholder="Masukkan judul tugas"
                                defaultValue={editing.title}
                            />
                            <InputError message={errors.title} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-description">Deskripsi</Label>
                            <Textarea
                                id="edit-description"
                                name="description"
                                placeholder="Masukkan deskripsi tugas"
                                defaultValue={editing.description ?? ''}
                            />
                            <InputError message={errors.description} />
                        </div>
                        <DateTimeField
                            label="Batas Waktu"
                            name="deadline"
                            required
                            defaultValue={editing.deadline}
                            placeholder="Pilih tanggal batas waktu"
                            error={errors.deadline}
                        />
                        <FileUploadField
                            name="attachment"
                            label="Lampiran"
                            existingFileName={editing.attachment_name}
                            existingFileUrl={editing.attachment_url}
                            error={errors.attachment}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}
