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

interface ContextProps {
  showSearchDialog: boolean;
  handleSearchDialog: (show: boolean) => void;
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_user: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_user: string | null) => void;
  selectedUser: string | null;
}

interface SelectedUser {
  id: string;
  name: string;
  email: string;
  username: string;
  role: string;
  new_password: string;
  check_new_password: string;
  customer: string;
}

const initialProps: ContextProps = {
  showSearchDialog: false,
  handleSearchDialog: (show: boolean) => {},
  showEditDialog: false,
  handleEditDialog: () => {},
  showAddDialog: false,
  handleAddDialog: () => {},
  showDeleteDialog: false,
  handleDeleteDialog: () => {},
  selectedUser: null
};

const ManageUserContext = createContext<ContextProps>(initialProps);

const API_URL = apiConfig.service_dashboard;

const ManageUserContextProvider = ({ children }: { children: React.ReactNode }) => {
  /* state */
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showSearchDialog, setShowSearchDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedUser, setSelectedUser] = useState<string | null>(null);
  const { GetData } = useCallApi();

  /* action */
  const handleSearchDialog = useCallback((show: boolean) => {
    setShowSearchDialog(show);
  }, []);

  const handleEditDialog = useCallback((show: boolean, selected_user: string | null) => {
    setSelectedUser(show ? selected_user : null);
    setShowEditDialog(show);
  }, []);

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

  const handleDeleteDialog = useCallback((show: boolean, selected_user: string | null) => {
    setSelectedUser(show ? selected_user : null);
    setShowDeleteDialog(show);
  }, []);

  /* Data Grid Options */
  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorKey: 'username',
        id: 'username',
        header: ({ column }) => <DataGridColumnHeader title="Username" column={column} />,
        enableSorting: true,
        enableHiding: false
      },
      {
        accessorFn: (row) => row.customer?.username,
        id: 'Users.customer',
        header: ({ column }) => <DataGridColumnHeader title="Customer" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[300px]'
        }
      },
      {
        accessorFn: (row) => row.email,
        id: 'email',
        header: ({ column }) => <DataGridColumnHeader title="Email" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[350px]'
        }
      },
      {
        accessorFn: (row) => row.name,
        id: 'Users.name',
        header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.role.name,
        id: 'Users.role',
        header: ({ column }) => <DataGridColumnHeader title="Role Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        cell: (data: any) => {
          const { role } = data.row.original;
          // console.log('role :', role);
          let html = <p className="text-danger italic">Unassigned</p>;
          if (role && role.name) html = role.name;
          return html;
        },
        meta: {
          headerClassName: 'w-[350px]'
        }
      },
      {
        accessorFn: (row) => row.status,
        id: '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',
        enableSorting: false,
        enableHiding: false,
        header: ({ column }) => <DataGridColumnHeader title="Action" column={column} />,
        cell: (data: any) => {
          const row = data.row.original;

          return (
            <>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleEditDialog(true, row.id)}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleDeleteDialog(true, row.id)}
              >
                <KeenIcon icon="trash" />
              </button>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const doGetListData = async (page: number, limit: number, sorting: any, filter: any) => {
    const USER_TABLE_COLUMNS = ['username', 'email', 'name', 'status'];

    // ➕ Tambahkan prefix ke field dari tabel Users
    const mappedSorting = sorting.map((sort: any) => ({
      ...sort,
      id: USER_TABLE_COLUMNS.includes(sort.id) ? `Users.${sort.id}` : sort.id
    }));

    const orderField = mappedSorting[0]?.id ?? 'Users.username';
    const orderDirection = mappedSorting[0]?.desc === false ? 'DESC' : 'ASC';

    filter =
      filter.length == 0
        ? {}
        : { 'Users.username': { like: `%${filter[0].value?.toLowerCase()}%` } };
    const response = await GetData(`${API_URL}/user/list`, {
      limit: limit,
      page: page + 1,
      with_deleted: false,
      order_field: orderField,
      order_direction: orderDirection,
      filter: JSON.stringify(filter)
    });
    // console.log('response api:', response);

    return { data: response?.data.list, totalCount: response?.data.total_count };
  };

  return (
    <ManageUserContext.Provider
      value={{
        showSearchDialog,
        handleSearchDialog,
        showEditDialog,
        handleEditDialog,
        selectedUser,
        showAddDialog,
        handleAddDialog,
        showDeleteDialog,
        handleDeleteDialog
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

      <DataGridProvider
        columns={columns}
        pagination={{ size: 10 }}
        toolbar={<ListToolBar />}
        layout={{ card: true }}
        sorting={[{ id: 'Users.created_at', desc: false }]}
        serverSide={true}
        onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
          doGetListData(pageIndex, pageSize, sorting, columnFilters)
        }
      >
        {children}
      </DataGridProvider>
    </ManageUserContext.Provider>
  );
};

export { ManageUserContextProvider, ManageUserContext };
export type { SelectedUser };
