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 { 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 { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as materialIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/academic-classes/materials';
import type { Material } from '@/types/material';
import { createMaterialColumns } from './columns';

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

type Props = {
    materials: {
        data: Material[];
        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 {
    return `${courseClass.course?.code ?? ''} ${courseClass.course?.name ?? ''}`;
}

export default function MaterialIndex({
    materials,
    courseClasses,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Material | null>(null);
    const [deleting, setDeleting] = useState<Material | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-materials');
    const canUpdate = hasPermission('update-materials');
    const canDelete = hasPermission('delete-materials');

    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: materials.current_page,
        last_page: materials.last_page,
        per_page: materials.per_page,
        total: materials.total,
    };

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

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

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

    const columns = createMaterialColumns({
        handleEdit: (material) => setEditing(material),
        handleDeleteClick: (material) => setDeleting(material),
        canUpdate,
        canDelete,
    });

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Materi"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan materi dari notifikasi.
                                <button
                                    onClick={() => {
                                        router.get(
                                            materialIndex.url(),
                                            {},
                                            {
                                                replace: true,
                                                preserveState: true,
                                            },
                                        );
                                    }}
                                    className="ml-1 text-primary underline underline-offset-4 hover:text-primary/80"
                                >
                                    Tampilkan semua
                                </button>
                            </p>
                        )
                    }
                    actions={
                        canCreate && (
                            <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={materials.data}
                    searchKey="title"
                    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 Materi"
                    description={(material) =>
                        `Apakah Anda yakin ingin menghapus materi "${material.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 Materi"
            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 materi"
                        />
                        <InputError message={errors.title} />
                    </div>
                    <div className="grid gap-2">
                        <Label htmlFor="description">Deskripsi</Label>
                        <Textarea
                            id="description"
                            name="description"
                            placeholder="Masukkan deskripsi materi"
                        />
                        <InputError message={errors.description} />
                    </div>
                    <div className="grid gap-2">
                        <Label htmlFor="meeting_number">Pertemuan Ke-</Label>
                        <Input
                            id="meeting_number"
                            name="meeting_number"
                            type="number"
                            min={1}
                            placeholder="Contoh: 1"
                        />
                        <InputError message={errors.meeting_number} />
                    </div>
                    <FileUploadField
                        key={open ? 'open' : 'closed'}
                        label="File Materi"
                        error={errors.file}
                    />
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    courseClasses,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: Material | null;
    courseClasses: CourseClassOption[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Materi"
            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 materi"
                                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 materi"
                                defaultValue={editing.description ?? ''}
                            />
                            <InputError message={errors.description} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-meeting_number">
                                Pertemuan Ke-
                            </Label>
                            <Input
                                id="edit-meeting_number"
                                name="meeting_number"
                                type="number"
                                min={1}
                                defaultValue={
                                    editing.meeting_number ?? undefined
                                }
                            />
                            <InputError message={errors.meeting_number} />
                        </div>
                        <FileUploadField
                            label="File Materi"
                            existingFileName={editing.file_name}
                            existingFileUrl={editing.file_url}
                            error={errors.file}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}
