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 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 {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as academicAdvisingLogIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/services/academic-advising-logs';
import type {
    AcademicAdvisingLog,
    AcademicAdvisingLogLecturer,
    AcademicAdvisingLogStudent,
} from '@/types/academic-advising-log';
import { createAcademicAdvisingLogColumns } from './columns';

type Props = {
    logs: {
        data: AcademicAdvisingLog[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    students: AcademicAdvisingLogStudent[];
    lecturers: AcademicAdvisingLogLecturer[];
    highlight?: number;
    filters: {
        lecturer_id?: string;
    };
};

function studentLabel(student: AcademicAdvisingLogStudent): string {
    return `${student.user?.profile?.full_name ?? 'N/A'} - ${student.student_number}`;
}

function lecturerLabel(lecturer: AcademicAdvisingLogLecturer): string {
    return `${lecturer.user?.profile?.full_name ?? 'N/A'} - ${lecturer.lecturer_number}`;
}

export default function AcademicAdvisingLogIndex({
    logs,
    students,
    lecturers,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<AcademicAdvisingLog | null>(null);
    const [deleting, setDeleting] = useState<AcademicAdvisingLog | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-academic-advising-logs');
    const canUpdate = hasPermission('update-academic-advising-logs');
    const canDelete = hasPermission('delete-academic-advising-logs');

    const filterFields: FilterField[] = [
        {
            key: 'lecturer_id',
            label: 'Dosen',
            options: lecturers.map((lecturer) => ({
                value: String(lecturer.id),
                label: lecturerLabel(lecturer),
            })),
        },
    ];

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

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

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

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

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

    return (
        <>
            <Head title="Bimbingan Akademik" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Bimbingan Akademik"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan log bimbingan dari notifikasi.
                            </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}
                    students={students}
                    lecturers={lecturers}
                />

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

                <DataTable
                    columns={columns}
                    data={logs.data}
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    searchKey="student"
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Log Bimbingan"
                    description={(log) =>
                        `Apakah Anda yakin ingin menghapus log bimbingan untuk "${log.student?.user?.profile?.full_name ?? 'mahasiswa ini'}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

function AdvisingLogFields({
    errors,
    editing,
    students,
    lecturers,
}: {
    errors: Record<string, string>;
    editing?: AcademicAdvisingLog;
    students: AcademicAdvisingLogStudent[];
    lecturers: AcademicAdvisingLogLecturer[];
}) {
    const [student, setStudent] = useState<AcademicAdvisingLogStudent | null>(
        editing?.student ?? null,
    );
    const [lecturer, setLecturer] =
        useState<AcademicAdvisingLogLecturer | null>(editing?.lecturer ?? null);

    return (
        <>
            <div className="grid gap-2">
                <Label>
                    Mahasiswa <span className="text-destructive">*</span>
                </Label>
                <input
                    type="hidden"
                    name="student_id"
                    value={student?.id ?? ''}
                />
                <Combobox
                    items={students}
                    value={student}
                    onValueChange={setStudent}
                    itemToStringLabel={(s) => studentLabel(s)}
                    isItemEqualToValue={(a, b) => a.id === b.id}
                >
                    <ComboboxInput
                        placeholder="Pilih mahasiswa"
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Mahasiswa tidak ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(s: AcademicAdvisingLogStudent) => (
                                <ComboboxItem key={s.id} value={s}>
                                    {studentLabel(s)}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
                <InputError message={errors.student_id} />
            </div>
            <div className="grid gap-2">
                <Label>
                    Dosen Wali <span className="text-destructive">*</span>
                </Label>
                <input
                    type="hidden"
                    name="lecturer_id"
                    value={lecturer?.id ?? ''}
                />
                <Combobox
                    items={lecturers}
                    value={lecturer}
                    onValueChange={setLecturer}
                    itemToStringLabel={(l) => lecturerLabel(l)}
                    isItemEqualToValue={(a, b) => a.id === b.id}
                >
                    <ComboboxInput
                        placeholder="Pilih dosen"
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>Dosen tidak ditemukan.</ComboboxEmpty>
                        <ComboboxList>
                            {(l: AcademicAdvisingLogLecturer) => (
                                <ComboboxItem key={l.id} value={l}>
                                    {lecturerLabel(l)}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
                <InputError message={errors.lecturer_id} />
            </div>
            <div className="grid gap-2">
                <Label htmlFor={editing ? 'edit-topic' : 'topic'}>Topik</Label>
                <Input
                    id={editing ? 'edit-topic' : 'topic'}
                    name="topic"
                    placeholder="Masukkan topik bimbingan"
                    defaultValue={editing?.topic ?? ''}
                />
                <InputError message={errors.topic} />
            </div>
            <div className="grid gap-2">
                <Label htmlFor={editing ? 'edit-notes' : 'notes'}>
                    Catatan
                </Label>
                <Textarea
                    id={editing ? 'edit-notes' : 'notes'}
                    name="notes"
                    placeholder="Masukkan catatan bimbingan"
                    defaultValue={editing?.notes ?? ''}
                />
                <InputError message={errors.notes} />
            </div>
            <DateTimeField
                label="Tanggal Sesi"
                name="session_date"
                defaultValue={editing?.session_date}
                placeholder="Pilih tanggal sesi"
                error={errors.session_date}
            />
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    students,
    lecturers,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    students: AcademicAdvisingLogStudent[];
    lecturers: AcademicAdvisingLogLecturer[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Bimbingan Akademik"
            action={store()}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <AdvisingLogFields
                        key={open ? 'open' : 'closed'}
                        errors={errors}
                        students={students}
                        lecturers={lecturers}
                    />
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    students,
    lecturers,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: AcademicAdvisingLog | null;
    students: AcademicAdvisingLogStudent[];
    lecturers: AcademicAdvisingLogLecturer[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Bimbingan Akademik"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <AdvisingLogFields
                            errors={errors}
                            editing={editing}
                            students={students}
                            lecturers={lecturers}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}
