// interface SelectedMenu {
//   id: string;
//   module: string;
//   name: string;
//   id_parent: string;
//   order_number: number;
//   icon: string;
//   application: string;
//   status: string;
// }

import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { ColumnDef } from '@tanstack/react-table';
import React, { createContext, useCallback, useMemo, useState } from 'react';
import { Toaster } from 'sonner';
import ListToolbar from '../blocks/ListToolbar';

interface MenuProps {
  id: string;
  module: string;
  name: string;
  id_parent: string;
  order_number: number;
  icon: string;
  status: string;
}

const initialState = {
  id: '',
  module: '',
  name: '',
  link: '',
  id_parent: '',
  order_number: 0,
  icon: '',
  status: ''
};

interface ContextProps {
  menus: MenuProps[];
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_postoAdms: object | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_postoAdms: object | null) => void;
  selectedMenu: object | null;
  getMenusLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: MenuProps[]; totalCount: number } | undefined>;
  setSelectedMenu: (data: object) => void;
  parents: any;
}

const initialProps: ContextProps = {
  menus: [],
  showAddDialog: false,
  handleAddDialog: (show: boolean) => {},
  showEditDialog: false,
  handleEditDialog: (show: boolean, selected_menu: object | null) => {},
  showDeleteDialog: false,
  handleDeleteDialog: (show: boolean, selected_menu: object | null) => {},
  selectedMenu: initialState,
  getMenusLists: async () => ({ data: [], totalCount: 0 }),
  setSelectedMenu: (data: object) => {},
  parents: []
};

const ManageMenusContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_dashboard;

const ManageMenusContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [menus, setMenus] = useState<MenuProps[]>([]);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedMenu, setSelectedMenu] = useState<object | null>(initialState);
  const [parents, setParents] = useState<any>([]);
  const { GetData } = useCallApi();

  const handleAddDialog = useCallback((show: boolean) => {
    setShowAddDialog(show);
  }, []);

  const handleEditDialog = useCallback((show: boolean, selected_menu: object | null) => {
    if (show) setSelectedMenu(selected_menu);
    setShowEditDialog(show);
  }, []);

  const handleDeleteDialog = useCallback((show: boolean, selected_menu: object | null) => {
    if (show) setSelectedMenu(selected_menu);
    setShowDeleteDialog(show);
  }, []);

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.module,
        id: 'module',
        header: ({ column }) => <DataGridColumnHeader title="Module" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[200px]' }
      },
      {
        accessorFn: (row) => row.parentName || row.module,
        id: 'menu',
        header: ({ column }) => <DataGridColumnHeader title="Menu" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[200px]' }
      },
      {
        accessorFn: (row) => row.name,
        id: 'name',
        header: ({ column }) => <DataGridColumnHeader title="Sub Menu" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[200px]' }
      },
      {
        accessorFn: (row) => row.link,
        id: 'link',
        header: ({ column }) => <DataGridColumnHeader title="URL" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[250px]' }
      },
      {
        accessorKey: 'status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: false,
        enableHiding: false,
        cell: ({ row }) => {
          const isActive = row.original.status === 'Y';

          return (
            <span
              className={`px-2 py-1 text-xs font-semibold rounded-full ${
                isActive ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'
              }`}
            >
              {isActive ? 'Active' : 'Inactive'}
            </span>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      },
      {
        id: 'actions',
        header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
        enableSorting: false,
        enableHiding: false,
        cell: (data) => {
          const row = data.row.original;
          return (
            <>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleEditDialog(true, row)}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleDeleteDialog(true, row)}
              >
                <KeenIcon icon="trash" />
              </button>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const flattenChildren = (parent: any, parentIdx: number, depth = 0, parentName = '') => {
    let result: any[] = [];

    if (parent.id_parent === null) {
      if (!parents.find((el: any) => el.id === parent.id))
        setParents((el: any) => [...el, { id: parent.id, name: parent.name }]);

      result.push({
        id: parent.id,
        module: parent.module,
        parentName: parentName || parent.name,
        name: parent.name,
        link: parent.link,
        id_parent: parent.id_parent,
        status: parent.status,
        order_number: parent.order_number
      });
    }

    if (!parent.children || parent.children.length === 0) {
      return result;
    }

    const childrenFlattened = parent.children.flatMap((child: any, childIdx: number) => {
      if (child.children && child.children.length > 0) {
        return flattenChildren(child, parentIdx * 100 + childIdx, depth + 1, child.name);
      }

      return {
        id: child.id,
        module: parent.module,
        parentName: parentName || parent.name,
        name: child.name,
        link: child.link,
        id_parent: child.id_parent,
        status: child.status,
        order_number: parent.order_number
      };
    });

    return [...result, ...childrenFlattened];
  };

  const getMenusLists = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      sorting = sorting.length === 0 ? [{ id: 'name', desc: false }] : sorting;
      filter = filter.length === 0 ? {} : { name: { like: `%${filter[0].value?.toLowerCase()}%` } };

      const query: any = {
        limit,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc ? 'DESC' : 'ASC'
      };

      if (filter && Object.keys(filter).length > 0) {
        query.filter = JSON.stringify(filter);
        query.page = page + 1;
      }

      const response = await GetData(`${API_URL}/menus/list`, query);

      if (query.filter && query.filter.length > 0) {
        return { data: response?.data.list, totalCount: response?.data.total_count };
      } else {
        const transformedData = response?.data.list.flatMap((row: any, parentIdx: number) =>
          flattenChildren(row, parentIdx)
        );

        const total_count = transformedData.length;

        // **Pagination di frontend saja (tanpa hit API ulang)**
        const paginatedData = transformedData.slice(page * limit, (page + 1) * limit);
        const totalPages = Math.ceil(total_count / limit);

        return { data: paginatedData, totalCount: total_count };
      }
    } catch (error) {
      console.error('Error fetching Menus', error);
      return { data: [], totalCount: 0 };
    }
  };

  return (
    <ManageMenusContext.Provider
      value={{
        menus,
        showAddDialog,
        handleAddDialog,
        showEditDialog,
        handleEditDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedMenu,
        getMenusLists,
        setSelectedMenu,
        parents
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

      <DataGridProvider
        columns={columns}
        pagination={{ size: 25 }}
        toolbar={<ListToolbar />}
        layout={{ card: true }}
        sorting={[{ id: 'created_at', desc: true }]}
        serverSide={true}
        onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
          getMenusLists(pageIndex, pageSize, sorting, columnFilters)
        }
      >
        {children}
      </DataGridProvider>
    </ManageMenusContext.Provider>
  );
};

export { ManageMenusContextProvider, ManageMenusContext };
export type { MenuProps };
