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';
import { toAbsoluteUrl } from '@/utils';

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

  const [trxDate, settrxDate] = useState({ from: '', to: '' });

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

  useEffect(() => {
    const today = new Date();
    const nextWeek = new Date(today);
    nextWeek.setDate(today.getDate() + 7);

    settrxDate({
      from: formatDate(today),
      to: formatDate(nextWeek)
    });
  }, []);

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

  const handleExportData = () => {
    const link = document.createElement('a');
    link.href = toAbsoluteUrl('/media/file-templates/upload-batch-template.xlsx');
    link.download = 'upload-batch-template.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  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={'Download Template'} placement={'top'}>
              <Button onClick={handleExportData} className="h-7.5" variant={'outline'}>
                <img
                  src={toAbsoluteUrl('/media/file-types/xls.svg')}
                  className="dark:hidden h-5"
                  alt="Export to Excel"
                />
              </Button>
            </DefaultTooltip>
            <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;
