import { Head, InfiniteScroll, router } from '@inertiajs/react';
import { format } from 'date-fns';
import {
    Clock,
    ClipboardList,
    Paperclip,
    Pencil,
    Plus,
    Trash2,
    Upload,
} from 'lucide-react';
import { useState } from 'react';
import { AttachmentPreviewDialog } from '@/components/attachment-preview-dialog';
import { DateTimeField } from '@/components/datetime-field';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import { FileUploadField } from '@/components/file-upload-field';
import type {
    FilterField,
    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 { RowActions } from '@/components/row-actions';
import {
    Accordion,
    AccordionContent,
    AccordionItem,
    AccordionTrigger,
} from '@/components/ui/accordion';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
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 {
    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 assignmentIndex,
    destroy,
    store,
    submit,
    update,
} from '@/routes/admin/academic-classes/assignments';
import { index as submissionsIndex } from '@/routes/admin/academic-classes/assignments/submissions';
import { formatAcademicTermLabel } from '@/types/academic-term';
import type { Assignment } from '@/types/assignment';
import { AssignmentStatusLabels, AssignmentStatuses } from '@/types/assignment';

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 = {
    assignments: {
        data: Assignment[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    courseClasses: 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 percentageOf(part: number, total: number): number {
    return total > 0 ? Math.round((part / total) * 100) : 0;
}

/** Turns red as the deadline passes, amber once it's within 3 days. */
function deadlineTextClass(deadline: string): string {
    const hoursLeft = (new Date(deadline).getTime() - Date.now()) / 3_600_000;

    if (hoursLeft <= 0) {
        return 'font-medium text-destructive';
    }

    if (hoursLeft <= 24) {
        return 'text-destructive';
    }

    if (hoursLeft <= 72) {
        return 'text-amber-600 dark:text-amber-500';
    }

    return 'text-muted-foreground';
}

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 courseClassFilterGroups(
    courseClasses: CourseClassOption[],
): FilterOptionGroup[] {
    return groupCourseClassesByDepartment(courseClasses).map((group) => ({
        label: group.value,
        options: group.items.map((option) => ({
            value: String(option.id),
            label: courseClassLabel(option),
        })),
    }));
}

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

export default function AssignmentIndex({
    assignments,
    courseClasses,
    academicTerms,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Assignment | null>(null);
    const [deleting, setDeleting] = useState<Assignment | null>(null);
    const [submitting, setSubmitting] = useState<Assignment | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-assignments');
    const canUpdate = hasPermission('update-assignments');
    const canDelete = hasPermission('delete-assignments');
    const canViewSubmissions = hasPermission('view-assignment-submissions');
    const canSubmit = hasPermission('submit-assignments');

    const filterFields: FilterField[] = [
        {
            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(courseClasses),
        },
    ];

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

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

    function handleApplyFilters(newFilters: Record<string, string>) {
        // Tanpa `academic_term_id` eksplisit, backend akan kembali ke
        // periode aktif, jadi menghapus filter ini perlu dikirim eksplisit
        // alih-alih hanya menghilangkan key-nya.
        const clearedAcademicTerm =
            Boolean(filters.academic_term_id) && !newFilters.academic_term_id;

        applyFilters({
            ...newFilters,
            ...(clearedAcademicTerm ? { academic_term_id: '' } : {}),
        });
    }

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

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

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

                <SubmitForm
                    key={submitting?.id}
                    open={submitting !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setSubmitting(null);
                        }
                    }}
                    assignment={submitting}
                />

                <div className="flex items-center gap-2">
                    <Input
                        placeholder="Cari judul tugas..."
                        value={search}
                        onChange={(event) =>
                            handleSearchChange(event.target.value)
                        }
                        className="max-w-sm"
                    />
                    <FilterDialog
                        fields={filterFields}
                        activeFilters={filters}
                        onApply={handleApplyFilters}
                    />
                </div>

                {assignments.data.length === 0 ? (
                    <p className="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground">
                        Belum ada tugas.
                    </p>
                ) : (
                    <InfiniteScroll
                        data="assignments"
                        as="div"
                        buffer={300}
                        className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3"
                        loading={() => (
                            <p className="col-span-full py-4 text-center text-sm text-muted-foreground">
                                Memuat tugas...
                            </p>
                        )}
                    >
                        {assignments.data.map((assignment) => {
                            const mySubmission = assignment.submissions?.[0];

                            return (
                                <Card
                                    key={assignment.id}
                                    className={
                                        highlight === assignment.id
                                            ? 'ring-2 ring-primary'
                                            : undefined
                                    }
                                >
                                    <CardHeader className="flex flex-row items-start justify-between gap-2">
                                        <div className="flex flex-col gap-1">
                                            <CardTitle className="text-base leading-tight">
                                                {assignment.title}
                                            </CardTitle>
                                            {assignment.course_class && (
                                                <span className="text-xs text-muted-foreground">
                                                    {assignment.course_class
                                                        .course?.code ??
                                                        ''}{' '}
                                                    {assignment.course_class
                                                        .course?.name ?? ''}
                                                </span>
                                            )}
                                        </div>
                                        <RowActions
                                            wrapperClassName="-mt-1 -mr-2 flex items-center gap-1"
                                            actions={[
                                                {
                                                    label:
                                                        mySubmission?.status ===
                                                        'submitted'
                                                            ? 'Kumpulkan Ulang'
                                                            : 'Kumpulkan Tugas',
                                                    icon: (
                                                        <Upload className="h-3.5 w-3.5" />
                                                    ),
                                                    show:
                                                        canSubmit &&
                                                        assignment.status ===
                                                            'open',
                                                    onClick: () =>
                                                        setSubmitting(
                                                            assignment,
                                                        ),
                                                },
                                                {
                                                    label: 'Pengumpulan',
                                                    icon: (
                                                        <ClipboardList className="h-3.5 w-3.5" />
                                                    ),
                                                    show: canViewSubmissions,
                                                    href: submissionsIndex.url(
                                                        assignment.id,
                                                    ),
                                                },
                                                {
                                                    label: 'Edit',
                                                    icon: (
                                                        <Pencil className="h-3.5 w-3.5" />
                                                    ),
                                                    show: canUpdate,
                                                    onClick: () =>
                                                        setEditing(assignment),
                                                },
                                                {
                                                    label: 'Hapus',
                                                    icon: (
                                                        <Trash2 className="h-3.5 w-3.5 text-destructive" />
                                                    ),
                                                    show: canDelete,
                                                    onClick: () =>
                                                        setDeleting(assignment),
                                                },
                                            ]}
                                        />
                                    </CardHeader>
                                    <CardContent className="flex flex-col gap-2 text-xs text-muted-foreground">
                                        <div className="flex flex-wrap items-center gap-1.5">
                                            <Badge
                                                variant={
                                                    assignment.status === 'open'
                                                        ? 'secondary'
                                                        : 'destructive'
                                                }
                                                className="w-fit text-[10px] font-normal"
                                            >
                                                {
                                                    AssignmentStatusLabels[
                                                        assignment.status
                                                    ]
                                                }
                                            </Badge>
                                            {assignment.course_class
                                                ?.academic_term && (
                                                <Badge
                                                    variant="outline"
                                                    className="w-fit text-[10px] font-normal"
                                                >
                                                    {formatAcademicTermLabel(
                                                        assignment.course_class
                                                            .academic_term,
                                                    )}
                                                </Badge>
                                            )}
                                        </div>
                                        <span
                                            className={`inline-flex items-center gap-1.5 ${deadlineTextClass(assignment.deadline)}`}
                                        >
                                            <Clock className="h-3.5 w-3.5 shrink-0" />
                                            {format(
                                                new Date(assignment.deadline),
                                                'd MMM yyyy, HH:mm',
                                            )}
                                        </span>
                                        {assignment.attachment_url &&
                                        assignment.attachment_name ? (
                                            <div className="flex items-center gap-1.5">
                                                <Paperclip className="h-3.5 w-3.5 shrink-0" />
                                                <AttachmentPreviewDialog
                                                    fileUrl={
                                                        assignment.attachment_url
                                                    }
                                                    fileName={
                                                        assignment.attachment_name
                                                    }
                                                />
                                            </div>
                                        ) : null}
                                        <div className="flex flex-wrap items-center gap-1.5 pt-1">
                                            {canSubmit ? (
                                                <Badge
                                                    variant={
                                                        mySubmission?.status ===
                                                        'submitted'
                                                            ? 'default'
                                                            : 'secondary'
                                                    }
                                                >
                                                    {mySubmission?.status ===
                                                    'submitted'
                                                        ? 'Sudah Mengumpulkan'
                                                        : 'Belum Mengumpulkan'}
                                                </Badge>
                                            ) : (
                                                <>
                                                    <Badge variant="secondary">
                                                        {assignment.submissions_count.toLocaleString(
                                                            'id-ID',
                                                        )}{' '}
                                                        /{' '}
                                                        {(
                                                            assignment
                                                                .course_class
                                                                ?.enrollments_count ??
                                                            0
                                                        ).toLocaleString(
                                                            'id-ID',
                                                        )}{' '}
                                                        Pengumpulan (
                                                        {percentageOf(
                                                            assignment.submissions_count,
                                                            assignment
                                                                .course_class
                                                                ?.enrollments_count ??
                                                                0,
                                                        )}
                                                        %)
                                                    </Badge>
                                                    <Badge variant="outline">
                                                        {assignment.graded_submissions_count.toLocaleString(
                                                            'id-ID',
                                                        )}{' '}
                                                        /{' '}
                                                        {assignment.submissions_count.toLocaleString(
                                                            'id-ID',
                                                        )}{' '}
                                                        Dinilai (
                                                        {percentageOf(
                                                            assignment.graded_submissions_count,
                                                            assignment.submissions_count,
                                                        )}
                                                        %)
                                                    </Badge>
                                                </>
                                            )}
                                        </div>

                                        {assignment.description && (
                                            <Accordion
                                                type="single"
                                                collapsible
                                                className="-mx-6 -mb-6 border-t"
                                            >
                                                <AccordionItem
                                                    value="description"
                                                    className="border-b-0"
                                                >
                                                    <AccordionTrigger className="px-6 text-xs font-medium text-foreground hover:no-underline">
                                                        Deskripsi
                                                    </AccordionTrigger>
                                                    <AccordionContent className="px-6">
                                                        <p className="text-sm whitespace-pre-line text-foreground">
                                                            {
                                                                assignment.description
                                                            }
                                                        </p>
                                                    </AccordionContent>
                                                </AccordionItem>
                                            </Accordion>
                                        )}
                                    </CardContent>
                                </Card>
                            );
                        })}
                    </InfiniteScroll>
                )}

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

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Tugas"
            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 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[];
}) {
    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 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>
                            <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 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}
                        />
                        <div className="grid gap-2">
                            <Label>
                                Status{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <input type="hidden" name="status" />
                            <Select name="status" defaultValue={editing.status}>
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih status" />
                                </SelectTrigger>
                                <SelectContent>
                                    {AssignmentStatuses.map((status) => (
                                        <SelectItem key={status} value={status}>
                                            {AssignmentStatusLabels[status]}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <p className="text-xs text-muted-foreground">
                                Menutup tugas akan mencegah mahasiswa
                                mengumpulkan, terlepas dari batas waktu.
                            </p>
                            <InputError message={errors.status} />
                        </div>
                        <FileUploadField
                            name="attachment"
                            label="Lampiran"
                            existingFileName={editing.attachment_name}
                            existingFileUrl={editing.attachment_url}
                            error={errors.attachment}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}

function SubmitForm({
    open,
    onOpenChange,
    assignment,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    assignment: Assignment | null;
}) {
    const mySubmission = assignment?.submissions?.[0];

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Kumpulkan Tugas"
            action={assignment ? submit(assignment.id) : ''}
            resetOnSuccess
            submitLabel="Kumpulkan"
            submittingLabel="Mengumpulkan..."
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <div className="grid gap-2">
                        <Label htmlFor="notes">Catatan</Label>
                        <Textarea
                            id="notes"
                            name="notes"
                            placeholder="Catatan untuk dosen (opsional)"
                            defaultValue={mySubmission?.notes ?? ''}
                        />
                        <InputError message={errors.notes} />
                    </div>
                    <FileUploadField
                        label="File Tugas"
                        existingFileName={mySubmission?.file_name}
                        existingFileUrl={mySubmission?.file_url}
                        error={errors.file}
                    />
                </div>
            )}
        </FormDialog>
    );
}
