import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import { DataCards } from '@/components/data-cards';
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 { FilterOptionGroup } 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 {
    Combobox,
    ComboboxCollection,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxGroup,
    ComboboxInput,
    ComboboxItem,
    ComboboxLabel,
    ComboboxList,
} from '@/components/ui/combobox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import type { ViewMode } from '@/components/view-toggle';
import { ViewToggle } from '@/components/view-toggle';
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 { formatAcademicTermLabel } from '@/types/academic-term';
import type { Material } from '@/types/material';
import { createMaterialCard } from './card';
import { createMaterialColumns } from './columns';

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

type CourseClassGroup = { value: string; items: CourseClassOption[] };

type AcademicTermOption = {
    id: number;
    academic_year: string;
    semester: string;
};

type Props = {
    materials: {
        data: Material[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    courseClasses: CourseClassOption[];
    filterCourseClasses: CourseClassOption[];
    academicTerms: AcademicTermOption[];
    highlight?: number;
    filters: {
        course_class_id?: string;
        academic_term_id?: string;
    };
};

function courseClassLabel(courseClass: CourseClassOption): string {
    return `${courseClass.course?.code ?? ''} - ${courseClass.course?.name ?? ''}`;
}

function groupCourseClassesByDepartment(
    options: CourseClassOption[],
): CourseClassGroup[] {
    const groups: CourseClassGroup[] = [];
    let currentKey: string | null = null;

    for (const option of options) {
        const key = `${option.course?.department?.name ?? 'Tanpa Jurusan'} — Semester ${option.course?.semester_number ?? 'Tidak ditentukan'}`;

        if (key !== currentKey) {
            currentKey = key;
            groups.push({ value: key, items: [] });
        }

        groups[groups.length - 1].items.push(option);
    }

    return groups;
}

function CourseClassField({
    courseClasses,
    value,
    onChange,
}: {
    courseClasses: CourseClassOption[];
    value: CourseClassOption | null;
    onChange: (value: CourseClassOption | null) => void;
}) {
    const groups = groupCourseClassesByDepartment(courseClasses);

    return (
        <Combobox
            items={groups}
            value={value}
            onValueChange={onChange}
            itemToStringLabel={courseClassLabel}
            isItemEqualToValue={(a, b) => a.id === b.id}
        >
            <ComboboxInput placeholder="Pilih kelas" className="w-full" />
            <ComboboxContent>
                <ComboboxEmpty>Kelas tidak ditemukan.</ComboboxEmpty>
                <ComboboxList>
                    {(group: CourseClassGroup) => (
                        <ComboboxGroup key={group.value} items={group.items}>
                            <ComboboxLabel>{group.value}</ComboboxLabel>
                            <ComboboxCollection>
                                {(option: CourseClassOption) => (
                                    <ComboboxItem
                                        key={option.id}
                                        value={option}
                                    >
                                        {courseClassLabel(option)}
                                    </ComboboxItem>
                                )}
                            </ComboboxCollection>
                        </ComboboxGroup>
                    )}
                </ComboboxList>
            </ComboboxContent>
        </Combobox>
    );
}

function courseClassFilterGroups(
    courseClasses: CourseClassOption[],
): FilterOptionGroup[] {
    return groupCourseClassesByDepartment(courseClasses).map((group) => ({
        label: group.value,
        options: group.items.map((option) => ({
            value: String(option.id),
            label: courseClassLabel(option),
        })),
    }));
}

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

    const filterFields = [
        {
            key: 'academic_term_id',
            label: 'Periode Akademik',
            options: academicTerms.map((term) => ({
                value: String(term.id),
                label: formatAcademicTermLabel(term),
            })),
        },
        {
            key: 'course_class_id',
            label: 'Kelas',
            type: 'combobox' as const,
            groups: courseClassFilterGroups(filterCourseClasses),
            disabled: filterCourseClasses.length === 0,
            placeholder:
                filterCourseClasses.length === 0
                    ? 'Pilih periode akademik dulu'
                    : undefined,
        },
    ];

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

    const { search, handleSearchChange, applyFilters } = useServerTable({
        route: () => materialIndex.url(),
        pagination,
        filters,
        resetKeys: ['materials'],
    });

    function handleApplyFilters(newFilters: Record<string, string>) {
        const clearedAcademicTerm =
            Boolean(filters.academic_term_id) && !newFilters.academic_term_id;

        const nextFilters: Record<string, string> = {
            ...newFilters,
            ...(clearedAcademicTerm ? { academic_term_id: '0' } : {}),
        };

        // The class list depends on the selected term, so a previously
        // picked class is no longer relevant once the term changes.
        const academicTermChanged =
            (nextFilters.academic_term_id ?? '0') !==
            (filters.academic_term_id ?? '0');

        if (academicTermChanged) {
            delete nextFilters.course_class_id;
        }

        applyFilters(nextFilters);
    }

    // '0' explicitly means "all terms" — treated as no active filter from
    // FilterDialog's point of view, so its Select shows "Semua" (not blank)
    // as selected.
    const filterDialogActiveFilters = {
        ...filters,
        academic_term_id:
            filters.academic_term_id === '0'
                ? undefined
                : filters.academic_term_id,
    };

    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,
    });

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

    const toolbar = (
        <>
            <FilterDialog
                fields={filterFields}
                activeFilters={filterDialogActiveFilters}
                onApply={handleApplyFilters}
            />
            <ViewToggle value={view} onChange={setView} />
        </>
    );

    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}
                />

                {view === 'table' ? (
                    <DataTable
                        columns={columns}
                        data={materials.data}
                        searchKey="title"
                        pagination={pagination}
                        onSearchChange={handleSearchChange}
                        searchValue={search}
                        infiniteScroll={{ propName: 'materials' }}
                        toolbar={toolbar}
                    />
                ) : (
                    <DataCards
                        data={materials.data}
                        renderCard={renderMaterialCard}
                        getRowId={(material) => material.id}
                        searchKey="title"
                        pagination={pagination}
                        onSearchChange={handleSearchChange}
                        searchValue={search}
                        infiniteScroll={{ propName: 'materials' }}
                        toolbar={toolbar}
                    />
                )}

                <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[];
}) {
    const [courseClass, setCourseClass] = useState<CourseClassOption | null>(
        null,
    );

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Materi"
            action={store()}
            resetOnSuccess
            onSuccess={() => {
                onOpenChange(false);
                setCourseClass(null);
            }}
        >
            {({ 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"
                            value={courseClass?.id ?? ''}
                        />
                        <CourseClassField
                            courseClasses={courseClasses}
                            value={courseClass}
                            onChange={setCourseClass}
                        />
                        <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[];
}) {
    const [courseClass, setCourseClass] = useState<CourseClassOption | null>(
        editing
            ? (courseClasses.find((c) => c.id === editing.course_class_id) ??
                  null)
            : null,
    );

    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>
                            <input
                                type="hidden"
                                name="course_class_id"
                                value={courseClass?.id ?? ''}
                            />
                            <CourseClassField
                                courseClasses={courseClasses}
                                value={courseClass}
                                onChange={setCourseClass}
                            />
                            <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>
    );
}
