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

    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={
                        <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[];
}) {
    return (
        <>
            <div className="grid gap-2">
                <Label>
                    Mahasiswa <span className="text-destructive">*</span>
                </Label>
                {!editing && <input type="hidden" name="student_id" />}
                <Select
                    name="student_id"
                    defaultValue={
                        editing ? String(editing.student_id) : undefined
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih mahasiswa" />
                    </SelectTrigger>
                    <SelectContent>
                        {students.map((student) => (
                            <SelectItem
                                key={student.id}
                                value={String(student.id)}
                            >
                                {studentLabel(student)}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.student_id} />
            </div>
            <div className="grid gap-2">
                <Label>
                    Dosen Wali <span className="text-destructive">*</span>
                </Label>
                {!editing && <input type="hidden" name="lecturer_id" />}
                <Select
                    name="lecturer_id"
                    defaultValue={
                        editing ? String(editing.lecturer_id) : undefined
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih dosen" />
                    </SelectTrigger>
                    <SelectContent>
                        {lecturers.map((lecturer) => (
                            <SelectItem
                                key={lecturer.id}
                                value={String(lecturer.id)}
                            >
                                {lecturerLabel(lecturer)}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <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
                        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>
    );
}
