import ConfirmAlert from '@/components/custom-alert/custom-alert';
import CustomFormSheet, { Field } from '@/components/custom-sheet/custom-sheet';
import { ColumnHeader } from '@/components/custom-table/column-header';
import DataTable from '@/components/custom-table/data-table';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuLabel,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Switch } from '@/components/ui/switch';
import { useAuthBreadcrumb } from '@/hooks/use-auth-breadcrumb';
import AppLayout from '@/layouts/app-layout';
import { Tahun } from '@/types';
import { Head, router } from '@inertiajs/react';
import { ColumnDef } from '@tanstack/react-table';
import { MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
import { useMemo, useState } from 'react';
import { toast, Toaster } from 'sonner';

type Props = {
    tahunList: Tahun[];
};

type AlertType = 'delete';

export default function IndexTahun({ tahunList }: Props) {
    const breadcrumbs = useAuthBreadcrumb();
    const [searchTerm, setSearchTerm] = useState('');
    const [openAlert, setOpenAlert] = useState(false);
    const [alertType, setAlertType] = useState<AlertType>();
    const [selectedTahun, setSelectedTahun] = useState<Tahun>();
    const [editingTahun, setEditingTahun] = useState<Tahun | undefined>(
        undefined,
    );
    const [openSheet, setOpenSheet] = useState(false);

    const handleSubmit = (tahun: Tahun) => {
        const payload = {
            ...tahun,
            is_active: String(Number(tahun.is_active)),
        };
        console.log('testser' + payload);
        if (tahun.id) {
            router.put(route('tahuns.update', tahun.id), payload, {
                onSuccess: () => {
                    toast.success('Tahun berhasil diperbarui');
                    setOpenSheet(false);
                },
                onError: (errors) => {
                    toast.error(errors.tahun || 'Terjadi kesalahan');
                },
            });
        } else {
            router.post(
                route('tahuns.store'),
                { ...tahun },
                {
                    onSuccess: () => {
                        toast.success('Tahun berhasil ditambahkan');
                        setOpenSheet(false);
                    },
                    onError: (errors) => {
                        toast.error(errors.tahun || 'Terjadi kesalahan');
                    },
                },
            );
        }
    };

    const handleEdit = (tahun: Tahun) => {
        setEditingTahun({
            ...tahun,
            is_active: tahun.is_active ? '1' : '0',
        });
        setOpenSheet(true);
    };

    const handleDelete = () => {
        router.delete(route('tahuns.destroy', selectedTahun?.id), {
            preserveState: true,
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Tahun telah dihapus');
                setSelectedTahun(undefined);
            },
        });
    };

    const presentAlert = (tahun: Tahun, type: AlertType) => {
        setSelectedTahun(tahun);
        setAlertType(type);
        setOpenAlert(true);
    };

    const columns = useMemo<ColumnDef<Tahun>[]>(
        () => [
            {
                id: 'no',
                header: () => <div className="text-center">#</div>,
                cell: ({ row }) => (
                    <div className="w-full text-center">{row.index + 1}</div>
                ),
                enableSorting: false,
                size: 40,
                minSize: 30,
            },
            {
                id: 'nama',
                accessorKey: 'nama',
                header: ({ column }) => (
                    <ColumnHeader column={column} title="Tahun" />
                ),
                enableSorting: false,
            },
            {
                id: 'jenis',
                accessorKey: 'jenis',
                header: ({ column }) => (
                    <ColumnHeader
                        className="text-center"
                        column={column}
                        title="Jenis"
                    />
                ),
                cell: ({ row }) => (
                    <div className="text-center">{row.getValue('jenis')}</div>
                ),
                enableSorting: false,
            },
            {
                id: 'keterangan',
                accessorKey: 'keterangan',
                header: ({ column }) => (
                    <ColumnHeader
                        className="text-center"
                        column={column}
                        title="Keterangan"
                    />
                ),
                cell: ({ row }) => (
                    <div className="text-center">
                        {row.getValue('keterangan')}
                    </div>
                ),
                enableSorting: false,
            },
            {
                id: 'status',
                accessorKey: 'status',
                header: ({ column }) => (
                    <ColumnHeader
                        className="text-center"
                        column={column}
                        title="Status"
                    />
                ),
                cell: ({ row }) => (
                    <div className="text-center">{row.getValue('status')}</div>
                ),
                enableSorting: false,
            },
            {
                id: 'is_active',
                accessorKey: 'is_active',
                header: ({ column }) => (
                    <ColumnHeader
                        column={column}
                        title="Aktif ?"
                        className="text-center"
                    />
                ),
                enableSorting: false,
                cell: ({ row }) => {
                    const tahun = row.original;
                    const handleToggle = (checked: boolean) => {
                        router.post(
                            route('tahuns.toggleActive', tahun.id),
                            { is_active: checked ? 1 : 0 },
                            {
                                preserveScroll: true,
                                preserveState: true,
                                onSuccess: () => {
                                    toast.success(
                                        `Status ${tahun.nama} (${tahun.jenis}) berhasil diubah menjadi ${
                                            checked ? 'Aktif' : 'Tidak Aktif'
                                        }`,
                                    );
                                },
                                onError: () => {
                                    toast.error(
                                        'Gagal memperbarui status pengguna',
                                    );
                                },
                            },
                        );
                    };

                    return (
                        <div className="flex justify-center">
                            <Switch
                                checked={!!tahun.is_active}
                                onCheckedChange={handleToggle}
                            />
                        </div>
                    );
                },
            },
            {
                id: 'actions',
                header: ({ column }) => (
                    <ColumnHeader column={column} title="Aksi" />
                ),
                enableSorting: false,
                cell: ({ row }) => {
                    const datatahun = row.original;
                    return (
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <Button
                                    variant="ghost"
                                    className="flex h-8 w-8 p-0"
                                >
                                    <MoreHorizontal />
                                    <span className="sr-only">Open menu</span>
                                </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent
                                align="start"
                                side="left"
                                className="w-[160px]"
                            >
                                <DropdownMenuLabel>Aksi</DropdownMenuLabel>
                                <DropdownMenuItem
                                    onClick={() => handleEdit(datatahun)}
                                >
                                    <Pencil />
                                    Edit
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                    onClick={() =>
                                        presentAlert(datatahun, 'delete')
                                    }
                                >
                                    <Trash2 />
                                    Hapus
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    );
                },
                size: 50,
            },
        ],
        [],
    );

    const tahunFields: Field[] = [
        {
            key: 'nama',
            name: 'nama',
            label: 'Tahun',
            type: 'number',
            placeholder: 'Ketik tahun',
            required: true,
            numericOnly: true,
            numericNoFormat: true,
            minLength: 4, // minimal 4 digit
            maxLength: 4, // maksimal 4 digit
            min: 1900, // minimal tahun valid
            max: 2099,
        },
        {
            key: 'jenis',
            name: 'jenis',
            label: 'Jenis',
            type: 'select',
            required: true,
            options: [
                { value: 'penetapan', label: 'Penetapan' },
                { value: 'pergeseran', label: 'Pergeseran' },
                { value: 'perubahan', label: 'Perubahan' },
                { value: 'rancangan', label: 'Rancangan' },
            ],
        },
        {
            key: 'keterangan',
            name: 'keterangan',
            label: 'Keterangan',
            type: 'text',
            placeholder: 'Ketik keterangan',
            required: false,
        },
        {
            key: 'status',
            name: 'status',
            label: 'Status',
            type: 'select',
            required: true,
            options: [
                { value: 'draft', label: 'Draft' },
                { value: 'final', label: 'Final' },
            ],
        },
        {
            key: 'is_active',
            name: 'is_active',
            label: 'Di aktifkan ?',
            type: 'select',
            required: true,
            options: [
                { value: '0', label: 'Tidak Aktif' },
                { value: '1', label: 'Aktif' },
            ],
        },
    ];

    const filteredData = (tahunList ?? []).filter(
        (tahun) =>
            tahun.nama?.toLowerCase().includes(searchTerm.toLowerCase()) ||
            tahun.jenis?.toLowerCase().includes(searchTerm.toLowerCase()),
    );

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Tahun" />
            <div className="flex h-full flex-1 flex-col gap-4 rounded-xl px-6 py-4">
                <span>
                    <h1 className="text-2xl font-bold uppercase">Tahun</h1>
                    <p className="text-sm text-muted-foreground">
                        Halaman ini digunakan untuk mengelola tahun
                    </p>
                </span>
                <DataTable
                    columns={columns}
                    data={filteredData}
                    searchValue={searchTerm}
                    onSearchChange={setSearchTerm}
                    onAddClick={() => {
                        setEditingTahun(undefined);
                        setOpenSheet(true);
                    }}
                />
            </div>

            <CustomFormSheet
                title={editingTahun ? 'Edit Tahun' : 'Tambah Tahun'}
                open={openSheet}
                onOpenChange={setOpenSheet}
                data={editingTahun}
                fields={tahunFields}
                onSave={handleSubmit}
            />

            <ConfirmAlert
                title={`Konfirmasi ${alertType}`}
                message={`Apakah Anda yakin ingin ${alertType === 'delete' ? 'menghapus' : ''} data ini?`}
                submessage={`"${selectedTahun?.nama}"`}
                open={openAlert}
                onOpenChange={setOpenAlert}
                onConfirm={alertType === 'delete' ? handleDelete : () => {}}
            />

            <Toaster position="top-right" />
        </AppLayout>
    );
}
