import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { useManageTransferTypeContext } from '../hooks/useManageTransferTypeContext';
import { Button } from '@/components/ui/button';
import { useEffect, useState } from 'react';
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem
} from '@/components/ui/select';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';

interface TransferType {
  id: number;
  name: string;
  type: string;
  wallet_origin: { id: number; name: string };
  wallet_destination: { id: number; name: string };
  status_approval: string;
}

const API_URL = apiConfig.service_transaction;

const typeLabelMap: 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'
};

const ListToolbar = () => {
  const { table, reload } = useDataGrid();
  const { handleAddDialog } = useManageTransferTypeContext();
  const [transferTypes, setTransferTypes] = useState<TransferType[]>([]);
  const { GetData } = useCallApi();
  const [statusKind, setStatusKind] = useState('');
  const [searchValue, setSearchValue] = useState('');
  const [statusTypes, setStatusTypes] = useState('');
  const [approval, setApproval] = useState('');

  const unique = (arr: string[]) => Array.from(new Set(arr));
  const types = unique(transferTypes.map((t) => t.type));

  const handleKeyDown = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter') {
      table.getColumn('name')?.setFilterValue(searchValue);
      table.setPageIndex(0);
    }
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      table.getColumn('name')?.setFilterValue(searchValue);
      table.setPageIndex(0);
    }, 200);
    return () => clearTimeout(timer);
  }, [searchValue, table]);

  useEffect(() => {
    table.getColumn('type')?.setFilterValue(statusTypes);
  }, [statusTypes, table]);

  useEffect(() => {
    table.getColumn('status_approval')?.setFilterValue(approval);
  }, [approval, table]);

  useEffect(() => {
    table.getColumn('status_kind')?.setFilterValue(statusKind);
  }, [statusKind, table]);

  const fetchTransferTypes = async () => {
    try {
      const response = await GetData(`${API_URL}/transactiontype/list`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: 'created_at',
        order_direction: 'ASC'
      });
      setTransferTypes(response?.data.list || []);
    } catch (error) {
      console.error('Error fetching transfer types', error);
    }
  };

  useEffect(() => {
    fetchTransferTypes();
  }, []);

  const handleClearFilter = () => {
    setSearchValue('');
    setStatusTypes('');
    setApproval('');
    setStatusKind('');

    table.getColumn('status_kind')?.setFilterValue('');
    table.getColumn('name')?.setFilterValue('');
    table.getColumn('type')?.setFilterValue('');
    table.getColumn('status_approval')?.setFilterValue('');

    setTimeout(() => {
      table.setPageIndex(0);
      reload();
    }, 0);
  };

  return (
    <div className="card-header flex-wrap border-b-0 px-5">
      <div className="flex flex-wrap gap-1 w-full">
        <div className="flex justify-between w-full items-center mb-3">
          <div className="flex flex-nowrap items-end gap-3 w-full overflow-x-auto">
            <div className="relative w-48 shrink-0">
              <div className="absolute left-3 top-1/2 transform -translate-y-1/2 pointer-events-none ">
                <KeenIcon icon="magnifier" />
              </div>
              <input
                type="text"
                placeholder="Search Name"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                className="input input-sm  w-full pl-9 text-ellipsis overflow-hidden"
                onKeyDown={handleKeyDown}
              />
            </div>

            <div className="min-w-[220px] shrink-0">
              <Select
                key={`type-filter-${statusTypes}`}
                value={statusTypes}
                onValueChange={setStatusTypes}
              >
                <SelectTrigger className="h-8">
                  <SelectValue
                    placeholder="Select Status Transaction Type"
                    className="text-ellipsis overflow-hidden"
                  />
                </SelectTrigger>
                <SelectContent className="max-h-64 overflow-y-auto">
                  {types.map((opt) => (
                    <SelectItem key={opt} value={opt} className="truncate">
                      {typeLabelMap[opt] ?? opt}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="min-w-[220px] shrink-0">
              <Select
                key={`approval-filter-${approval}`}
                value={approval}
                onValueChange={setApproval}
              >
                <SelectTrigger className="h-8">
                  <SelectValue
                    placeholder="Select Status Approval"
                    className="text-ellipsis overflow-hidden"
                  />
                </SelectTrigger>
                <SelectContent className="max-h-64 overflow-y-auto">
                  <SelectItem value="Y" className="truncate">
                    Yes
                  </SelectItem>
                  <SelectItem value="N" className="truncate">
                    No
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="min-w-[220px] shrink-0">
              <Select
                key={`status-kind-filter-${statusKind}`}
                value={statusKind}
                onValueChange={setStatusKind}
              >
                <SelectTrigger className="h-8">
                  <SelectValue
                    placeholder="Select Status Kind"
                    className="text-ellipsis overflow-hidden"
                  />
                </SelectTrigger>
                <SelectContent className="max-h-64 overflow-y-auto">
                  <SelectItem value="R">Return</SelectItem>
                  <SelectItem value="T">Transfer</SelectItem>
                  <SelectItem value="P">Purchase</SelectItem>
                  <SelectItem value="W">Withdraw</SelectItem>
                  <SelectItem value="U">Top Up</SelectItem>
                  <SelectItem value="N">Top Up Patner</SelectItem>
                  <SelectItem value="E">Reward</SelectItem>
                  <SelectItem value="L">Purchase Loja</SelectItem>
                  <SelectItem value="B">Top Up P24</SelectItem>
                  <SelectItem value="A">Transfer Agent</SelectItem>
                  <SelectItem value="M">Withdraw Agent</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <DefaultTooltip title={'Reset Filter'} placement={'top'}>
              <Button
                variant="outline"
                className="h-7.5 disabled:bg-gray-400 shrink-0"
                onClick={handleClearFilter}
              >
                <KeenIcon icon="arrow-circle-left" />
              </Button>
            </DefaultTooltip>
          </div>

          <div className="flex gap-2 items-center ml-2 shrink-0">
            <Button
              variant="outline"
              className="h-8 px-3 text-xs"
              onClick={() => handleAddDialog(true)}
            >
              Add
            </Button>
            <DefaultTooltip title="Refresh" placement="top">
              <Button variant="outline" className="h-8 px-3" onClick={() => reload()}>
                <KeenIcon icon="arrows-circle" />
              </Button>
            </DefaultTooltip>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ListToolbar;
