import { Button } from '@/components/ui/button';
import { UserPlus } from 'lucide-react';
import { KeenIcon, useDataGrid } from '@/components';
import { DefaultTooltip } from '@/components';
import { useState,useEffect } from 'react';
import { toast } from 'sonner';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { getAuth } from '@/auth';
import { apiConfig } from '@/config/api.config';
import { useAuthContext } from '@/auth';
const API_URL = apiConfig.service_customer;

interface ListToolbarProps {
  createMember: () => void;
  onReload: () => void;
  isReloading: boolean;
  groups: any;
}

const ListToolbar = ({ createMember, onReload, isReloading, groups }: ListToolbarProps) => {
  const [groupFilter, setGroupFilter] = useState('');
  const { table, reload } = useDataGrid();
  const [searchValue, setSearchValue] = useState<string>();
  const [typeSearchValue, setSearchTypeValue] = useState<string>();
  const [isAdmin, setisAdmin] = useState(false);
  const { getUser } = useAuthContext();
  
  useEffect(() => {
    getUserData();
  }, []);

  async function getUserData() {
    let userlogin:any = await getUser();
    let userloginrole = userlogin?.data?.role?.name;
    if (userloginrole === 'Admin') setisAdmin(true);
  }


  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.preventDefault()
    // setSearchValue(e.target.value)
    if (typeSearchValue === 'username') {
      table.getColumn('username')?.setFilterValue(searchValue);
      table.getColumn('msisdn')?.setFilterValue('');
    }
    if (typeSearchValue === 'msisdn') {
      table.getColumn('msisdn')?.setFilterValue(searchValue);
      table.getColumn('username')?.setFilterValue('');
    }
    table.getColumn('group_name')?.setFilterValue(groupFilter);
  };

  const handleGroupChange = (e: any) => {
    let value = e.target.value;
    if (value === '__all__') value = '';
    setGroupFilter(value);
    // if (typeSearchValue === 'username') table.getColumn('username')?.setFilterValue(searchValue);
    // if (typeSearchValue === 'msisdn') table.getColumn('msisdn')?.setFilterValue(searchValue);
    // table.getColumn('group_name')?.setFilterValue(value);
  };

  const generateExportFilters = (groupFilter: string, typeSearchValue: any, searchValue: any): { id: string; value: string }[] => {
    const filters: { id: string; value: string }[] = [];
    if (groupFilter) filters.push({ id: 'group_name', value: groupFilter });
    if (typeSearchValue && searchValue) filters.push({ id: typeSearchValue, value: searchValue });
    return filters;
  };

  const exporDataToExcel = async (filters: { id: string; value: string }[]) => {
    try {
      const filterParam = encodeURIComponent(JSON.stringify(filters));
      const response = await fetch(`${API_URL}/customer/export-excel?filter=${filterParam}`, {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${getAuth()?.access_token}`,
        }
      });
      if (!response.ok) throw new Error('Failed to fetch file');

      const blob = await response.blob();
      const contentDisposition = response.headers.get('content-disposition');
      const currentYear = new Date().getFullYear();
      const filename = `TPAY_members_${currentYear}.xlsx`;
      return { blob, filename };
    } catch (error:any) {
      console.error('Error exporting data:', error);
      toast.error(error)
    }
  };

  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">

          <form onSubmit={(e:any) => handleSearch(e)}>
            <div className="flex gap-3 items-center">
              <Select value={groupFilter} onValueChange={(e) => (handleGroupChange({ target : { value: e }}))}>
                <SelectTrigger className="input input-sm w-[250px] h-[31px]">
                  <SelectValue placeholder="Select Group" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={"__all__"}>All Group</SelectItem>
                  {groups.map((el: any, idx: any) => (
                    <SelectItem key={idx} value={el.name}>
                      {el.name}
                    </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="username">Username</SelectItem>
                  <SelectItem value="msisdn">Phone Number</SelectItem>
                </SelectContent>
              </Select>

              <label className="input input-sm w-1/3">
                {/* <KeenIcon icon="magnifier" /> */}
                <input
                  type="text"
                  placeholder={`Search ${typeSearchValue || ''}`}  // Use typeSearchValue if it's set, else fallback to an empty string
                  value={searchValue}
                  onChange={(e:any) => setSearchValue(e.target.value)}
                />
              </label>
              <Button variant="outline" className="h-7.5">
                <KeenIcon icon="magnifier" />
              </Button>
            </div>
          </form>

          <div className="flex gap-3 items-center">
            { (!isAdmin) ? (
              <>
                <Button
                  variant="outline"
                  className="h-7.5"
                  onClick={async () => {
                    const filters = generateExportFilters(groupFilter, typeSearchValue, searchValue);
                    const result = await exporDataToExcel(filters);
      
                    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>
                <Button variant="outline" className="h-7.5 text-[0.8rem]" onClick={createMember}>Add Data</Button>
              </>
            ) : ('') }

            <DefaultTooltip title={isReloading ? 'Refreshing...' : 'Refresh'} placement={'top'}>
              <Button 
                variant="outline" 
                className="h-7.5" 
                onClick={onReload}
                disabled={isReloading}
              >
                {isReloading ? (
                  <div className="animate-spin">
                    <KeenIcon icon="arrows-circle" />
                  </div>
                ) : (
                  <KeenIcon icon="arrows-circle" />
                )}
              </Button>
            </DefaultTooltip>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ListToolbar;