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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

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

  const [trxDate, settrxDate] = useState({ from: '', to: '' });
  const [searchValue, setSearchValue] = useState<string>(
    (table.getColumn('code')?.getFilterValue() as string) ?? ''
  );

  // const [statusValue, setStatusValue] = useState<string>(
  //   (table.getColumn('status')?.getFilterValue() as string) ?? ''
  // );

  const [typeValue, setTypeValue] = useState<string>(
    (table.getState().columnFilters.find(f => f.id === 'kind')?.value as string) ?? ''
  );

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

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

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

  // useEffect(() => {
  //   const timer = setTimeout(() => {
  //     table.getColumn('status')?.setFilterValue(statusValue);
  //     table.setPageIndex(0);
  //   }, 200);
  //   return () => clearTimeout(timer);
  // }, [statusValue, table]);

  useEffect(() => {
    const timer = setTimeout(() => {
      table.setColumnFilters((prev) => [
        ...prev.filter((f) => f.id !== 'kind'),
        { id: 'kind', value: typeValue },
      ]);
      table.setPageIndex(0);
    }, 200);
    return () => clearTimeout(timer);
  }, [typeValue, table]);

  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(() => {
    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>

          {/* <Select
            value={statusValue}
            onValueChange={(value) => {
              setStatusValue(value);
            }}
          >
            <SelectTrigger className="input input-sm w-[160px] h-[31px]">
              <SelectValue placeholder="Select Status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="C">COMPLETE</SelectItem>
              <SelectItem value="F">FAILED</SelectItem>
              <SelectItem value="O">ON PROCESS</SelectItem>
            </SelectContent>
          </Select> */}

          <Select
            value={typeValue}
            onValueChange={(value) => {
              setTypeValue(value);
            }}
          >
            <SelectTrigger className="input input-sm w-[160px] h-[31px]">
              <SelectValue placeholder="Select Type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="T">TRANSFER</SelectItem>
              <SelectItem value="P">PURCHASE</SelectItem>
              <SelectItem value="W">WITHDRAW</SelectItem>
              <SelectItem value="U">TOP UP</SelectItem>
              <SelectItem value="R">RETURN</SelectItem>
              <SelectItem value='N'>TOP UP PARTNER</SelectItem>
            </SelectContent>
          </Select>

          <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={() => {
                // Preserve trxDate values (from, to) and reset others
                const today = new Date();
                const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

                // Only reset filters excluding from and to
                setSearchValue('');
                // setStatusValue('');
                setTypeValue('');
                settrxDate({
                  from: formatDate(firstDayOfMonth),
                  to: formatDate(today),
                });

                // Reset other filters except for date range
                table.setColumnFilters([
                  { id: 'code', value: '' },
                  // { id: 'status', value: '' },
                  { id: 'kind', value: '' },
                ]);

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

export default ListToolbar;
