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 WalletProps {
  id: string;
  name: string;
  id_currency: string;
  status: string;
}

interface ContextProps {
  wallets: 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 = {
  wallets: [],
  showAddDialog: false,
  handleAddDialog: (show: boolean) => {},
  showEditDialog: false,
  handleEditDialog: (show: boolean, selected_wallet: object | null) => {},
  showDeleteDialog: false,
  handleDeleteDialog: (show: boolean, selected_wallet: object | null) => {},
  selectedWallet: null,
  getWalletLists: async () => undefined
};

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

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>[]>(
    () => [
      {
        accessorKey: 'msisdn',
        header: ({ column }) => <DataGridColumnHeader title="MSISDN" column={column} />,
        enableSorting: true,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[550px]',
          cellClassName: 'p-[20px]'
        }
      },
      {
        accessorKey: 'amount' ,
        header: ({ column }) => <DataGridColumnHeader title="Amount" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'trx_count_today' ,
        header: ({ column }) => <DataGridColumnHeader title="Transaction Count Today" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'amount_this_month' ,
        header: ({ column }) => <DataGridColumnHeader title="Ammount This Month" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'CreatedAt',
        header: ({ column }) => (
          <DataGridColumnHeader title="Created At" column={column} />
        ),
        cell: ({ row }) => 
          new Date(row.original.CreatedAt).toLocaleString('id-ID', {
            day: '2-digit',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
          }),
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorFn: (row) => row.balance_type.name,
        id: 'balance_type_name',
        header: ({ column }) => <DataGridColumnHeader title="Balance Type Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorFn: (row) => row.balance_type.currency.name,
        id: 'currency_name',
        header: ({ column }) => <DataGridColumnHeader title="Currency Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorFn: (row) => row.balance_type.currency.code,
        id: 'currency_code',
        header: ({ column }) => <DataGridColumnHeader title="Currency Code" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorFn: (row) => row.group.name,
        id: 'group_name',
        header: ({ column }) => <DataGridColumnHeader title="Group Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorFn: (row) => row.group.is_bank,
        id: 'is_bank',
        header: ({ column }) => <DataGridColumnHeader title="Is Bank" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      }
    ],
    []
  );

  const getWalletLists = async (page: number, limit: number, sorting: any, filter: any) => {
    try {
      const sortField = 'CreatedAt';
      const sortDirection = 'ASC';
      
      filter = filter.length == 0 ? {} : { name: filter[0].value?.toLowerCase() };
      const response = await GetData(`${API_URL_WALLET}/dashboard/balance/`, {
        limit,
        page: page + 1,
        with_deleted: false,
        order_field: sortField,
        order_direction: sortDirection,
        // filter: JSON.stringify(filter)
      });
      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={{
        wallets,
        showAddDialog,
        handleAddDialog,
        showEditDialog,
        handleEditDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedWallet,
        getWalletLists
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />
      <DataGridProvider
        columns={columns}
        pagination={{ size: 10 }}
        toolbar={<ListToolbar />}
        layout={{ card: true }}
        // sorting={[{ id: '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 };