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';

// Helper function for number formatting with currency format
const formatNumber = (num: number, currencyCode: string = 'USD'): string => {
  return num.toLocaleString('en-US', {
    style: 'currency',
    currency: currencyCode,
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

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: (
    page: number,
    limit: number,
    sorting: any,
    filter: 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: 'id_wallet',
        header: ({ column }) => <DataGridColumnHeader title="Wallet ID" column={column} />,
        enableSorting: false,
        enableHiding: true, // Hide this column from view but use it for filtering
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'amount',
        header: ({ column }) => <DataGridColumnHeader title="Amount" column={column} />,
        cell: ({ row }) => {
          // Get currency code from the nested data structure if available
          const currencyCode = row.original.balance_type?.currency?.code || 'USD';
          return formatNumber(row.original.amount, currencyCode);
        },
        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="Amount This Month" column={column} />,
        cell: ({ row }) => {
          // Get currency code from the nested data structure if available
          const currencyCode = row.original.balance_type?.currency?.code || 'USD';
          return formatNumber(row.original.amount_this_month, currencyCode);
        },
        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 = sorting.length > 0 ? sorting[0].id : 'created_at';
      const sortDirection = sorting.length > 0 ? (sorting[0].desc ? 'ASC' : 'DESC') : 'DESC';

      // Initialize filter object
      let filterParams: any = {};

      // Process filter array
      if (Array.isArray(filter)) {
        filter.forEach((f: any) => {
          // Handle MSISDN search
          if (f.id === 'msisdn' && f.value) {
            filterParams.msisdn = { like: `%${f.value.toLowerCase()}%` };
          }

          // Handle date range filter
          if (f.id === 'CreatedAt' && f.value?.from && f.value?.to) {
            filterParams.created_at = {
              from: `${f.value.from} 00:00:00`,
              to: `${f.value.to} 23:59:59`
            };
          }

          // Handle wallet ID filter
          if (f.id === 'id_wallet' && f.value) {
            filterParams.id_wallet = f.value;
          }
        });
      }

      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(filterParams)
      });

      if (!response || !response.data) {
        console.warn('No data received:', response);
        return { data: [], totalCount: 0 };
      }

      setWallets(response?.data.list);
      return { data: response?.data.list, totalCount: response?.data.total_count };
    } catch (error) {
      console.error('Error fetching Wallet', error);
      return { data: [], totalCount: 0 };
    }
  };

  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 }}
        serverSide={true}
        onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
          getWalletLists(pageIndex, pageSize, sorting, columnFilters)
        }
      >
        {children}
      </DataGridProvider>
    </ManageWalletContext.Provider>
  );
};

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