import { Head, router } from '@inertiajs/react';
import { format } from 'date-fns';
import type { LucideIcon } from 'lucide-react';
import {
    CircleDollarSign,
    FileText,
    Plus,
    UserRoundX,
    Wallet,
} 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 {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Combobox,
    ComboboxChip,
    ComboboxChips,
    ComboboxChipsInput,
    ComboboxCollection,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxGroup,
    ComboboxInput,
    ComboboxItem,
    ComboboxLabel,
    ComboboxList,
    useComboboxAnchor,
} from '@/components/ui/combobox';
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 { formatRupiah } from '@/lib/currency';
import {
    destroy,
    store,
    index as tuitionInvoiceIndex,
    update,
} from '@/routes/admin/finances/tuition-invoices';
import { formatAcademicTermLabel } from '@/types/academic-term';
import type {
    TuitionInvoice,
    TuitionInvoiceStudent,
} from '@/types/tuition-invoice';
import {
    PaymentMethodLabels,
    PaymentMethods,
    PaymentStatusLabels,
    PaymentStatuses,
} from '@/types/tuition-payment';
import { createTuitionInvoiceColumns } from './columns';

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

type InvoiceSummary = {
    unpaid_students: number;
    partial_students: number;
    paid_students: number;
    total_outstanding: number;
    total_collected: number;
    total_invoices: number;
};

