import { Head, router } 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 { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    approve,
    destroy,
    index as leaveRequestIndex,
    reject,
    store,
    update,
} from '@/routes/admin/hr/leave-requests';
import type { LeaveRequest } from './columns';
import { createLeaveRequestColumns } from './columns';

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

type Props = {
    leaveRequests: {
        data: LeaveRequest[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        status?: string;
    };
    filterOptions: {
        statusOptions: StatusOption[];
    };
    currentUserId: number;
};

function toLocalDateString(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

export default function LeaveRequestIndex({ leaveRequests, filters, filterOptions, currentUserId }: Props) {
    const { can } = useCan();
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<LeaveRequest | null>(null);
    const [deleting, setDeleting] = useState<LeaveRequest | null>(null);
    const [approving, setApproving] = useState<LeaveRequest | null>(null);
    const [rejecting, setRejecting] = useState<LeaveRequest | null>(null);
    const [startDate, setStartDate] = useState<Date | undefined>(undefined);
    const [endDate, setEndDate] = useState<Date | undefined>(undefined);
    const [editingStartDate, setEditingStartDate] = useState<Date | undefined>(
        undefined,
    );
    const [editingEndDate, setEditingEndDate] = useState<Date | undefined>(
        undefined,
    );

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

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

    useEffect(() => {
        if (editing) {
            setEditingStartDate(new Date(editing.start_date));
            setEditingEndDate(new Date(editing.end_date));
        } else {
            setEditingStartDate(undefined);
            setEditingEndDate(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 handleReject() {
        if (!rejecting) {
            return;
        }

        router.post(
            reject(rejecting.id),
            {},
            {
                onSuccess: () => setRejecting(null),
            },
        );
    }

    const columns = createLeaveRequestColumns({
        handleEdit: (leaveRequest) => setEditing(leaveRequest),
        handleDeleteClick: (leaveRequest) => setDeleting(leaveRequest),
        handleApprove: (leaveRequest) => setApproving(leaveRequest),
        handleReject: (leaveRequest) => setRejecting(leaveRequest),
        can,
        currentUserId,
    });

    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="Cuti" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Cuti"
                    actions={
                        can('leave_requests.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) {
                            setStartDate(undefined);
                            setEndDate(undefined);
                        }
                    }}
                    title="Tambah Permohonan Cuti"
                    action={store()}
                    resetOnSuccess
                    onSuccess={() => setCreateOpen(false)}
                >
                    {({ errors }) => (
                        <>
                            <div className="grid gap-2">
                                <Label>
                                    Tanggal Mulai{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <input
                                    type="hidden"
                                    name="start_date"
                                    value={
                                        startDate
                                            ? toLocalDateString(startDate)
                                            : ''
                                    }
                                />
                                <DatePicker
                                    value={startDate}
                                    onChange={setStartDate}
                                    placeholder="Pilih tanggal mulai"
                                />
                                <InputError message={errors.start_date} />
                            </div>
                            <div className="grid gap-2">
                                <Label>
                                    Tanggal Selesai{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <input
                                    type="hidden"
                                    name="end_date"
                                    value={
                                        endDate
                                            ? toLocalDateString(endDate)
                                            : ''
                                    }
                                />
                                <DatePicker
                                    value={endDate}
                                    onChange={setEndDate}
                                    placeholder="Pilih tanggal selesai"
                                />
                                <InputError message={errors.end_date} />
                            </div>
                        </>
                    )}
                </FormDialog>

                <DataTable
                    columns={columns}
                    data={leaveRequests.data}
                    searchKey="employee.user.user_profile.full_name"

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

                <FormDialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                            setEditingStartDate(undefined);
                            setEditingEndDate(undefined);
                        }
                    }}
                    title="Edit Permohonan Cuti"
                    action={editing ? update(editing.id) : ''}
                    resetOnSuccess
                    onSuccess={() => {
                        setEditing(null);
                        setEditingStartDate(undefined);
                        setEditingEndDate(undefined);
                    }}
                >
                    {({ errors }) =>
                        editing && (
                            <>
                                <div className="grid gap-2">
                                    <Label>
                                        Tanggal Mulai{' '}
                                        <span className="text-destructive">
                                            *
                                        </span>
                                    </Label>
                                    <input
                                        type="hidden"
                                        name="start_date"
                                        value={
                                            editingStartDate
                                                ? toLocalDateString(editingStartDate)
                                                : ''
                                        }
                                    />
                                    <DatePicker
                                        value={editingStartDate}
                                        onChange={setEditingStartDate}
                                        placeholder="Pilih tanggal mulai"
                                    />
                                    <InputError message={errors.start_date} />
                                </div>
                                <div className="grid gap-2">
                                    <Label>
                                        Tanggal Selesai{' '}
                                        <span className="text-destructive">
                                            *
                                        </span>
                                    </Label>
                                    <input
                                        type="hidden"
                                        name="end_date"
                                        value={
                                            editingEndDate
                                                ? toLocalDateString(editingEndDate)
                                                : ''
                                        }
                                    />
                                    <DatePicker
                                        value={editingEndDate}
                                        onChange={setEditingEndDate}
                                        placeholder="Pilih tanggal selesai"
                                    />
                                    <InputError message={errors.end_date} />
                                </div>
                            </>
                        )
                    }
                </FormDialog>

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

                <DeleteConfirmDialog
                    target={approving}
                    onOpenChange={(open) => {
                        if (!open) {
                            setApproving(null);
                        }
                    }}
                    title="Setujui Permohonan Cuti"
                    description={`Apakah Anda yakin ingin menyetujui permohonan cuti ini?`}
                    confirmLabel="Setujui"
                    onConfirm={handleApprove}
                />

                <DeleteConfirmDialog
                    target={rejecting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setRejecting(null);
                        }
                    }}
                    title="Tolak Permohonan Cuti"
                    description={`Apakah Anda yakin ingin menolak permohonan cuti ini?`}
                    confirmLabel="Tolak"
                    onConfirm={handleReject}
                />
            </div>
        </>
    );
}
