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

const API_URL_WALLET = apiConfig.service_wallet;

interface WalletProps {
  ID: string;
  name: string;
}

interface GroupProps {
  ID: string;
  name: string;
}

const ListToolbar = ({
  filters,
  setFilters
}: {
  filters: any;
  setFilters: (value: any) => void;
}) => {
  const { table, reload } = useDataGrid();
  const { GetData } = useCallApi();

  const [searchValue, setSearchValue] = useState('');
  const [wallets, setWallets] = useState<WalletProps[]>([]);
  const [walletId, setWalletId] = useState<string | null>(null);
  const [groups, setGroups] = useState<GroupProps[]>([]);
  const [groupId, setGroupId] = useState<string | null>(null);

  const fetchWallets = async () => {
    try {
      const response = await GetData(`${API_URL_WALLET}/dashboard/wallet/`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: 'created_at',
        order_direction: 'ASC'
      });
      setWallets(response?.data.list || []);
    } catch (error) {
      console.error('Error fetching wallets', error);
    }
  };

  const fetchGroups = async () => {
    try {
      const response = await GetData(`${API_URL_WALLET}/dashboard/group/`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: 'created_at',
        order_direction: 'ASC'
      });
      setGroups(response?.data.list || []);
    } catch (error) {
      console.error('Error fetching groups', error);
    }
  };

  useEffect(() => {
    fetchWallets();
    fetchGroups();
  }, []);

  const handleApplyFilters = () => {
    const appliedFilters: any[] = [];

    if (searchValue) {
      appliedFilters.push({ id: 'msisdn', value: searchValue });
    }

    if (walletId) {
      appliedFilters.push({ id: 'id_wallet', value: walletId });
    }

    if (groupId) {
      appliedFilters.push({ id: 'id_group', value: groupId });
    }

    setFilters(appliedFilters);
  };

  const handleClearAllFilters = () => {
    setSearchValue('');
    setWalletId(null);
    setGroupId(null);
    setFilters([]);

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

  const handleRefresh = () => {
    table.setPageIndex(0);
    reload();
  };

  useEffect(() => {
    table.setPageIndex(0); 
    reload();
  }, [filters]);

  return (
    <div className="card-header flex-wrap gap-2 border-b-0 px-5">
      <div className="flex flex-wrap gap-2 lg:gap-5 w-full">
        <div className="flex justify-between w-full items-center">
          <div className="flex flex-wrap items-end gap-3 w-full">
            <label className="input input-sm w-[160px]">
              <KeenIcon icon="magnifier" />
              <input
                type="text"
                placeholder="Search MSISDN"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                className="overflow-hidden text-ellipsis w-full"
              />
            </label>

            <div className="w-[160px]">
              <Select value={walletId ?? ''} onValueChange={(value) => setWalletId(value)}>
                <SelectTrigger className="h-[32px]">
                  <SelectValue placeholder="Select Wallet" />
                </SelectTrigger>
                <SelectContent>
                  {wallets.map((wallet) => (
                    <SelectItem key={wallet.ID} value={wallet.ID}>
                      {wallet.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="w-[160px]">
              <Select value={groupId ?? ''} onValueChange={(value) => setGroupId(value)}>
                <SelectTrigger className="h-[32px]">
                  <SelectValue placeholder="Select Group" />
                </SelectTrigger>
                <SelectContent>
                  {groups.map((group) => (
                    <SelectItem key={group.ID} value={group.ID}>
                      {group.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

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

            <Button variant="default" className="h-8" onClick={handleApplyFilters}>
              Filter Data
            </Button>
          </div>

          <div className="flex gap-3 items-center">
            <DefaultTooltip title={'Refresh'} placement={'top'}>
              <Button variant="outline" className="h-7.5" onClick={handleRefresh}>
                <KeenIcon icon="arrows-circle" />
              </Button>
            </DefaultTooltip>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ListToolbar;
