import { Head, router, usePage } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useEffect, useState } from 'react';
import type { PaginationState } from '@/components/data-display';
import { DataTable } from '@/components/data-display';
import { DatePicker } from '@/components/inputs';
import { DeleteConfirmDialog } from '@/components/dialogs';
import { FilterPopover } from '@/components/data-display';
import { FormDialog } from '@/components/dialogs';
import { InputError } from '@/components/ui';
import { PageHeader } from '@/components/layout';
import { RupiahInput } from '@/components/inputs';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    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 { Separator } from '@/components/ui/separator';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    approve,
    destroy,
    index as employeeAdvanceIndex,
    pay,
    store,
    update,
} from '@/routes/admin/finance/employee-advances';
import type { EmployeeAdvance } from './columns';
import { createEmployeeAdvanceColumns } from './columns';

type TypeOption = {
    value: string;
    label: string;
};

type Props = {
    employeeAdvances: {
        data: EmployeeAdvance[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        status?: string;
    };
    filterOptions: {
        statusOptions: TypeOption[];
    };
};

export default function EmployeeAdvanceIndex({
    employeeAdvances,
    filters,
    filterOptions,
}: Props) {
    const { can } = useCan();
    const { auth } = usePage().props as { auth: { user: { id: number } } };
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<EmployeeAdvance | null>(null);
    const [deleting, setDeleting] = useState<EmployeeAdvance | null>(null);
    const [approving, setApproving] = useState<EmployeeAdvance | null>(null);
    const [paying, setPaying] = useState<EmployeeAdvance | null>(null);
    const [viewingPayments, setViewingPayments] = useState<EmployeeAdvance | null>(null);
    const [dueDate, setDueDate] = useState<Date | undefined>(undefined);
    const [editingDueDate, setEditingDueDate] = useState<Date | undefined>(
        undefined,
    );

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

    const {
        search,
        filterOpen,
        setFilterOpen,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilter,
        clearFilters,
    } = useServerTable({
        route: () => employeeAdvanceIndex.url(),
        pagination,
        filters,
    });

    useEffect(() => {
        if (editing) {
            setEditingDueDate(new Date(editing.due_date));
        } else {
            setEditingDueDate(undefined);
        }
    }, [editing]);

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

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

    function handleApprove() {
        if (!approving) {
            return;
        }

        router.post(
            approve(approving.id),
            {},
            {
                onSuccess: () => setApproving(null),
            },
        );
    }

    const columns = createEmployeeAdvanceColumns({
        handleEdit: (employeeAdvance) => setEditing(employeeAdvance),
        handleDeleteClick: (employeeAdvance) => setDeleting(employeeAdvance),
        handleApprove: (employeeAdvance) => setApproving(employeeAdvance),
        handlePay: (employeeAdvance) => setPaying(employeeAdvance),
        handleShowPayments: (employeeAdvance) => setViewingPayments(employeeAdvance),
        can,
        authUserId: auth.user.id,
    });

    const filterToolbar = (
        <FilterPopover
            open={filterOpen}
            onOpenChange={setFilterOpen}
            filters={filters}
            hasActiveFilters={Boolean(filters.status)}
            onClear={clearFilters}
        >
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">Status</label>
                <Select
                    value={filters.status ?? 'all'}
                    onValueChange={(value) => applyFilter('status', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Status" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua Status</SelectItem>
                        {filterOptions.statusOptions.map((opt) => (
                            <SelectItem key={opt.value} value={opt.value}>
                                {opt.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>
        </FilterPopover>
    );

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Kasbon"
                    actions={
                        can('employee_advances.create') ? (
                            <Button asChild>
                                <button
                                    type="button"
                                    onClick={() => setCreateOpen(true)}
                                >
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </button>
                            </Button>
                        ) : undefined
                    }
                />

                <FormDialog
                    open={createOpen}
                    onOpenChange={(open) => {
                        setCreateOpen(open);

                        if (!open) {
                            setDueDate(undefined);
                        }
                    }}
                    title="Tambah Kasbon"
                    action={store()}
                    resetOnSuccess
                    onSuccess={() => setCreateOpen(false)}
                >
                    {({ errors }) => (
                        <>
                            <div className="grid gap-2">
                                <Label>
                                    Jumlah{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <RupiahInput name="amount" />
                                <InputError message={errors.amount} />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="description">
                                    Keterangan{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <Input
                                    id="description"
                                    name="description"
                                    placeholder="Masukkan keterangan"
                                />
                                <InputError message={errors.description} />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="due_date">
                                    Jatuh Tempo{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <input
                                    type="hidden"
                                    name="due_date"
                                    value={
                                        dueDate
                                            ? dueDate
                                                .toISOString()
                                                .split('T')[0]
                                            : ''
                                    }
                                />
                                <DatePicker
                                    value={dueDate}
                                    onChange={setDueDate}
                                    placeholder="Pilih jatuh tempo"
                                />
                                <InputError message={errors.due_date} />
                            </div>
                        </>
                    )}
                </FormDialog>

                <DataTable
                    columns={columns}
                    data={employeeAdvances.data}
                    searchKey="description"

                    emptyText="Belum ada data kasbon."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    toolbar={filterToolbar}
                />

                <FormDialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                            setEditingDueDate(undefined);
                        }
                    }}
                    title="Edit Kasbon"
                    action={editing ? update(editing.id) : ''}
                    resetOnSuccess
                    onSuccess={() => {
                        setEditing(null);
                        setEditingDueDate(undefined);
                    }}
                >
                    {({ errors }) =>
                        editing && (
                            <>
                                <div className="grid gap-2">
                                    <Label>
                                        Jumlah{' '}
                                        <span className="text-destructive">
                                            *
                                        </span>
                                    </Label>
                                    <RupiahInput
                                        name="amount"
                                        defaultValue={editing.amount}
                                    />
                                    <InputError message={errors.amount} />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="edit-description">
                                        Keterangan{' '}
                                        <span className="text-destructive">
                                            *
                                        </span>
                                    </Label>
                                    <Input
                                        id="edit-description"
                                        name="description"
                                        placeholder="Masukkan keterangan"
                                        defaultValue={editing.description}
                                    />
                                    <InputError message={errors.description} />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="edit-due_date">
                                        Jatuh Tempo{' '}
                                        <span className="text-destructive">
                                            *
                                        </span>
                                    </Label>
                                    <input
                                        type="hidden"
                                        name="due_date"
                                        value={
                                            editingDueDate
                                                ? editingDueDate
                                                    .toISOString()
                                                    .split('T')[0]
                                                : ''
                                        }
                                    />
                                    <DatePicker
                                        value={editingDueDate}
                                        onChange={setEditingDueDate}
                                        placeholder="Pilih jatuh tempo"
                                    />
                                    <InputError message={errors.due_date} />
                                </div>
                            </>
                        )
                    }
                </FormDialog>

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

                <DeleteConfirmDialog
                    target={approving}
                    onOpenChange={(open) => {
                        if (!open) {
                            setApproving(null);
                        }
                    }}
                    title="Setujui Kasbon"
                    description={(advance) =>
                        `Apakah Anda yakin ingin menyetujui kasbon "${advance.description}"?`
                    }
                    confirmLabel="Setujui"
                    onConfirm={handleApprove}
                />

                <FormDialog
                    open={paying !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setPaying(null);
                        }
                    }}
                    title="Bayar Kasbon"
                    action={paying ? pay(paying.id) : ''}
                    resetOnSuccess
                    onSuccess={() => setPaying(null)}
                >
                    {({ errors }) =>
                        paying && (
                            <>
                                <div className="mb-4 rounded-md bg-muted p-3 text-sm">
                                    <p>
                                        Sisa:{' '}
                                        <span className="font-medium">
                                            {paying.formatted_remaining_amount}
                                        </span>
                                    </p>
                                </div>
                                <div className="grid gap-2">
                                    <Label>
                                        Jumlah Bayar{' '}
                                        <span className="text-destructive">
                                            *
                                        </span>
                                    </Label>
                                    <RupiahInput
                                        name="amount"
                                        defaultValue={paying.remaining_amount}
                                    />
                                    <InputError message={errors.amount} />
                                </div>
                            </>
                        )
                    }
                </FormDialog>

                <Dialog
                    open={viewingPayments !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setViewingPayments(null);
                        }
                    }}
                >
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>Riwayat Pembayaran</DialogTitle>
                            <DialogDescription>
                                {viewingPayments?.description}
                            </DialogDescription>
                        </DialogHeader>
                        {viewingPayments && (
                            <div className="space-y-4">
                                <div className="flex items-center justify-between text-sm">
                                    <span className="text-muted-foreground">
                                        Total:
                                    </span>
                                    <span className="font-medium">
                                        {viewingPayments.formatted_amount}
                                    </span>
                                </div>
                                <div className="flex items-center justify-between text-sm">
                                    <span className="text-muted-foreground">
                                        Terbayar:
                                    </span>
                                    <span className="font-medium text-green-600">
                                        {viewingPayments.formatted_paid_amount}
                                    </span>
                                </div>
                                <div className="flex items-center justify-between text-sm">
                                    <span className="text-muted-foreground">
                                        Sisa:
                                    </span>
                                    <span className="font-medium text-orange-600">
                                        {viewingPayments.formatted_remaining_amount}
                                    </span>
                                </div>

                                <Separator />

                                {viewingPayments.payments.length === 0 ? (
                                    <p className="py-4 text-center text-sm text-muted-foreground">
                                        Belum ada pembayaran.
                                    </p>
                                ) : (
                                    <div className="space-y-3">
                                        {viewingPayments.payments.map(
                                            (payment) => (
                                                <div
                                                    key={payment.id}
                                                    className="rounded-md border p-3"
                                                >
                                                    <div className="flex items-center justify-between">
                                                        <span className="text-sm font-medium text-green-600">
                                                            {payment.formatted_amount}
                                                        </span>
                                                        <span className="text-xs text-muted-foreground">
                                                            {payment.formatted_paid_at}
                                                        </span>
                                                    </div>
                                                    {payment.paid_by && (
                                                        <p className="mt-1 text-xs text-muted-foreground">
                                                            oleh{' '}
                                                            {payment.paid_by
                                                                .user_profile
                                                                .full_name ?? '-'}
                                                        </p>
                                                    )}
                                                </div>
                                            ),
                                        )}
                                    </div>
                                )}
                            </div>
                        )}
                    </DialogContent>
                </Dialog>
            </div>
        </>
    );
}