type Props = {
    invoices: {
        data: TuitionInvoice[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    summary: InvoiceSummary;
    summaryAcademicTerm: AcademicTermOption | null;
    students: TuitionInvoiceStudent[];
    academicTerms: AcademicTermOption[];
    highlight?: number;
    filters: {
        academic_term_id?: string;
        status?: string;
        payment_method?: string;
    };
};

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

type StudentGroup = { value: string; items: TuitionInvoiceStudent[] };

function groupStudentsByDepartmentAndSemester(
    students: TuitionInvoiceStudent[],
): StudentGroup[] {
    const groups: StudentGroup[] = [];
    let currentKey: string | null = null;

    for (const student of students) {
        const key = `${student.department?.name ?? 'Tanpa Jurusan'} — Semester ${student.current_semester ?? 'Tidak ditentukan'}`;

        if (key !== currentKey) {
            currentKey = key;
            groups.push({ value: key, items: [] });
        }

        groups[groups.length - 1].items.push(student);
    }

    return groups;
}

export default function TuitionInvoiceIndex({
    invoices,
    summary,
    summaryAcademicTerm,
    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 { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-tuition-invoices');
    const canUpdate = hasPermission('update-tuition-invoices');
    const canDelete = hasPermission('delete-tuition-invoices');
    const canViewPayments = hasPermission('view-tuition-payments');

    const filterFields: FilterField[] = [
        {
            key: 'academic_term_id',
            label: 'Periode Akademik',
            options: academicTerms.map((term) => ({
                value: String(term.id),
                label: formatAcademicTermLabel(term),
            })),
        },
        {
            key: 'status',
            label: 'Status Bayar',
            options: PaymentStatuses.map((status) => ({
                value: status,
                label: PaymentStatusLabels[status],
            })),
        },
        {
            key: 'payment_method',
            label: 'Metode Pembayaran',
            options: PaymentMethods.map((method) => ({
                value: method,
                label: PaymentMethodLabels[method],
            })),
        },
    ];

    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),
        canUpdate,
        canDelete,
        canViewPayments,
    });

    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={
                        canCreate && (
                            <Button asChild>
                                <button
                                    type="button"
                                    onClick={() => setCreateOpen(true)}
                                >
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </button>
                            </Button>
                        )
                    }
                />

                <p className="text-xs text-muted-foreground">
                    Ringkasan berikut hanya menampilkan periode{' '}
                    {summaryAcademicTerm
                        ? formatAcademicTermLabel(summaryAcademicTerm)
                        : '-'}{' '}
                    dan bisa disesuaikan lewat filter.
                </p>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <StudentStatusSummaryCard summary={summary} />
                    <SummaryCard
                        icon={Wallet}
                        label="Uang Tertahan"
                        value={formatRupiah(summary.total_outstanding)}
                    />
                    <SummaryCard
                        icon={CircleDollarSign}
                        label="Total Terkumpul"
                        value={formatRupiah(summary.total_collected)}
                    />
                    <SummaryCard
                        icon={FileText}
                        label="Total Tagihan"
                        value={summary.total_invoices.toLocaleString('id-ID')}
                    />
                </div>

                <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}
                    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 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 SummaryCard({
    icon: Icon,
    label,
    value,
}: {
    icon: LucideIcon;
    label: string;
    value: string;
}) {
    return (
        <Card>
            <CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
                <CardDescription>{label}</CardDescription>
                <Icon className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
                <CardTitle className="text-2xl font-semibold">
                    {value}
                </CardTitle>
            </CardContent>
        </Card>
    );
}

function StudentStatusSummaryCard({ summary }: { summary: InvoiceSummary }) {
    const items: { label: string; value: number }[] = [
        { label: 'Belum Bayar', value: summary.unpaid_students },
        { label: 'Sebagian', value: summary.partial_students },
        { label: 'Lunas', value: summary.paid_students },
    ];

    return (
        <Card>
            <CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
                <CardDescription>Status Mahasiswa</CardDescription>
                <UserRoundX className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent className="flex items-center justify-between gap-2">
                {items.map((item) => (
                    <div key={item.label} className="text-center">
                        <p className="text-2xl font-semibold">
                            {item.value.toLocaleString('id-ID')}
                        </p>
                        <p className="text-xs text-muted-foreground">
                            {item.label}
                        </p>
                    </div>
                ))}
            </CardContent>
        </Card>
    );
}

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

    const availableStudents = academicTermId
        ? students.filter(
              (student) =>
                  !student.invoiced_term_ids?.includes(Number(academicTermId)),
          )
        : [];
    const studentGroups = groupStudentsByDepartmentAndSemester(availableStudents);

    function reset() {
        setAcademicTermId('');
        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">
                        <Label>
                            Periode Akademik{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <input
                            type="hidden"
                            name="academic_term_id"
                            value={academicTermId}
                        />
                        <Select
                            value={academicTermId}
                            onValueChange={(value) => {
                                setAcademicTermId(value);
                                setSelectedStudents([]);
                            }}
                        >
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Pilih periode akademik" />
                            </SelectTrigger>
                            <SelectContent>
                                {academicTerms.map((term) => (
                                    <SelectItem
                                        key={term.id}
                                        value={String(term.id)}
                                    >
                                        {formatAcademicTermLabel(term)}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.academic_term_id} />
                    </div>
                    <div className="grid gap-2">
                        <div className="flex items-center justify-between">
                            <Label>
                                Mahasiswa{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <button
                                type="button"
                                disabled={!academicTermId}
                                className="text-xs text-primary underline underline-offset-4 hover:text-primary/80 disabled:pointer-events-none disabled:opacity-50"
                                onClick={() =>
                                    setSelectedStudents(
                                        selectedStudents.length ===
                                            availableStudents.length
                                            ? []
                                            : availableStudents,
                                    )
                                }
                            >
                                {selectedStudents.length ===
                                    availableStudents.length &&
                                availableStudents.length > 0
                                    ? 'Batalkan Semua'
                                    : 'Pilih Semua'}
                            </button>
                        </div>
                        {selectedStudents.map((student) => (
                            <input
                                key={student.id}
                                type="hidden"
                                name="student_ids[]"
                                value={student.id}
                            />
                        ))}
                        <Combobox
                            items={studentGroups}
                            multiple
                            disabled={!academicTermId}
                            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
                                    disabled={!academicTermId}
                                    placeholder={
                                        selectedStudents.length > 0
                                            ? ''
                                            : academicTermId
                                              ? 'Pilih mahasiswa (aktif)'
                                              : 'Pilih periode akademik terlebih dahulu'
                                    }
                                />
                            </ComboboxChips>
                            <ComboboxContent anchor={studentAnchor}>
                                <ComboboxEmpty>
                                    Mahasiswa tidak ditemukan.
                                </ComboboxEmpty>
                                <ComboboxList>
                                    {(group: StudentGroup) => (
                                        <ComboboxGroup
                                            key={group.value}
                                            items={group.items}
                                        >
                                            <ComboboxLabel>
                                                {group.value}
                                            </ComboboxLabel>
                                            <ComboboxCollection>
                                                {(
                                                    student: TuitionInvoiceStudent,
                                                ) => (
                                                    <ComboboxItem
                                                        key={student.id}
                                                        value={student}
                                                    >
                                                        {studentLabel(student)}
                                                    </ComboboxItem>
                                                )}
                                            </ComboboxCollection>
                                        </ComboboxGroup>
                                    )}
                                </ComboboxList>
                            </ComboboxContent>
                        </Combobox>
                        <InputError message={errors.student_ids} />
                    </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,
    );
    const studentGroups = groupStudentsByDepartmentAndSemester(students);

    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>
                                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)}
                                        >
                                            {formatAcademicTermLabel(term)}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.academic_term_id} />
                        </div>
                        <div className="grid gap-2">
                            <Label>
                                Mahasiswa{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <input
                                type="hidden"
                                name="student_id"
                                value={student?.id ?? ''}
                            />
                            <Combobox
                                items={studentGroups}
                                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>
                                        {(group: StudentGroup) => (
                                            <ComboboxGroup
                                                key={group.value}
                                                items={group.items}
                                            >
                                                <ComboboxLabel>
                                                    {group.value}
                                                </ComboboxLabel>
                                                <ComboboxCollection>
                                                    {(
                                                        option: TuitionInvoiceStudent,
                                                    ) => (
                                                        <ComboboxItem
                                                            key={option.id}
                                                            value={option}
                                                        >
                                                            {studentLabel(
                                                                option,
                                                            )}
                                                        </ComboboxItem>
                                                    )}
                                                </ComboboxCollection>
                                            </ComboboxGroup>
                                        )}
                                    </ComboboxList>
                                </ComboboxContent>
                            </Combobox>
                            <InputError message={errors.student_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>
    );
}
