import { useState, useEffect, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  EmployeeQueryParams,
  employeeService,
} from "../services/api/employeesService";
import { useLocalizedName } from "@/shared/common/localizedName";
import {
  EmployeeWithUnitDto,
  EmployeeWithUnitListResponse,
} from "../dto/employees/employees";

// Use the existing EmployeeWithUnitDto interface
export type OrganizationEmployee = EmployeeWithUnitDto;

export const useOrganizationEmployeeSearch = (
  organizationId?: string,
  params?: EmployeeQueryParams,
) => {
  const [searchQuery, setSearchQuery] = useState("");
  const [dynamicParams, setDynamicParams] = useState<
    EmployeeQueryParams | undefined
  >({
    ...params,
    take: params?.take || 3000, // Initial take value of 3000
  });
  const [hasSetCount, setHasSetCount] = useState(false);
  const localizedName = useLocalizedName();

  const {
    data: employeesData,
    isLoading,
    error,
    refetch,
  } = useQuery<EmployeeWithUnitListResponse>({
    queryKey: ["organizationEmployees", organizationId, dynamicParams],
    queryFn: async () => {
      if (!organizationId) throw new Error("Organization ID is required");
      const response = await employeeService.getEmployeesWithOrganizationById(
        organizationId,
        dynamicParams,
      );
      return response.data;
    },
    enabled: !!organizationId,
  });

  // Update params with count from response using useEffect
  useEffect(() => {
    if (employeesData?.count && !hasSetCount) {
      setDynamicParams((prev) => ({
        ...prev,
        take: employeesData.count,
      }));
      setHasSetCount(true);
    }
  }, [employeesData?.count, hasSetCount]);

  // Deduplicate employees by ID and filter based on search query
  const filteredEmployees = useMemo(() => {
    if (!employeesData?.items) {
      return [];
    }

    // First, deduplicate employees by their ID
    const uniqueEmployees = employeesData.items.reduce((acc, employee) => {
      if (!acc.find((e) => e.id === employee.id)) {
        acc.push(employee);
      }
      return acc;
    }, [] as EmployeeWithUnitDto[]);

    // Then filter based on search query
    if (!searchQuery.trim()) {
      return uniqueEmployees;
    }

    const query = searchQuery.toLowerCase().trim();

    return uniqueEmployees.filter((employee) => {
      // Search by user name (both am and en)
      const userNameAm = employee.user.name.am?.toLowerCase() || "";
      const userNameEn = employee.user.name.en?.toLowerCase() || "";
      const localizedUserName =
        localizedName(employee.user.name)?.toLowerCase() || "";

      // Search by employee name (both am and en)
      const empNameAm = employee.name.am?.toLowerCase() || "";
      const empNameEn = employee.name.en?.toLowerCase() || "";
      const localizedEmpName =
        localizedName(employee.name)?.toLowerCase() || "";

      // Search by email
      const email = employee.user.email?.toLowerCase() || "";

      // Search by phone number
      const phoneNumber = employee.user.phoneNumber?.toLowerCase() || "";

      // Search by position name
      const positionNames = (employee.employeePositions ?? [])
        .filter((ep) => ep?.position?.name)
        .map((ep) => localizedName(ep.position.name)?.toLowerCase() || "")
        .join(" ");

      return (
        userNameAm.includes(query) ||
        userNameEn.includes(query) ||
        localizedUserName.includes(query) ||
        empNameAm.includes(query) ||
        empNameEn.includes(query) ||
        localizedEmpName.includes(query) ||
        email.includes(query) ||
        phoneNumber.includes(query) ||
        positionNames.includes(query)
      );
    });
  }, [employeesData?.items, searchQuery, localizedName]);

  // Get unique employees for total count
  const uniqueEmployees = useMemo(() => {
    if (!employeesData?.items) return [];
    return employeesData.items.reduce((acc, employee) => {
      if (!acc.find((e) => e.id === employee.id)) {
        acc.push(employee);
      }
      return acc;
    }, [] as EmployeeWithUnitDto[]);
  }, [employeesData?.items]);

  return {
    employees: uniqueEmployees,
    filteredEmployees,
    totalCount: uniqueEmployees.length,
    filteredCount: filteredEmployees.length,
    searchQuery,
    setSearchQuery,
    isLoading,
    error,
    refetch,
  };
};
