import { Form, Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useEffect, useState } from 'react';
import InputError from '@/components/input-error';
import { RupiahInput } from '@/components/rupiah-input';
import { DatePicker } from '@/components/date-picker';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { destroy, index as employeeAdvanceIndex, store, update, approve, pay } from '@/routes/admin/finance/employee-advances';
import { createEmployeeAdvanceColumns } from './columns';
import type { EmployeeAdvance } from './columns';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTable } from '@/components/data-table';

type Props = {
    employeeAdvances: EmployeeAdvance[];
};

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

    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">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-semibold tracking-tight">
                            Kasbon
                        </h2>
                    </div>
                    <Dialog open={createOpen} onOpenChange={(open) => {
                        setCreateOpen(open);
                        if (!open) {
                            setDueDate(undefined);
                        }
                    }}>
                        <Button asChild>
                            <button
                                type="button"
                                onClick={() => setCreateOpen(true)}
                            >
                                <Plus className="h-4 w-4" />
                                Tambah
                            </button>
                        </Button>
                        <DialogContent>
                            <Form action={store()} resetOnSuccess onSuccess={() => setCreateOpen(false)}>
                                {({ errors, processing }) => {

                                    return (
                                        <>
                                            <DialogHeader>
                                                <DialogTitle>Tambah Kasbon</DialogTitle>
                                            </DialogHeader>
                                            <div className="grid gap-4 py-4">
                                                <div className="grid gap-2">
                                                    <Label>
                                                        Jumlah{' '} <span className="text-destructive">*</span>
                                                    </Label>
                                                    <RupiahInput name="amount" min={1} />
                                                    <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"
                                                        min={new Date()}
                                                    />
                                                    <InputError message={errors.due_date} />
                                                </div>
                                            </div>
                                            <DialogFooter>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() => setCreateOpen(false)}
                                                >
                                                    Batal
                                                </Button>
                                                <Button
                                                    type='submit'
                                                    disabled={processing}
                                                >
                                                    {processing
                                                        ? 'Menyimpan...'
                                                        : 'Simpan'}
                                                </Button>
                                            </DialogFooter>
                                        </>
                                    );
                                }}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                <DataTable
                    columns={columns}
                    data={employeeAdvances}
                    searchKey="description"
                    searchPlaceholder="Cari kasbon..."
                    emptyText="Belum ada data kasbon."
                />

                <Dialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                            setEditingDueDate(undefined);
                        }
                    }}
                >
                    <DialogContent>
                        {editing && (
                            <Form action={update(editing.id)} resetOnSuccess onSuccess={() => {
                                setEditing(null);
                                setEditingDueDate(undefined);
                            }}>
                                {({ errors, processing }) => {

                                    return (
                                        <>
                                            <DialogHeader>
                                                <DialogTitle>Edit Kasbon</DialogTitle>
                                            </DialogHeader>
                                            <div className="grid gap-4 py-4">
                                                <div className="grid gap-2">
                                                    <Label>Jumlah{' '} <span className="text-destructive">*</span></Label>
                                                    <RupiahInput name="amount" defaultValue={editing.amount} min={1} />
                                                    <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"
                                                        min={new Date()}
                                                    />
                                                    <InputError message={errors.due_date} />
                                                </div>
                                            </div>
                                            <DialogFooter>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() => {
                                                        setEditing(null);
                                                    }}
                                                >
                                                    Batal
                                                </Button>
                                                <Button
                                                    type="submit"
                                                    disabled={processing}
                                                >
                                                    {processing
                                                        ? 'Menyimpan...'
                                                        : 'Simpan'}
                                                </Button>
                                            </DialogFooter>
                                        </>
                                    );
                                }}
                            </Form>
                        )}
                    </DialogContent>
                </Dialog>

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

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

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

EmployeeAdvanceIndex.layout = {
    breadcrumbs: [
        {
            title: 'Keuangan',
            href: employeeAdvanceIndex(),
        },
        {
            title: 'Kasbon',
            href: employeeAdvanceIndex(),
        },
    ],
};
