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 } from 'vue'
import { MoreHorizontal, Pencil, Trash2 } from 'lucide-vue-next'
import type { ColumnDef } from '@tanstack/vue-table'
import { Switch } from '@/components/ui/switch'
import {
    Select,
    SelectContent,
    // SelectGroup,
    SelectItem,
    // SelectLabel,
    SelectTrigger,
} from "@/components/ui/select";
import {
    DropdownMenu,
    DropdownMenuTrigger,
    DropdownMenuContent,
    DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import {
    DialogTrigger,
} from "@/components/ui/dialog";
export const useUser = defineStore('UserPengguna', () => {
    // ---------------------------
    // Interface Data
    // ---------------------------

    // ---------------------------
    // 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<USER[]>([])

    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_USER: ColumnDef<USER>[] = [
        {
            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.user_id);
                                                            dialogVisibleDelete.value = true;
                                                        },
                                                    },
                                                    {
                                                        default: () => [
                                                            h(Trash2, { class: 'w-4 h-4 mr-2 text-red-600' }),
                                                            'Delete',
                                                        ],
                                                    }
                                                ),

                                            ],
                                        }
                                    ),
                                ],
                            }
                        ),
                    ]
                ),
        },
        {
            accessorKey: 'status_akun',
            header: 'Status Akun',
            cell: ({ row }) =>
                h('div', { class: 'flex justify-center' }, [
                    h(
                        Switch,
                        {
                            modelValue: row.original.status_akun == 1,
                            'onUpdate:modelValue': async (val: boolean) => {
                                const newStatus = val ? 1 : 0;
                                const success = await UPDATE_STATUS_AKUN_AKSES(row.original.user_id, newStatus);

                                if (success) {
                                    row.original.status_akun = newStatus; // update state
                                }
                            }
                        },
                        {
                            thumb: () => h('div', { class: 'size-3 bg-white rounded-full' }) // isi thumb kalau perlu
                        }
                    )
                ])
        },
        {
            accessorKey: 'nama_petugas',
            header: 'Nama Petugas',
            enableColumnFilter: true,
            cell: ({ row }) =>
                h('div', { class: 'text-center' }, row.original.nama_petugas),
        },

        {
            accessorKey: 'username',
            header: 'Username',
            cell: ({ row }) =>
                h('div', { class: 'text-center' }, row.original.username),
        },
        {
            accessorKey: 'id_tipe_akses',
            header: 'Nama Tipe Akses',
            cell: ({ row }) =>
                h('div', { class: 'flex justify-center' }, [
                    h(
                        Select,
                        {
                            modelValue: row.original.id_tipe_akses ?? undefined,
                            'onUpdate:modelValue': async (val: string) => {
                                const idTipe = parseInt(val);
                                const success = await UPDATE_STATUS_AKUN_AKSES(row.original.user_id, null, idTipe);
                                if (success) {
                                    row.original.id_tipe_akses = val;
                                    const selected = DATA_TIPE_AKSES.value.find(
                                        x => String(x.id_tipe_akses) === val
                                    );
                                    row.original.nama_tipe_akses = selected?.nama_tipe_akses || '';
                                }
                            },

                        },

                        {
                            default: () => {
                                const selected = DATA_TIPE_AKSES.value.find(
                                    x => String(x.id_tipe_akses) === String(row.original.id_tipe_akses)
                                );
                                return [
                                    h(
                                        SelectTrigger,
                                        {},
                                        {
                                            default: () =>
                                                h(
                                                    'span',
                                                    {},
                                                    selected?.nama_tipe_akses || ''
                                                )
                                        }
                                    ),
                                    h(
                                        SelectContent,
                                        {},
                                        {
                                            default: () =>
                                                DATA_TIPE_AKSES.value.map(item =>
                                                    h(
                                                        SelectItem,
                                                        { value: String(item.id_tipe_akses) },
                                                        { default: () => item.nama_tipe_akses }
                                                    )
                                                )
                                        }
                                    )
                                ];
                            }
                        }
                    )
                ])

        }


    ];

    // ---------------------------
    // Fetch LOKER STUDIO DATA
    // ---------------------------
    // const GET_USER_DATA = async (start_date: string, end_date: string) => {

    const DATA_TIPE_AKSES = ref<{ id_tipe_akses: string, nama_tipe_akses: string }[]>([]);

    const GET_TIPE_AKSES_DATA = async () => {
        try {
            const response = await API.get("/tipe-akses");
            DATA_TIPE_AKSES.value = response.data?.data || [];
        } catch (err) {
            console.error("Gagal mengambil tipe akses:", err);
            DATA_TIPE_AKSES.value = [];
        }
    };

    const GET_USER_DATA = async () => {
        try {
            const response = await API.get("/user");
            DATA_TABLE.value = response.data?.data || [];
        } catch (err) {
            console.error("Gagal mengambil data user:", err);
            DATA_TABLE.value = [];
        }
    };

    interface USER {
        user_id_old: string;
        user_id: string;
        nama_petugas: string;
        username: string;
        password: string;
        id_tipe_akses: string;
        nama_tipe_akses: string;
        status_akun: number;
    }

    const defaultForm: USER = {
        user_id_old: "",
        user_id: "",
        nama_petugas: "",
        username: "",
        password: "",
        id_tipe_akses: "",
        nama_tipe_akses: "",
        status_akun: 1,
    };

    const form = reactive<USER>({ ...defaultForm });


    const filteredData = computed(() => DATA_TABLE.value)
    const resetForm = () => {
        Object.assign(form, defaultForm);
        isEditMode.value = false;
        dialogVisibleAdd.value = false;
        dialogVisibleEdit.value = false;
        dialogVisibleDelete.value = false;
    };


    const CREATE_USER = async (payload: USER) => {
        try {
            const response = await API.post("/user/create", payload);
            return response.data;
        } catch (err: any) {
            console.error("CREATE_USER Error:", err);
            throw err;
        }
    };

    const SUBMIT_ADD_USER = async () => {
        try {
            await CREATE_USER(form);
            isError.value = false;
            alertMessage.value = "Data berhasil ditambahkan.";
            resetForm();
            await GET_USER_DATA();
            dialogVisibleAdd.value = false;
        } catch (err: any) {
            isError.value = true;
            alertMessage.value =
                err?.response?.data?.message || "Gagal menambahkan data.";
        } finally {
            showAlert.value = true;
            setTimeout(() => (showAlert.value = false), 3000);
        }
    };
    const UPDATE_USER = async (payload: USER) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await API.put("/user/update", payload);
            return response.data;
        } catch (err: any) {
            error.value = err?.response?.data?.message || "Gagal memperbarui data user";
            console.error("UPDATE_USER Error:", err);
            throw err;
        } finally {
            loading.value = false;
        }
    };

    const HANDLE_EDIT = (data: USER) => {
        Object.assign(form, data);
        isEditMode.value = true;
        dialogVisibleEdit.value = true;
    };


    const SUBMIT_UPDATE_USER = async () => {
        console.log("form", form);
        try {
            await UPDATE_USER(form);
            isError.value = false;
            alertMessage.value = "Data berhasil diperbarui.";
            resetForm();
            await GET_USER_DATA();
            dialogVisibleEdit.value = false;
        } catch (err: any) {
            dialogVisibleEdit.value = false;
            isError.value = true;
            alertMessage.value = err?.response?.data?.message || "Gagal update data.";
        } finally {
            showAlert.value = true;
            setTimeout(() => (showAlert.value = false), 3000);
        }
    };
    const DELETE_USER = async (user_id: string) => {
        loading.value = true;
        error.value = null;
        try {
            const response = await API.delete("/user/delete", {
                user_id: user_id
            });
            return response.data;
        } catch (err: any) {
            error.value = err?.response?.data?.message || "Gagal menghapus data user";
            console.error("DELETE_USER Error:", err);
            throw err;
        } finally {
            loading.value = false;
        }
    };

    const HANDLE_DELETE = (user_id: string) => {
        form.user_id = user_id;
        isEditMode.value = false;
        dialogVisibleDelete.value = true;
    };

    const SUBMIT_DELETE_USER = async () => {
        try {
            await DELETE_USER(form.user_id);
            isError.value = false;
            alertMessage.value = "Data berhasil dihapus.";
            resetForm();
            await GET_USER_DATA();
            dialogVisibleDelete.value = false;
        } catch (err: any) {
            dialogVisibleDelete.value = false;
            isError.value = true;
            alertMessage.value = err?.response?.data?.message || "Gagal menghapus data.";
        } finally {
            showAlert.value = true;
            setTimeout(() => (showAlert.value = false), 3000);
        }
    };

    const UPDATE_STATUS_AKUN_AKSES = async (
        user_id: string,
        status: number | null = null,
        id_tipe_akses: number | null = null
    ): Promise<boolean> => {
        try {
            await API.put('/user/change-user-account', {
                user_id,
                status_akun: status,
                id_tipe_akses
            });
            return true;
        } catch (err: any) {
            isError.value = true;
            alertMessage.value = err?.response?.data?.message || "Gagal ubah status akun.";
            return false;
        } finally {
            showAlert.value = true;
            setTimeout(() => {
                showAlert.value = false;
            }, 3000);
        }
    };


    return {
        // DATE_RANGE,
        DATA_TABLE,
        COLUMNS_USER,
        DATA_TIPE_AKSES,
        filteredData,
        showAlert, isError, alertMessage, isEditMode, form, dialogVisibleEdit, dialogVisibleAdd, dialogVisibleDelete, resetForm,
        // CHANGE_DATE_RANGE,
        // DEFAULT_DATE_RANGE,
        // REFRESH_DATA,
        GET_USER_DATA,
        GET_TIPE_AKSES_DATA,
        CREATE_USER,
        UPDATE_USER,
        DELETE_USER,
        SUBMIT_ADD_USER,
        SUBMIT_UPDATE_USER,
        SUBMIT_DELETE_USER,
        HANDLE_EDIT,
        HANDLE_DELETE,
        UPDATE_STATUS_AKUN_AKSES
    }
})
