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 { createContext, useCallback, useEffect, useMemo, useState } from 'react';
import ListToolbar from '../blocks/ListToolBar';

function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [value, delay]);

  return debouncedValue;
}

interface AccountProps {
  id: string;
  name: string;
}

interface TransferType {
  id: string;
  name: string;
  minimum_amount: number;
  maximum_amount: number;
  max_transaction_per_day: number;
  walletOriginId: string;
  walletDestinationId: string;
  status: string;
  type: string;
}

interface ContextProps {
  showEditDialog: boolean;
  handleEditDialog: (show: boolean, selected_user: string | null) => void;
  showAddDialog: boolean;
  handleAddDialog: (show: boolean) => void;
  showDeleteDialog: boolean;
  handleDeleteDialog: (show: boolean, selected_user: string | null) => void;
  selectedTransferType: string | null;
  transferType: string | null;
  accounts: AccountProps[];
  searchTerm: string;
  setSearchTerm: (term: string) => void;
}

const initialProps: ContextProps = {
  showEditDialog: false,
  handleEditDialog: () => {},
  showAddDialog: false,
  handleAddDialog: () => {},
  showDeleteDialog: false,
  handleDeleteDialog: () => {},
  selectedTransferType: null,
  accounts: [],
  transferType: null,
  searchTerm: '',
  setSearchTerm: () => {}
};

const ManageTransferTypeContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_transaction;

const ManageTransferTypeContextProvider = ({ children }: { children: React.ReactNode }) => {
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [selectedUser, setSelectedUser] = useState<string | null>(null);
  const [accounts, setAccount] = useState<AccountProps[]>([]);
  const { GetData } = useCallApi();
  const [selectedTransferType, setSelectedTransferType] = useState<string | null>(null);
  const [transferType, setTransferType] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState<string>('');
  
  const debouncedSearchTerm = useDebounce(searchTerm, 200);

  const handleEditDialog = useCallback((show: boolean, selected_transfertype: string | null) => {
    setSelectedTransferType(show ? selected_transfertype : null);
    setShowEditDialog(show);
  }, []);

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

  const handleDeleteDialog = useCallback((show: boolean, selected_transfertype: string | null) => {
    setSelectedTransferType(show ? selected_transfertype : null);
    setShowDeleteDialog(show);
  }, []);

  const columns = useMemo<ColumnDef<any>[]>(
    () => [
      {
        accessorFn: (row) => row.id,
        id: 'id',
        header: ({ column }) => (
          <DataGridColumnHeader title="Transaction Type ID" column={column} />
        ),
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[250px]' }
      },
      {
        accessorFn: (row) => row.name,
        id: 'name',
        header: ({ column }) => (
          <DataGridColumnHeader title="Transaction Type Name" column={column} />
        ),
        enableSorting: false,
        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.wallet_origin?.name || 'N/A',
        id: 'wallet_origin',
        header: ({ column }) => <DataGridColumnHeader title="From Account" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[250px]' }
      },
      {
        accessorFn: (row) => row.wallet_destination.name || 'N/A',
        id: 'wallet_destination',
        header: ({ column }) => <DataGridColumnHeader title="To Account" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[250px]' }
      },
      {
        accessorFn: (row) => row.maximum_amount,
        id: 'maximum_amount',
        header: ({ column }) => <DataGridColumnHeader title="Maximum Amount" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[250px]' }
      },
      {
        accessorFn: (row) => row.minimum_amount,
        id: 'minimum_amount',
        header: ({ column }) => <DataGridColumnHeader title="Minimum Amount" column={column} />,
        enableSorting: false,
        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: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[250px]' }
      },
      {
        accessorFn: (row: { type: string }) => {
          const mapping: Record<string, string> = {
            D: 'Disbursement',
            O: 'Other',
            CA: 'Change Group Emoney Customer to Agent',
            AC: 'Change Group Emoney Agent to Customer',
            PC: 'Change Group Point Agent to Customer',
            PA: 'Change Group Point Customer to Agent',
            CE: 'Return Customer Emoney',
            AD: 'Return Agent Deposit',
            AM: 'Return Agent Merchant',
            AE: 'Return Agent Emoney',
            R: 'Reward Point',
            TE:'Top Up Escrow',
            TM:'Top Up Master Agent',
            TA:'Top Up Agent'
          };

          return mapping[row.type] || 'Unknown';
        },
        id: 'type',
        header: ({ column }) => (
          <DataGridColumnHeader title="Status Transaction Type" column={column} />
        ),
        enableSorting: true,
        enableHiding: false,
        meta: { headerClassName: 'w-[250px]' }
      },
      {
        accessorFn: (row) => (row.status === 'Y' ? 'Active' : 'Inactive'),
        id: 'status',
        header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' }
      },
      {
        accessorFn: (row) => (row.status_approval === 'Y' ? 'Yes' : 'No'),
        id: 'status_approval',
        header: ({ column }) => <DataGridColumnHeader title="Approval Status" column={column} />,
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[150px]' }
      },
      {
        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.id)}
              >
                <KeenIcon icon="notepad-edit" />
              </button>
              <button
                className="btn btn-sm btn-icon btn-clear btn-light"
                onClick={() => handleDeleteDialog(true, row.id)}
              >
                <KeenIcon icon="trash" />
              </button>
            </>
          );
        },
        meta: { headerClassName: 'w-[100px]', cellClassName: 'text-center' }
      }
    ],
    [handleEditDialog, handleDeleteDialog]
  );

  const doGetTransferTypeListData = async (
    page: number,
    limit: number,
    sorting: any,
    filter: any
  ) => {
    const orderField = 'created_at';

    const orderDirection = sorting.length > 0 ? (sorting[0].desc ? 'DESC' : 'ASC') : 'DESC';

    const searchFilter = debouncedSearchTerm ? { any: debouncedSearchTerm.toLowerCase() } : {};
    
    filter = filter.length == 0 ? searchFilter : { any: filter[0].value?.toLowerCase() };

    const response = await GetData(`${API_URL}/transactiontype/list`, {
      limit: limit,
      page: page + 1,
      with_deleted: false,
      order_field: orderField,
      order_direction: orderDirection,
      filter: JSON.stringify(filter)
    });
    return { data: response?.data.list, totalCount: response?.data.total_count };
  };

  return (
    <div className="min-h-screen">
      <ManageTransferTypeContext.Provider
        value={{
          showEditDialog,
          handleEditDialog,
          showAddDialog,
          handleAddDialog,
          showDeleteDialog,
          handleDeleteDialog,
          selectedTransferType,
          accounts,
          transferType,
          searchTerm,
          setSearchTerm
        }}
      >
        <Toaster expand visibleToasts={9} duration={3000} />

        <div className="px-4">
          <DataGridProvider
            columns={columns}
            pagination={{ size: 10 }}
            layout={{ card: true }}
            toolbar={<ListToolbar />}
            sorting={[{ id: 'created_at', desc: true }]}
            serverSide={true}
            onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
              doGetTransferTypeListData(pageIndex, pageSize, sorting, columnFilters)
            }
          >
            {children}
          </DataGridProvider>
        </div>
      </ManageTransferTypeContext.Provider>
    </div>
  );
};

export { ManageTransferTypeContext, ManageTransferTypeContextProvider };
export type { TransferType };