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 getOneMonthsAgo = () => {
  const today = new Date();
  return new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
};

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

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[]>([]);

  useEffect(() => {
    const today = new Date();
    const threeMonthsAgo = getOneMonthsAgo();
    setDateRange({ from: formatDate(threeMonthsAgo), 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 = () => {
    const today = new Date();
    const oneMonthAgo = getOneMonthsAgo();
    const resetDateRange = {
      from: formatDate(oneMonthAgo),
      to: formatDate(today)
    };
  
    setSearchValue('');
    setWalletId('');
    setDateRange(resetDateRange);
  
    table.getColumn('msisdn')?.setFilterValue('');
    table.getColumn('id_wallet')?.setFilterValue('');
    table.getColumn('CreatedAt')?.setFilterValue(resetDateRange);
  
    setTimeout(() => {
      table.setPageIndex(0);
      reload();
    }, 0);
  };
  

  const handleRefresh = () => {
    const today = new Date();
    const threeMonthsAgo = getOneMonthsAgo();
    const resetDateRange = {
      from: formatDate(threeMonthsAgo),
      to: formatDate(today)
    };

    setSearchValue('');
    setWalletId('');
    setDateRange(resetDateRange);

    table.setColumnFilters([{ id: 'CreatedAt', value: resetDateRange }]);
    table.setPageIndex(0);
    reload();
  };

  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]">
              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-[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>

          <div className="flex gap-3 items-center">
          <DefaultTooltip title={'Reset Filter'} placement={'top'}>
              <Button
                variant="outline"
                className="h-7.5 disabled:bg-gray-400"
                onClick={handleClearAllFilters}
              >
                <KeenIcon icon="arrow-circle-left" />
              </Button>
            </DefaultTooltip>
            <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;
