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 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 [groupId, setGroupId] = useState<string>(
    (table.getColumn('id_group')?.getFilterValue() as string) ?? ''
  );
  const [wallets, setWallets] = useState<WalletProps[]>([]);
  const [groups, setGroups] = useState<GroupProps[]>([]);

  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(() => {
    table.getColumn('id_group')?.setFilterValue(groupId);
    table.setPageIndex(0);
  }, [groupId, 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);
    }
  };

  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 handleClearAllFilters = () => {
    const today = new Date();
    const oneMonthAgo = getOneMonthsAgo();
    const resetDateRange = {
      from: formatDate(oneMonthAgo),
      to: formatDate(today)
    };
  
    setSearchValue('');
    setWalletId('');
    setGroupId('');
    setDateRange(resetDateRange);
  
    table.getColumn('msisdn')?.setFilterValue('');
    table.getColumn('id_wallet')?.setFilterValue('');
    table.getColumn('id_group')?.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('');
    setGroupId('');
    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-[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>
          </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;