import API from '@/lib/axios'
import { defineStore } from 'pinia'
import { CalendarDate } from '@internationalized/date'
import { type DateRange } from 'reka-ui'
import { computed, ref, h, reactive, type Ref } from 'vue'
import { MoreHorizontal, Pencil, Trash2 } from 'lucide-vue-next'
import type { ColumnDef } from '@tanstack/vue-table'
import {
    DropdownMenu,
    DropdownMenuTrigger,
    DropdownMenuContent,
    DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import {
    DialogTrigger,
} from "@/components/ui/dialog";
export const useTipeAkses = defineStore('TipeAkses', () => {
    // ---------------------------
    // Interface Data
    // ---------------------------
    interface TIPE_AKSES {
        id_tipe_akses_old: string
        id_tipe_akses: string
        nama_tipe_akses: string
    }

    // ---------------------------
    // Helper: Date Range
    // ---------------------------
    function getCurrentMonthRange(): DateRange {
        const now = new Date()
        const currentYear = now.getFullYear()
        const currentMonth = now.getMonth() + 1
        const startOfMonth = new CalendarDate(currentYear, currentMonth, 1)
        const daysInMonth = new Date(currentYear, currentMonth, 0).getDate()
        const endOfMonth = new CalendarDate(currentYear, currentMonth, daysInMonth)

        return { start: startOfMonth, end: endOfMonth }
    }

    const DATE_RANGE = ref(getCurrentMonthRange()) as Ref<DateRange>
    const DATA_TABLE = ref<TIPE_AKSES[]>([])
    const loading = ref(false)
    const error = ref<string | null>(null)
    const showAlert = ref(false);
    const isError = ref(false);
    const alertMessage = ref("");
    const dialogVisibleAdd = ref(false);
    const dialogVisibleEdit = ref(false);
    const isEditMode = ref(false);
    const dialogVisibleDelete = ref(false);

    // ---------------------------
    // Table Columns
    // ---------------------------
    const COLUMNS_TIPE_AKSES: ColumnDef<TIPE_AKSES>[] = [
        {
            id: 'actions',
            header: 'Actions',
            cell: ({ row }) =>
                h(
                    'div',
                    { class: 'flex justify-center' },
                    [
                        h(
                            DropdownMenu,
                            {},
                            {
                                default: () => [
                                    h(
                                        DropdownMenuTrigger,
                                        { asChild: true },
                                        {
                                            default: () =>
                                                h(
                                                    'div',
                                                    {
                                                        class: 'flex items-center gap-1 cursor-pointer text-sm font-medium text-black-200 dark:text-gray-100',
                                                    },
                                                    [
                                                        h(MoreHorizontal, { class: 'w-5 h-5' }),
                                                        h('span', {}, 'Action'),
                                                    ]
                                                ),
                                        }
                                    ),
                                    h(
                                        DropdownMenuContent,
                                        {},
                                        {
                                            default: () => [
                                                h(
                                                    DialogTrigger,
                                                    { asChild: true },
                                                    {
                                                        default: () =>
                                                            h(
                                                                DropdownMenuItem,
                                                                {
                                                                    onClick: () => HANDLE_EDIT(row.original),
                                                                },
                                                                {
                                                                    default: () => [
                                                                        h(Pencil, { class: 'w-4 h-4 mr-2' }),
                                                                        'Edit',
                                                                    ],
                                                                }
                                                            ),
                                                    }
                                                ),
                                                h(
                                                    DropdownMenuItem,
                                                    {
                                                        onClick: () => {
                                                            HANDLE_DELETE(row.original.id_tipe_akses);
                                                            dialogVisibleDelete.value = true;
                                                        },
                                                    },
                                                    {
                                                        default: () => [
                                                            h(Trash2, { class: 'w-4 h-4 mr-2 text-red-600' }),
                                                            'Delete',
                                                        ],
                                                    }
                                                ),

                                            ],
                                        }
                                    ),
                                ],
                            }
                        ),
                    ]
                ),
        },
        {
            accessorKey: 'id_tipe_akses',
            header: 'ID Tipe Akses',
            enableColumnFilter: true,
            cell: ({ row }) =>
                h('div', { class: 'text-center' }, row.original.id_tipe_akses),
        },

        {
            accessorKey: 'nama_tipe_akses',
            header: 'Nama Tipe Akses',
            cell: ({ row }) =>
                h('div', { class: 'text-center' }, row.original.nama_tipe_akses),
        },
    ];

    // ---------------------------
    // Fetch LOKER STUDIO DATA
    // ---------------------------
    // const GET_TIPE_AKSES_DATA = async (start_date: string, end_date: string) => {
    const GET_TIPE_AKSES_DATA = async () => {
        try {
            const response = await API.get('/tipe-akses')
            DATA_TABLE.value = response.data?.data || []
        } catch (error) {
            console.error('Gagal mengambil data:', error)
            DATA_TABLE.value = []
        }
    }
    const filteredData = computed(() => DATA_TABLE.value)
    const CREATE_TIPE_AKSES = async (payload: TIPE_AKSES) => {
        loading.value = true
        error.value = null
        try {
            const response = await API.post('/tipe-akses/create', payload)
            return response.data
        } catch (err: any) {
            error.value = err?.response?.data?.message || 'Gagal membuat data loker'
            console.error('CREATE_TIPE_AKSES Error:', err)
            throw err
        } finally {
            loading.value = false
        }
    }

    const UPDATE_TIPE_AKSES = async (payload: TIPE_AKSES) => {
        loading.value = true
        error.value = null
        try {
            const response = await API.put(`/tipe-akses/update`, payload)
            return response.data
        } catch (err: any) {
            error.value = err?.response?.data?.message || 'Gagal memperbarui data loker'
            console.error('UPDATE_TIPE_AKSES Error:', err)
            throw err
        } finally {
            loading.value = false
        }
    }
    const DELETE_TIPE_AKSES = async (id_tipe_akses: string) => {
        console.log("DELETE_TIPE_AKSES", id_tipe_akses);
        loading.value = true;
        error.value = null;
        try {
            const response = await API.delete('/tipe-akses/delete', { id_tipe_akses });
            return response.data;
        } catch (err: any) {
            error.value = err?.response?.data?.message || 'Gagal menghapus data loker';
            console.error('DELETE_TIPE_AKSES Error:', err);
            throw err;
        } finally {
            loading.value = false;
        }
    };


    const defaultForm = {
        id_tipe_akses_old: "",
        id_tipe_akses: "",
        nama_tipe_akses: "",
    };

    const form = reactive<TIPE_AKSES>(defaultForm);
    const resetForm = () => {
        Object.assign(form, defaultForm);
        isEditMode.value = false;
        dialogVisibleAdd.value = false;
        dialogVisibleEdit.value = false;
    };


    const HANDLE_EDIT = (data: TIPE_AKSES) => {
        Object.assign(form, data);
        form.id_tipe_akses_old = data.id_tipe_akses
        isEditMode.value = true;
        dialogVisibleEdit.value = true;
    };

    const HANDLE_DELETE = async (id_tipe_akses: string) => {
        form.id_tipe_akses = id_tipe_akses
        isEditMode.value = false;
        dialogVisibleDelete.value = true;
    };

    const SUBMIT_UPDATE_TIPE_AKSES = async () => {
        try {
            await UPDATE_TIPE_AKSES(form);
            isError.value = false;
            alertMessage.value = "Data berhasil di update.";
            resetForm();
            await GET_TIPE_AKSES_DATA();
            dialogVisibleEdit.value = false;
        } catch (err: any) {
            dialogVisibleEdit.value = false;
            isError.value = true;
            alertMessage.value = err?.response?.data?.message || "Gagal menambahkan data.";
        } finally {
            showAlert.value = true;
            setTimeout(() => {
                showAlert.value = false;
            }, 3000);

        }
    };

    const SUBMIT_ADD_TIPE_AKSES = async () => {
        try {
            await CREATE_TIPE_AKSES(form);
            isError.value = false;
            alertMessage.value = "Data berhasil ditambahkan.";
            resetForm();
            await GET_TIPE_AKSES_DATA();
            dialogVisibleAdd.value = false;

        } catch (err: any) {
            dialogVisibleAdd.value = false;
            isError.value = true;
            alertMessage.value = err?.response?.data?.message || "Gagal menambahkan data.";
        } finally {
            showAlert.value = true;
            setTimeout(() => {
                showAlert.value = false;
            }, 3000);

        }
    };

    const SUBMIT_DELETE_TIPE_AKSES = async () => {
        try {
            await DELETE_TIPE_AKSES(form.id_tipe_akses);
            isError.value = false;
            alertMessage.value = "Data berhasil di Hapus.";
            resetForm();
            await GET_TIPE_AKSES_DATA();
            dialogVisibleDelete.value = false;
        } catch (err: any) {
            dialogVisibleDelete.value = false;
            isError.value = true;
            alertMessage.value = err?.response?.data?.message || "Gagal menambahkan data.";
        } finally {
            showAlert.value = true;
            setTimeout(() => {
                showAlert.value = false;
            }, 3000);

        }
    };
    return {
        DATE_RANGE,
        DATA_TABLE,
        COLUMNS_TIPE_AKSES,
        filteredData,
        showAlert, isError, alertMessage, isEditMode, form, dialogVisibleEdit, dialogVisibleAdd, dialogVisibleDelete, resetForm,
        // CHANGE_DATE_RANGE,
        // DEFAULT_DATE_RANGE,
        // REFRESH_DATA,
        GET_TIPE_AKSES_DATA,
        CREATE_TIPE_AKSES,
        UPDATE_TIPE_AKSES,
        DELETE_TIPE_AKSES,
        SUBMIT_ADD_TIPE_AKSES,
        SUBMIT_UPDATE_TIPE_AKSES,
        SUBMIT_DELETE_TIPE_AKSES,
        HANDLE_EDIT,
        HANDLE_DELETE
    }
})
