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';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';

const ListToolbar = () => {
  const { table, reload } = useDataGrid();
  const [trxDate, settrxDate] = useState({ from: '', to: '' });
  const [searchValue, setSearchValue] = useState<string>(''); // default: empty string
  const [typeSearchValue, setSearchTypeValue] = useState<string>(''); // default: empty string
  const [typeValue, setTypeValue] = useState<string>(
    (table.getState().columnFilters.find(f => f.id === 'kind')?.value as string) ?? ''
  );

  const { GetData } = useCallApi();
  const API_URL = apiConfig.transaction;

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

  useEffect(() => {
    const today = new Date();
    settrxDate({
      from: formatDate(today),
      to: formatDate(today),
    });
  }, []);

  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 timer = setTimeout(() => {
      table.setColumnFilters((prev) => [
        ...prev.filter((f) => f.id !== 'searchtype'),
        { id: 'searchtype', value: typeSearchValue },
      ]);
      table.setPageIndex(0);
    }, 200);
    return () => clearTimeout(timer);
  }, [typeSearchValue, table]);

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

  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]);

  const exporDataToExcel = async (
    typeSearchValue: string,
    searchValue: string,
    trxDate: any,
    typeValue: string
  ) => {
    try {
      const formattedFilter: any = {
        "Transactions.transaction_date": {
          from: `${trxDate.from} 00:00:00`,
          to: `${trxDate.to} 23:59:59`
        }
      };

      if (typeSearchValue === 'msisdn') {
        formattedFilter['Transactions.origin_msisdn'] = searchValue;
      } else if (typeSearchValue === 'fullname') {
        formattedFilter['Transactions.origin_name'] = searchValue;
      } else if (typeSearchValue === 'trxid') {
        formattedFilter['Transactions.code'] = searchValue;
      }

      if (typeValue) {
        formattedFilter["Transactions.kind"] = typeValue;
      }

      const filterParam = encodeURIComponent(JSON.stringify(formattedFilter));

      const response = await fetch(`${API_URL}/transaction/export?filter=${filterParam}`, {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${getAuth()?.access_token}`, // ganti dengan token kamu
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch file');
      }

      const blob = await response.blob();
      const contentDisposition = response.headers.get('content-disposition');
      const filenameMatch = contentDisposition?.match(/filename="?(.+)"?/);
      const filename = filenameMatch ? filenameMatch[1] : 'transaction_history.xlsx';

      return { blob, filename };
    } catch (error) {
      console.error('Error exporting data:', error);
      return null;
    }
  };


  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"
              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"
              value={trxDate.to}
              onChange={(event) =>
                settrxDate({ ...trxDate, to: event.target.value })
              }
              name="to"
            />
          </label>

          <Select
            value={typeValue}
            onValueChange={(value) => setTypeValue(value)}
          >
            <SelectTrigger className="input input-sm w-[250px] h-[31px]">
              <SelectValue placeholder="Select Transaction 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>
              <SelectItem value="E">REWARD</SelectItem>
              <SelectItem value="L">PURCHASE LOJA</SelectItem>
              <SelectItem value="B">TOP UP P24</SelectItem>
              <SelectItem value="A">TRANSFER AGENT</SelectItem>
              <SelectItem value="M">WITHDRAWAL AGENT</SelectItem>
            </SelectContent>
          </Select>

          <Select
            value={typeSearchValue}
            onValueChange={(value) => setSearchTypeValue(value)}
          >
            <SelectTrigger className="input input-sm w-[250px] h-[31px]">
              <SelectValue placeholder="Select Search Type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="msisdn">MSISDN</SelectItem>
              <SelectItem value="fullname">FULLNAME</SelectItem>
              <SelectItem value="trxid">TRANSACTION ID</SelectItem>
            </SelectContent>
          </Select>

          <label className="input input-sm w-1/3">
            <KeenIcon icon="magnifier" />
            <input
              type="text"
              placeholder={`Search ${typeSearchValue || ''}`}
              value={searchValue}
              onChange={(event) => setSearchValue(event.target.value)}
            />
          </label>
        </div>

        <div className="ml-auto flex gap-2">
          <Button
            variant="outline"
            className="h-7.5"
            onClick={async () => {
              const result = await exporDataToExcel(
                typeSearchValue || '',
                searchValue || '',
                trxDate || {},
                typeValue || ''
              );

              if (result) {
                const url = window.URL.createObjectURL(result.blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = result.filename;
                a.click();
                window.URL.revokeObjectURL(url);
              } else {
                toast.error('Failed to export data');
              }
            }}
          >
            Export Data
          </Button>



          <DefaultTooltip title={'Refresh'} placement={'top'}>
            <Button
              variant="outline"
              className="h-7.5"
              onClick={() => {
                const today = new Date();

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

                table.setColumnFilters([
                  { id: 'code', value: '' },
                  { id: 'kind', value: '' },
                ]);

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

export default ListToolbar;
