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

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

const formatInteger = (num: number): string => {
  return num.toLocaleString('en-US', {
    style: 'decimal',
    maximumFractionDigits: 0
  })
}

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 StatusBadge = ({
    value,
    map
  }: {
    value: string;
    map: Record<string, { label: string; color: string }>;
  }) => {
    const statusInfo = map[value] || { label: value || 'Unknown', color: 'gray' };
    const { label, color } = statusInfo;

    return (
      <span
        className={`px-2 py-1 text-xs font-semibold rounded-full bg-${color}-100 text-${color}-600`}
      >
        {label}
      </span>
    );
  };

  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} />,
        cell: ({ row }) => formatNumber(row.original.maximum_amount),
        enableSorting: false,
        enableHiding: false,
        meta: { headerClassName: 'w-[250px]' }
      },
      {
        accessorFn: (row) => row.minimum_amount,
        id: 'minimum_amount',
        header: ({ column }) => <DataGridColumnHeader title="Minimum Amount" column={column} />,
        cell: ({ row }) => formatNumber(row.original.minimum_amount),
        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} />
        ),
        cell: ({ row }) => formatInteger(row.original.max_transaction_per_day),
        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',
            PL: 'Purchase Loja',
            DE: 'Disbursment Escrow',
            DM: 'Disbursment Master Agent',
            DA: 'Disbursment Agent',
            WI: 'Withdraw Merchant',
            IC: 'Income Merchant',
            DN: 'Donation'
          };

          return mapping[row.type] || 'Unknown';
        },
        id: 'type',
        header: ({ column }) => (
          <DataGridColumnHeader title="Status Transaction Type" column={column} />
        ),
        enableSorting: false,
        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 status = row.original.status;
          const label = status === 'Y' ? 'Active' : 'Inactive';
          const color = status === 'Y' ? 'green' : 'red';

          return (
            <span
              className={`px-2 py-1 text-xs font-semibold rounded-full bg-${color}-100 text-${color}-600`}
            >
              {label}
            </span>
          );
        },
        meta: {
          headerClassName: 'w-[100px]',
          cellClassName: 'text-center'
        }
      },
      {
        accessorFn: (row) => row.status_kind,
        id: 'status_kind',
        header: ({ column }) => <DataGridColumnHeader title="Status Kind" column={column} />,
        enableSorting: false,
        enableHiding: false,
        cell: ({ row }) => {
          const kind = row.original.status_kind;

          const mapping: Record<string, { label: string; className: string }> = {
            R: { label: 'Return', className: 'bg-blue-100 text-blue-600' },
            T: { label: 'Transfer', className: 'bg-indigo-100 text-indigo-600' },
            P: { label: 'Purchase', className: 'bg-green-100 text-green-600' },
            W: { label: 'Withdraw', className: 'bg-fuchsia-100 text-fuchsia-600' },
            U: { label: 'Top Up', className: 'bg-yellow-100 text-yellow-600' },
            N: { label: 'Top Up Patner', className: 'bg-purple-100 text-purple-600' },
            E: { label: 'Reward', className: 'bg-rose-100 text-rose-600' },
            L: { label: 'Purchase Loja', className: 'bg-rose-100 text-rose-600' },
            B: { label: 'Top Up P24', className: 'bg-rose-100 text-rose-600' },
            A: { label: 'Transfer Agent', className: 'bg-rose-100 text-rose-600' },
            M: { label: 'Withdraw Agent', className: 'bg-rose-100 text-rose-600' }
          };

          const kindInfo = mapping[kind] || {
            label: 'Unknown',
            className: 'bg-gray-100 text-gray-600'
          };

          return (
            <span className={`px-2 py-1 text-xs font-semibold rounded-full ${kindInfo.className}`}>
              {kindInfo.label}
            </span>
          );
        },
        meta: { headerClassName: 'w-[250px]', cellClassName: 'text-center' }
      },
      {
        accessorFn: (row) => row.status_approval,
        id: 'status_approval',
        header: ({ column }) => <DataGridColumnHeader title="Approval Status" column={column} />,
        enableSorting: false,
        enableHiding: false,
        cell: ({ row }) => {
          const approval = row.original.status_approval;
          const label = approval === 'Y' ? 'Yes' : 'No';
          const color = approval === 'Y' ? 'green' : 'red';

          return (
            <span
              className={`px-2 py-1 text-xs font-semibold rounded-full bg-${color}-100 text-${color}-600`}
            >
              {label}
            </span>
          );
        },
        meta: { headerClassName: 'w-[150px]', 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.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,
    columnFilters: any
  ) => {
    const orderField = 'created_at';
    const orderDirection = sorting.length > 0 ? (sorting[0].desc ? 'DESC' : 'ASC') : 'DESC';

    let filterObject: Record<string, any> = {};

    if (debouncedSearchTerm) {
      filterObject['any'] = debouncedSearchTerm.toLowerCase();
    }

    if (columnFilters.length > 0) {
      columnFilters.forEach((filter: any) => {
        if (filter.id && filter.value) {
          if (filter.id === 'name') {
            filterObject['any'] = filter.value.toLowerCase();
          } else if (filter.id === 'wallet_origin') {
            filterObject['wallet_origin.name'] = filter;
          } else if (filter.id === 'wallet_destination') {
            filterObject['wallet_destination.name'] = filter.value;
          } else if (filter.id === 'status_kind') {
            filterObject[filter.id] = filter.value;
          } else if (filter.id === 'status_approval') {
            filterObject[filter.id] = filter.value;
          } else if (filter.id === 'type') {
            filterObject[filter.id] = filter.value;
          } else {
            filterObject[filter.id] = filter.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(filterObject)
    });
    // console.log(response);
    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 };
