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 { 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>();

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Tagihan"
            action={store()}
            resetOnSuccess
            onSuccess={() => {
                onOpenChange(false);
                setDueDate(undefined);
            }}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <div className="grid gap-2">
                        <Label>
                            Mahasiswa{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <input type="hidden" name="student_id" />
                        <Select name="student_id">
                            <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>
                            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</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,
    );

    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>
                            <Select
                                name="student_id"
                                defaultValue={String(editing.student_id)}
                            >
                                <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>
                                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</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>
    );
}
