import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { useTransactionContext } from '../hooks/useApprovalTransactionContext';
import { Button } from '@/components/ui/button';
import { useCallback, useState, useEffect } from 'react';
import { toast } from 'sonner';

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

  // Set the initial state for trxDate
  const [trxDate, settrxDate] = useState({ from: '', to: '' });

  // Function to format date to YYYY-MM-DD
  const formatDate = (date: Date): string => {
    return date.toISOString().split('T')[0];
  };

  const [searchValue, setSearchValue] = useState<string>(
    (table.getColumn('code')?.getFilterValue() as string) ?? ''
  );

  // useEffect to set the default date values
  useEffect(() => {
    const today = new Date();
    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    settrxDate({
      from: formatDate(firstDayOfMonth),
      to: formatDate(today),
    });
  }, []);

  const handleFilterData = useCallback(() => {
    try {
      table.getColumn('transaction_date')?.setFilterValue(trxDate);
    } catch (error) {
      toast.error('Error applying filter');
      console.error('Error applying filter:', error);
    }
  }, [trxDate, table]);

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

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

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

  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 justify-between items-center">
        <div className="flex gap-3 items-center w-full md:w-auto">
          <label className="input input-sm w-[160px]">
            From
            <input
              type="date"
              placeholder="From"
              value={trxDate.from}
              onChange={(event) =>
                settrxDate({ ...trxDate, from: event.target.value })
              }
              name="from"
            />
          </label>

          <label className="input input-sm w-[160px]">
            To
            <input
              type="date"
              placeholder="To"
              value={trxDate.to}
              onChange={(event) =>
                settrxDate({ ...trxDate, to: event.target.value })
              }
              name="to"
            />
          </label>

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

        </div>

        <div className="ml-auto">
          <DefaultTooltip title={'Refresh'} placement={'top'}>
            <Button
              variant="outline"
              className="h-7.5"
              onClick={() => {
                const today = new Date();
                const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

                setSearchValue('');
                settrxDate({
                  from: formatDate(firstDayOfMonth),
                  to: formatDate(today),
                });

                table.getColumn('code')?.setFilterValue('');
                table.setPageIndex(0);

                reload();
              }}
            >
              <KeenIcon icon="arrows-circle" />
            </Button>
          </DefaultTooltip>
        </div>
      </div>
    </div>
  );

};

export default ListToolbar;
