import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
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 ListToolbar from '../blocks/ListToolbar';

interface WalletRuleProps {
  ID: string;
  id_wallet: string;
  id_group: string;
  max_transaction_per_day: number | null;
  balance_minimum: number | null;
  balance_maximum: number | null;
  credit_limit: number | null;
  monthly_limit: number | null;
  status: string;
}

interface ContextProps {
  walletRules: WalletRuleProps[];
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_walletRule: WalletRuleProps | null) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_walletRule: WalletRuleProps | null) => void;
  selectedWalletRule: WalletRuleProps | null;
  getWalletRuleLists: (
    limit: number,
    page: number,
    with_deleted: boolean,
    order_field: any,
    order_direction: any
  ) => Promise<{ data: WalletRuleProps[]; totalCount: number } | undefined>;
}

const initialProps: ContextProps = {
  walletRules: [],
  showAddDialog: false,
  handleAddDialog: (show: boolean) => {},
  showEditDialog: false,
  handleEditDialog: (show: boolean, selected_walletRule: object | null) => {},
  showDeleteDialog: false,
  handleDeleteDialog: (show: boolean, selected_walletRule: object | null) => {},
  selectedWalletRule: null,
  getWalletRuleLists: async () => undefined
};

const ManageWalletRuleContext = createContext<ContextProps>(initialProps);
const API_URL_WALLET = apiConfig.service_wallet;

const ManageWalletRuleContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [walletRules, setWalletRules] = useState<WalletRuleProps[]>([]);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedWalletRule, setSelectedWalletRule] = useState<WalletRuleProps | null>(null);
  const { GetData } = useCallApi();

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

  const handleEditDialog = useCallback(
    (show: boolean, selected_walletRule: WalletRuleProps | null) => {
      setShowEditDialog(show);
      setSelectedWalletRule(show ? selected_walletRule : null);
    },
    []
  );

  const handleDeleteDialog = useCallback(
    (show: boolean, selected_walletRule: WalletRuleProps | null) => {
      setShowDeleteDialog(show);
      setSelectedWalletRule(show ? selected_walletRule : null);
    },
    []
  );

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.wallet.name,
        id: 'wallet_name',
        header: ({ column }) => <DataGridColumnHeader title="Wallet Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.group.name,
        id: 'group_name',
        header: ({ column }) => <DataGridColumnHeader title="Group Name" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.balance_minimum,
        id: 'balance_minimum',
        header: ({ column }) => <DataGridColumnHeader title="Balance Minimum" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.balance_maximum,
        id: 'balance_maximum',
        header: ({ column }) => <DataGridColumnHeader title="Balance Maximum" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.credit_limit,
        id: 'credit_limit',
        header: ({ column }) => <DataGridColumnHeader title="Credit Limit" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.max_transaction_per_day,
        id: 'max_transaction_per_day',
        header: ({ column }) => (
          <DataGridColumnHeader title="Max Transaction Per Day" column={column} />
        ),
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        accessorFn: (row) => row.monthly_limit,
        id: 'monthly_limit',
        header: ({ column }) => <DataGridColumnHeader title="Monthly Limit" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[250px]'
        }
      },
      {
        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',
        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'
        }
      }
    ],
    []
  );

  const getWalletRuleLists = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
      const response = await GetData(`${API_URL_WALLET}/dashboard/wallet_rule`, {
        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);
      setWalletRules(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching Wallet Rule', error);
    }
  };

  return (
    <ManageWalletRuleContext.Provider
      value={{
        walletRules: walletRules,
        showAddDialog,
        handleAddDialog,
        showEditDialog,
        handleEditDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedWalletRule: selectedWalletRule,
        getWalletRuleLists
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />
      <DataGridProvider
        columns={columns}
        pagination={{ size: 10 }}
        toolbar={<ListToolbar />}
        layout={{ card: true }}
        sorting={[{ id: 'id', desc: false }]}
        serverSide={true}
        onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
          getWalletRuleLists(pageIndex, pageSize, sorting, columnFilters)
        }
      >
        {children}
      </DataGridProvider>
    </ManageWalletRuleContext.Provider>
  );
};

export { ManageWalletRuleContext, ManageWalletRuleContextProvider };
export type { WalletRuleProps };
