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 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 { RupiahInput } from '@/components/rupiah-input';
import { Button } from '@/components/ui/button';
import {
    Combobox,
    ComboboxChip,
    ComboboxChips,
    ComboboxChipsInput,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
    useComboboxAnchor,
} from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as tuitionInvoiceIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/finances/tuition-invoices';
import type {
    TuitionInvoice,
    TuitionInvoiceStudent,
} from '@/types/tuition-invoice';
import { createTuitionInvoiceColumns } from './columns';

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

type Props = {
    invoices: {
        data: TuitionInvoice[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    students: TuitionInvoiceStudent[];
    academicTerms: AcademicTermOption[];
    highlight?: number;
    filters: {
        academic_term_id?: string;
    };
};

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

export default function TuitionInvoiceIndex({
    invoices,
    students,
    academicTerms,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<TuitionInvoice | null>(null);
    const [deleting, setDeleting] = useState<TuitionInvoice | null>(null);

    const filterFields: FilterField[] = [
        {
            key: 'academic_term_id',
            label: 'Periode Akademik',
            options: academicTerms.map((term) => ({
                value: String(term.id),
                label: term.name,
            })),
        },
    ];

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

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

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

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

    const columns = createTuitionInvoiceColumns({
        handleEdit: (invoice) => setEditing(invoice),
        handleDeleteClick: (invoice) => setDeleting(invoice),
    });

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Tagihan"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan tagihan 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}
                    academicTerms={academicTerms}
                />

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

                <DataTable
                    columns={columns}
                    data={invoices.data}
                    emptyText="Belum ada data tagihan."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    searchKey="student"
                    searchPlaceholder="Cari nama atau NIM mahasiswa..."
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />

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

function CreateForm({
    open,
    onOpenChange,
    students,
    academicTerms,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    students: TuitionInvoiceStudent[];
    academicTerms: AcademicTermOption[];
}) {
    const [dueDate, setDueDate] = useState<Date | undefined>();
    const [selectedStudents, setSelectedStudents] = useState<
        TuitionInvoiceStudent[]
    >([]);
    const studentAnchor = useComboboxAnchor();

    function reset() {
        setDueDate(undefined);
        setSelectedStudents([]);
    }

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Tagihan"
            action={store()}
            resetOnSuccess
            onSuccess={() => {
                onOpenChange(false);
                reset();
            }}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <div className="grid gap-2">
                        <div className="flex items-center justify-between">
                            <Label>
                                Mahasiswa{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <button
                                type="button"
                                className="text-xs text-primary underline underline-offset-4 hover:text-primary/80"
                                onClick={() =>
                                    setSelectedStudents(
                                        selectedStudents.length ===
                                            students.length
                                            ? []
                                            : students,
                                    )
                                }
                            >
                                {selectedStudents.length === students.length
                                    ? 'Batalkan Semua'
                                    : 'Pilih Semua'}
                            </button>
                        </div>
                        {selectedStudents.map((student) => (
                            <input
                                key={student.id}
                                type="hidden"
                                name="student_ids[]"
                                value={student.id}
                            />
                        ))}
                        <Combobox
                            items={students}
                            multiple
                            value={selectedStudents}
                            onValueChange={setSelectedStudents}
                            itemToStringLabel={studentLabel}
                            isItemEqualToValue={(a, b) => a.id === b.id}
                        >
                            <ComboboxChips ref={studentAnchor}>
                                {selectedStudents.map((student) => (
                                    <ComboboxChip
                                        key={student.id}
                                        aria-label={studentLabel(student)}
                                    >
                                        {studentLabel(student)}
                                    </ComboboxChip>
                                ))}
                                <ComboboxChipsInput
                                    placeholder={
                                        selectedStudents.length === 0
                                            ? 'Pilih mahasiswa (aktif)'
                                            : ''
                                    }
                                />
                            </ComboboxChips>
                            <ComboboxContent anchor={studentAnchor}>
                                <ComboboxEmpty>
                                    Mahasiswa tidak ditemukan.
                                </ComboboxEmpty>
                                <ComboboxList>
                                    {students.map((student) => (
                                        <ComboboxItem
                                            key={student.id}
                                            value={student}
                                        >
                                            {studentLabel(student)}
                                        </ComboboxItem>
                                    ))}
                                </ComboboxList>
                            </ComboboxContent>
                        </Combobox>
                        <InputError message={errors.student_ids} />
                    </div>
                    <div className="grid gap-2">
                        <Label>
                            Periode Akademik{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <input type="hidden" name="academic_term_id" />
                        <Select name="academic_term_id">
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Pilih periode akademik" />
                            </SelectTrigger>
                            <SelectContent>
                                {academicTerms.map((term) => (
                                    <SelectItem
                                        key={term.id}
                                        value={String(term.id)}
                                    >
                                        {term.name}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.academic_term_id} />
                    </div>
                    <div className="grid gap-2">
                        <Label htmlFor="amount_due">
                            Jumlah Tagihan{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <RupiahInput
                            id="amount_due"
                            name="amount_due"
                            placeholder="3.000.000"
                            ariaInvalid={!!errors.amount_due}
                        />
                        <InputError message={errors.amount_due} />
                    </div>
                    <div className="grid gap-2">
                        <Label>
                            Jatuh Tempo{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <input
                            type="hidden"
                            name="due_date"
                            value={dueDate ? format(dueDate, 'yyyy-MM-dd') : ''}
                        />
                        <DatePicker
                            value={dueDate}
                            onChange={setDueDate}
                            placeholder="Pilih tanggal jatuh tempo"
                        />
                        <InputError message={errors.due_date} />
                    </div>
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    students,
    academicTerms,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: TuitionInvoice | null;
    students: TuitionInvoiceStudent[];
    academicTerms: AcademicTermOption[];
}) {
    const [dueDate, setDueDate] = useState<Date | undefined>(
        editing?.due_date ? new Date(editing.due_date) : undefined,
    );
    const [student, setStudent] = useState<TuitionInvoiceStudent | null>(
        students.find((s) => s.id === editing?.student_id) ?? null,
    );

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Tagihan"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <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={studentLabel}
                                isItemEqualToValue={(a, b) => a.id === b.id}
                            >
                                <ComboboxInput
                                    placeholder="Pilih mahasiswa (aktif)"
                                    className="w-full"
                                />
                                <ComboboxContent>
                                    <ComboboxEmpty>
                                        Mahasiswa tidak ditemukan.
                                    </ComboboxEmpty>
                                    <ComboboxList>
                                        {students.map((option) => (
                                            <ComboboxItem
                                                key={option.id}
                                                value={option}
                                            >
                                                {studentLabel(option)}
                                            </ComboboxItem>
                                        ))}
                                    </ComboboxList>
                                </ComboboxContent>
                            </Combobox>
                            <InputError message={errors.student_id} />
                        </div>
                        <div className="grid gap-2">
                            <Label>
                                Periode Akademik{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <Select
                                name="academic_term_id"
                                defaultValue={String(editing.academic_term_id)}
                            >
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih periode akademik" />
                                </SelectTrigger>
                                <SelectContent>
                                    {academicTerms.map((term) => (
                                        <SelectItem
                                            key={term.id}
                                            value={String(term.id)}
                                        >
                                            {term.name}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.academic_term_id} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-amount_due">
                                Jumlah Tagihan{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <RupiahInput
                                id="edit-amount_due"
                                name="amount_due"
                                defaultValue={editing.amount_due}
                                ariaInvalid={!!errors.amount_due}
                            />
                            <InputError message={errors.amount_due} />
                        </div>
                        <div className="grid gap-2">
                            <Label>
                                Jatuh Tempo{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <input
                                type="hidden"
                                name="due_date"
                                value={
                                    dueDate ? format(dueDate, 'yyyy-MM-dd') : ''
                                }
                            />
                            <DatePicker
                                value={dueDate}
                                onChange={setDueDate}
                                placeholder="Pilih tanggal jatuh tempo"
                            />
                            <InputError message={errors.due_date} />
                        </div>
                    </div>
                )
            }
        </FormDialog>
    );
}
