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

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

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

  // useEffect to set the default date values
  useEffect(() => {
    const today = new Date();
    const nextWeek = new Date(today);
    nextWeek.setDate(today.getDate() + 7);

    settrxDate({
      from: formatDate(today),   // Set 'from' to today
      to: formatDate(nextWeek),  // Set 'to' to 7 days later
    });
  }, []);

  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(() => {
    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">
        <div className="flex justify-between w-full items-center">
          <div className="flex gap-3 items-center ml-auto">
            <Button
              variant="outline"
              className="h-7.5 text-[0.8rem]"
              onClick={() => handleUploadBatchDialog(true)}
            >
              Upload Batch
            </Button>
            <DefaultTooltip title={'Refresh'} placement={'top'}>
              <Button variant="outline" className="h-7.5" onClick={() => reload()}>
                <KeenIcon icon="arrows-circle" />
              </Button>
            </DefaultTooltip>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ListToolbar;
