import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useEffect, 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 { RupiahInput } from '@/components/rupiah-input';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    index as employeeAdvanceIndex,
    store,
    update,
    approve,
    pay,
} from '@/routes/admin/finance/employee-advances';
import { createEmployeeAdvanceColumns } from './columns';
import type { EmployeeAdvance } from './columns';

type Props = {
    employeeAdvances: {
        data: EmployeeAdvance[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
};

export default function EmployeeAdvanceIndex({ employeeAdvances }: Props) {
    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 [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,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
    } = useServerTable({
        route: () => employeeAdvanceIndex.url(),
        pagination,
    });

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

    function handlePay() {
        if (!paying) {
            return;
        }

        router.post(
            pay(paying.id),
            {},
            {
                onSuccess: () => setPaying(null),
            },
        );
    }

    const columns = createEmployeeAdvanceColumns({
        handleEdit: (employeeAdvance) => setEditing(employeeAdvance),
        handleDeleteClick: (employeeAdvance) => setDeleting(employeeAdvance),
        handleApprove: (employeeAdvance) => setApproving(employeeAdvance),
        handlePay: (employeeAdvance) => setPaying(employeeAdvance),
    });

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

                <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"
                    searchPlaceholder="Cari kasbon..."
                    emptyText="Belum ada data kasbon."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

                <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}
                />

                <DeleteConfirmDialog
                    target={paying}
                    onOpenChange={(open) => {
                        if (!open) {
                            setPaying(null);
                        }
                    }}
                    title="Bayar Kasbon"
                    description={(advance) =>
                        `Apakah Anda yakin ingin membayar kasbon "${advance.description}" sebesar ${advance.amount}? Saldo kas akan dikembalikan.`
                    }
                    confirmLabel="Bayar"
                    onConfirm={handlePay}
                />
            </div>
        </>
    );
}
