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';
import ShowDetailDialog from '../blocks/ShowDetailDialog';

const formatNumber = (num: number): string => {
  return num.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

interface WalletProps {
  ID: string;
  id: string;
  id_wallet: string;
  name: string;
  id_currency: string;
  status: string;
}

interface ContextProps {
  wallets: WalletProps[];
  showDetailDialog: boolean;
  setShowDetailDialog: React.Dispatch<React.SetStateAction<boolean>>;
  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: [],
  showDetailDialog: false,
  setShowDetailDialog: () => {},
  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 [showDetailDialog, setShowDetailDialog] = useState(false);
  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: 'id_wallet',
        header: ({ column }) => <DataGridColumnHeader title="Wallet Name" column={column} />,
        cell: ({ row }) => row.original.name || 'Unknown Wallet',
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'msisdn',
        header: ({ column }) => <DataGridColumnHeader title="MSISDN" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[300px]',
          cellClassName: 'p-[20px]'
        }
      },
      {
        accessorKey: 'amount',
        header: ({ column }) => <DataGridColumnHeader title="Amount" column={column} />,
        cell: ({ row }) => formatNumber(row.original.amount),
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'total_debit',
        header: ({ column }) => <DataGridColumnHeader title="Total Debit" column={column} />,
        cell: ({ row }) => formatNumber(row.original.total_debit),
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'total_credit',
        header: ({ column }) => <DataGridColumnHeader title="Total Credit" column={column} />,
        cell: ({ row }) => formatNumber(row.original.total_credit),
        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 }) => formatNumber(row.original.amount_this_month),
        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]'
        }
      },
      {
        accessorKey: 'currency_name',
        header: ({ column }) => <DataGridColumnHeader title="Currency Name" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'currency_code',
        header: ({ column }) => <DataGridColumnHeader title="Currency Code" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'id_group',
        header: ({ column }) => <DataGridColumnHeader title="Group Name" column={column} />,
        cell: ({ row }) => row.original.group_name || 'Unknown Group',
        enableSorting: false,
        enableHiding: false,
        meta: {
          headerClassName: 'w-[200px]'
        }
      },
      {
        accessorKey: 'detail_statemenet',
        header: ({ column }) => <DataGridColumnHeader title="Detail Statement" column={column} />,
        enableSorting: false,
        enableHiding: false,
        cell: (data) => {
          const row = data.row.original;
          return (
            <div key={`detail_statement-${row.id}`} className="flex gap-2 justify-center">
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => {
                  setSelectedWallet({
                    ...row,
                    ID: row.ID || row.id
                  });
                  setShowDetailDialog(true);
                }}
              >
                {' '}
                <KeenIcon icon="eye" />
              </button>
            </div>
          );
        }
      }
      // {
      //   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';

      let filterParams: any = {};

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

          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`
            };
          }

          if (f.id === 'id_wallet' && f.value) {
            filterParams.id_wallet = f.value;
          }

          if (f.id === 'id_group' && f.value) {
            filterParams.id_group = 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 };
      }

      const walletsResponse = await GetData(`${API_URL_WALLET}/dashboard/wallet/`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: 'created_at',
        order_direction: 'ASC'
      });

      const groupsResponse = await GetData(`${API_URL_WALLET}/dashboard/group/`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: 'created_at',
        order_direction: 'ASC'
      });

      const currenciesResponse = await GetData(`${API_URL_WALLET}/dashboard/currency/`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: 'created_at',
        order_direction: 'ASC'
      });

      const walletsMap = walletsResponse?.data?.list
        ? walletsResponse.data.list.reduce((acc: any, wallet: any) => {
            acc[wallet.ID] = {
              name: wallet.name,
              id_currency: wallet.id_currency
            };
            return acc;
          }, {})
        : {};

      const groupsMap = groupsResponse?.data?.list
        ? groupsResponse.data.list.reduce((acc: any, group: any) => {
            acc[group.ID] = group.name;
            return acc;
          }, {})
        : {};

      const currenciesMap = currenciesResponse?.data?.list
        ? currenciesResponse.data.list.reduce((acc: any, currency: any) => {
            acc[currency.ID] = {
              name: currency.name,
              code: currency.code
            };
            return acc;
          }, {})
        : {};

      const enrichedData = response?.data.list.map((item: any) => {
        const walletInfo = walletsMap[item.id_wallet] || {
          name: 'Unknown Wallet',
          id_currency: null
        };
        const currencyInfo = currenciesMap[walletInfo.id_currency] || {
          name: 'Unknown Currency',
          code: 'USD'
        };

        return {
          ...item,
          name: walletInfo.name,
          group_name: groupsMap[item.id_group] || 'Unknown Group',
          currency_name: currencyInfo.name,
          currency_code: currencyInfo.code
        };
      });

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

  return (
    <ManageWalletContext.Provider
      value={{
        wallets,
        showDetailDialog,
        setShowDetailDialog,
        showAddDialog,
        handleAddDialog,
        showEditDialog,
        handleEditDialog,
        showDeleteDialog,
        handleDeleteDialog,
        selectedWallet,
        getWalletLists
      }}
    >
      <Toaster expand visibleToasts={9} duration={3000} />

      <ShowDetailDialog />

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