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 WalletProps {
  id: string;
  name: string;
  status: string;
  description: string;
  group: string[];
  currency_id: string;
}

interface ContextProps {
  wallet: WalletProps[];
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_wallet: WalletProps | null) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_wallet: WalletProps | null) => void;
  selectedWallet: WalletProps | null;
  getWalletLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: WalletProps[]; totalCount: number } | undefined>;
}

const initialProps: ContextProps = {
  wallet: [],
  showAddDialog: false,
  handleAddDialog: (show: boolean) => {},
  showEditDialog: false,
  handleEditDialog: (show: boolean, selected_wallet: WalletProps | null) => {},
  showDeleteDialog: false,
  handleDeleteDialog: (show: boolean, selected_wallet: WalletProps | null) => {},
  selectedWallet: null,
  getWalletLists: async () => ({ data: [], totalCount: 0 })
};

const ManageWalletContext = createContext<ContextProps>(initialProps);
const API_URL_MASTER_DATA = apiConfig.service_master_data;

const ManageWalletContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [wallets, setWallets] = useState<WalletProps[]>([]);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedWallet, setSelectedWallet] = useState<WalletProps | null>(null);
  const { GetData } = useCallApi();

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

  const handleEditDialog = useCallback((show: boolean, selected_wallet: WalletProps | null) => {
    setShowEditDialog(show);
    setSelectedWallet(show ? selected_wallet : null);
  }, []);

  const handleDeleteDialog = useCallback((show: boolean, selected_wallet: WalletProps | null) => {
    setShowDeleteDialog(show);
    setSelectedWallet(show ? selected_wallet : null);
  }, []);

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.name,
        id: 'wallets.name',
        header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.description,
        id: 'description',
        header: ({ column }) => <DataGridColumnHeader title="Description" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.status,
        id: 'wallets.status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: true,
        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] text-center',
          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>
            </>
          );
        },
        meta: {
          headerClassName: 'w-[100px] text-center',
          cellClassName: 'text-center'
        }
      }
    ],
    []
  );

  const getWalletLists = 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 response = await GetData(`${API_URL_MASTER_DATA}/wallet/list`, {
        limit,
        page: page + 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
        filter: JSON.stringify(filter)
      });
      // console.log(response?.data);
      setWallets(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching Wallet', error);
    }
  };

  return (
    <ManageWalletContext.Provider
      value={{
        wallet: wallets,
        showAddDialog,
        handleAddDialog,
        showEditDialog,
        handleEditDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedWallet,
        getWalletLists
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />
      <DataGridProvider
        columns={columns}
        pagination={{ size: 25 }}
        toolbar={<ListToolbar />}
        layout={{ card: true }}
        sorting={[{ id: 'wallets.created_at', desc: true }]}
        serverSide={true}
        onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
          getWalletLists(pageIndex, pageSize, sorting, columnFilters)
        }
      >
        {children}
      </DataGridProvider>
    </ManageWalletContext.Provider>
  );
};

export { ManageWalletContext, ManageWalletContextProvider };
export type { WalletProps };
