import { Head, router } from '@inertiajs/react';
import { format } from 'date-fns';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import type { PaginationState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import { DatePicker } from '@/components/date-picker';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import { FormDialog } from '@/components/form-dialog';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as departmentIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/master/departments';
import { DegreeLevels } from '@/types/department';
import type { Department, DepartmentLecturer } from '@/types/department';
import { createDepartmentColumns } from './columns';

type Props = {
    departments: {
        data: Department[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    lecturers: DepartmentLecturer[];
    highlight?: number;
};

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

export default function DepartmentIndex({
    departments,
    lecturers,
    highlight,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Department | null>(null);
    const [deleting, setDeleting] = useState<Department | null>(null);
    const [historyDepartment, setHistoryDepartment] =
        useState<Department | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-departments');
    const canUpdate = hasPermission('update-departments');
    const canDelete = hasPermission('delete-departments');

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

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

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

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

    const columns = createDepartmentColumns({
        handleEdit: (department) => setEditing(department),
        handleDeleteClick: (department) => setDeleting(department),
        handleViewHistory: (department) => setHistoryDepartment(department),
        canUpdate,
        canDelete,
    });

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Jurusan"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan jurusan dari notifikasi.
                                <button
                                    onClick={() => {
                                        router.get(
                                            departmentIndex.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}
                    lecturers={lecturers}
                />

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

                <DataTable
                    columns={columns}
                    data={departments.data}
                    searchKey="name"
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Jurusan"
                    description={(department) =>
                        `Apakah Anda yakin ingin menghapus jurusan "${department.name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />

                <LeadershipHistoryDialog
                    department={historyDepartment}
                    onOpenChange={(open) => {
                        if (!open) {
                            setHistoryDepartment(null);
                        }
                    }}
                />
            </div>
        </>
    );
}

function LeadershipHistoryDialog({
    department,
    onOpenChange,
}: {
    department: Department | null;
    onOpenChange: (open: boolean) => void;
}) {
    const entries = department?.leaderships ?? [];

    return (
        <Dialog open={department !== null} onOpenChange={onOpenChange}>
            <DialogContent className="max-h-[85vh] overflow-hidden sm:max-w-lg">
                <DialogHeader>
                    <DialogTitle>
                        Riwayat Kaprodi
                        {department ? ` — ${department.name}` : ''}
                    </DialogTitle>
                </DialogHeader>

                <div className="max-h-[60vh] space-y-3 overflow-y-auto">
                    {entries.length === 0 && (
                        <p className="text-sm text-muted-foreground">
                            Belum ada riwayat kaprodi untuk jurusan ini.
                        </p>
                    )}

                    {entries.map((entry) => (
                        <div
                            key={entry.id}
                            className="flex items-start justify-between gap-3 rounded-md border p-3"
                        >
                            <div>
                                <p className="font-medium">
                                    {entry.lecturer?.user?.profile
                                        ?.full_name ?? 'N/A'}
                                </p>
                                <p className="text-sm text-muted-foreground">
                                    {format(
                                        new Date(entry.started_at),
                                        'd MMM yyyy',
                                    )}{' '}
                                    -{' '}
                                    {entry.ended_at
                                        ? format(
                                              new Date(entry.ended_at),
                                              'd MMM yyyy',
                                          )
                                        : 'Sekarang'}
                                </p>
                            </div>
                            {!entry.ended_at && <Badge>Sekarang</Badge>}
                        </div>
                    ))}
                </div>
            </DialogContent>
        </Dialog>
    );
}

function KaprodiFields({
    errors,
    lecturers,
    editing,
}: {
    errors: Record<string, string>;
    lecturers: DepartmentLecturer[];
    editing?: Department | null;
}) {
    const [lecturer, setLecturer] = useState<DepartmentLecturer | null>(
        editing?.current_leader?.lecturer ?? null,
    );
    const [startedAt, setStartedAt] = useState<Date | undefined>(
        editing?.current_leader
            ? new Date(editing.current_leader.started_at)
            : undefined,
    );

    const availableLecturers = editing
        ? lecturers.filter((l) =>
              l.departments.some((d) => d.id === editing.id),
          )
        : [];

    return (
        <>
            <div className="grid gap-2">
                <Label>
                    Kaprodi{' '}
                    {editing && (
                        <span className="text-destructive">*</span>
                    )}
                </Label>
                <input
                    type="hidden"
                    name="lecturer_id"
                    value={lecturer?.id ?? ''}
                />
                <Combobox
                    items={availableLecturers}
                    value={lecturer}
                    disabled={!editing}
                    onValueChange={(value) => {
                        setLecturer(value);

                        if (value && !startedAt) {
                            setStartedAt(new Date());
                        }
                    }}
                    itemToStringLabel={(l) => lecturerLabel(l)}
                    isItemEqualToValue={(a, b) => a.id === b.id}
                >
                    <ComboboxInput
                        placeholder={
                            editing
                                ? 'Pilih kaprodi'
                                : 'Simpan jurusan terlebih dahulu'
                        }
                        disabled={!editing}
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            {editing
                                ? 'Belum ada dosen di jurusan ini.'
                                : 'Simpan jurusan terlebih dahulu, lalu tambahkan dosen ke jurusan ini.'}
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(l: DepartmentLecturer) => (
                                <ComboboxItem key={l.id} value={l}>
                                    {lecturerLabel(l)}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
                <InputError message={errors.lecturer_id} />
            </div>
            {lecturer && (
                <div className="grid gap-2">
                    <Label>
                        Mulai Menjabat{' '}
                        <span className="text-destructive">*</span>
                    </Label>
                    <input
                        type="hidden"
                        name="leadership_started_at"
                        value={
                            startedAt ? format(startedAt, 'yyyy-MM-dd') : ''
                        }
                    />
                    <DatePicker value={startedAt} onChange={setStartedAt} />
                    <InputError message={errors.leadership_started_at} />
                </div>
            )}
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    lecturers,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    lecturers: DepartmentLecturer[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Jurusan"
            action={store()}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <div className="grid gap-2">
                        <Label htmlFor="code">
                            Kode <span className="text-destructive">*</span>
                        </Label>
                        <Input id="code" name="code" placeholder="Contoh: SI" />
                        <InputError message={errors.code} />
                    </div>
                    <div className="grid gap-2">
                        <Label htmlFor="name">
                            Nama <span className="text-destructive">*</span>
                        </Label>
                        <Input
                            id="name"
                            name="name"
                            placeholder="Masukkan nama jurusan"
                        />
                        <InputError message={errors.name} />
                    </div>
                    <div className="grid gap-2">
                        <Label>Jenjang</Label>
                        <input type="hidden" name="degree_level" />
                        <Select name="degree_level">
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Pilih jenjang" />
                            </SelectTrigger>
                            <SelectContent>
                                {DegreeLevels.map((level) => (
                                    <SelectItem key={level} value={level}>
                                        {level}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.degree_level} />
                    </div>
                    <KaprodiFields errors={errors} lecturers={lecturers} />
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    lecturers,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: Department | null;
    lecturers: DepartmentLecturer[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Jurusan"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="edit-code">
                                Kode <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="edit-code"
                                name="code"
                                placeholder="Contoh: SI"
                                defaultValue={editing.code}
                            />
                            <InputError message={errors.code} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-name">
                                Nama <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="edit-name"
                                name="name"
                                placeholder="Masukkan nama jurusan"
                                defaultValue={editing.name}
                            />
                            <InputError message={errors.name} />
                        </div>
                        <div className="grid gap-2">
                            <Label>Jenjang</Label>
                            <input
                                type="hidden"
                                name="degree_level"
                                defaultValue={editing.degree_level ?? ''}
                            />
                            <Select
                                name="degree_level"
                                defaultValue={editing.degree_level ?? undefined}
                            >
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih jenjang" />
                                </SelectTrigger>
                                <SelectContent>
                                    {DegreeLevels.map((level) => (
                                        <SelectItem key={level} value={level}>
                                            {level}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.degree_level} />
                        </div>
                        <KaprodiFields
                            errors={errors}
                            lecturers={lecturers}
                            editing={editing}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}
