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

const ListToolbar = () => {
  const { table, reload } = useDataGrid();
  const { GetData } = useCallApi();

  const [searchValue, setSearchValue] = useState<string>(
    (table.getColumn('msisdn')?.getFilterValue() as string) ?? ''
  );
  const [dateRange, setDateRange] = useState({ from: '', to: '' });
  const [walletId, setWalletId] = useState<string>(
    (table.getColumn('id_wallet')?.getFilterValue() as string) ?? ''
  );
  const [wallets, setWallets] = useState<WalletProps[]>([]);

  const formatDate = (date: Date): string => date.toISOString().split('T')[0];

  useEffect(() => {
    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    setDateRange({ from: formatDate(firstDayOfMonth), to: formatDate(today) });
  }, []);

  useEffect(() => {
    const timer = setTimeout(() => {
      table.getColumn('msisdn')?.setFilterValue(searchValue);
      table.setPageIndex(0);
    }, 200);

    return () => clearTimeout(timer);
  }, [searchValue, table]);

  const handleFilterByDate = useCallback(() => {
    try {
      table.getColumn('CreatedAt')?.setFilterValue(dateRange);
    } catch (error) {
      toast.error('Error applying date filter');
      console.error('Error applying date filter:', error);
    }
  }, [dateRange, table]);

  useEffect(() => {
    table.getColumn('id_wallet')?.setFilterValue(walletId);
    table.setPageIndex(0);
  }, [walletId, table]);

  useEffect(() => {
    if (dateRange.from && dateRange.to) {
      handleFilterByDate();
    }
  }, [dateRange, handleFilterByDate]);

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

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

  const handleClearAllFilters = () => {
    setSearchValue('');
    setWalletId('');

    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    setDateRange({
      from: formatDate(firstDayOfMonth),
      to: formatDate(today)
    });

    table.getAllColumns().forEach((column) => {
      if (column.id !== 'CreatedAt') {
        column.setFilterValue(undefined);
      }
    });

    table.setPageIndex(0);

    table.getColumn('CreatedAt')?.setFilterValue({
      from: formatDate(firstDayOfMonth),
      to: formatDate(today)
    });
  };

  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 gap-3 items-center flex-wrap">
            <label className="input input-sm w-[160px]">
              From
              <input
                type="date"
                value={dateRange.from}
                onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
              />
            </label>

            <label className="input input-sm w-[160px]">
              To
              <input
                type="date"
                value={dateRange.to}
                onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
              />
            </label>

            <label className="input input-sm w-1/3">
              <KeenIcon icon="magnifier" />
              <input
                type="text"
                placeholder="Search MSISDN"
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
              />
            </label>

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

            <Button variant="outline" size="sm" onClick={handleClearAllFilters}>
              Clear Filter
            </Button>
          </div>

          <div className="flex gap-3 items-center">
            <DefaultTooltip title={'Refresh'} placement={'top'}>
              <Button
                variant="outline"
                className="h-7.5"
                onClick={() => {
                  setSearchValue('');
                  setWalletId('');
                  table.setColumnFilters((prev) => prev.filter((f) => f.id === 'CreatedAt'));
                  table.setPageIndex(0);
                  reload();
                }}
              >
                <KeenIcon icon="arrows-circle" />
              </Button>
            </DefaultTooltip>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ListToolbar;
