"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { ColumnDef, DataTableLayout } from "ikoncomponents";
import { useSearchParams } from "next/navigation";

import { getEmployees } from "@/app/utils/api/employeeDetails";

interface EmployeeResponseDto {
  accountId: string;
  empId: string;
  name: string;
  email: string;
  organizationEmail: string;
  role: string;
  grade: string;
  active: boolean;
}

interface RoleDto {
  id: string;
  accountId: string;
  role: string;
}

interface GradeDto {
  id: string;
  grade: string;
}

interface ResolvedEmployee extends EmployeeResponseDto {
  roleName: string;
  gradeName: string;
}

function EmployeePage({
  roleData,
  gradeData,
}: {
  roleData: RoleDto[];
  gradeData: GradeDto[];
}) {
  const [employees, setEmployees] = useState<ResolvedEmployee[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // This table is list-only, so hide DataTableLayout's built-in List/Grid toggle
  // (it has no prop to disable it). Once mounted we find the grid button and hide
  // the whole toggle group, so a lone list button isn't left dangling.
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const hidGridToggle = useRef(false);

  const searchParams = useSearchParams();
  const currentSearch = (searchParams.get("search") || "").toLowerCase().trim();

  const fetchEmployees = useCallback(async () => {
    setIsLoading(true);

    try {
      const data = await getEmployees();
      console.log("emp data", data);

      const empList: EmployeeResponseDto[] = data || [];

      const roleMap = new Map(
        roleData?.map((role) => [role.id, role.role]) || [],
      );

      const gradeMap = new Map(
        gradeData?.map((grade) => [grade.id, grade.grade]) || [],
      );
      console.log("emp", empList, roleMap, gradeMap);

      const resolved: ResolvedEmployee[] = empList.map((emp) => ({
        ...emp,
        roleName: roleMap.get(emp.role) || "n/a",
        gradeName: gradeMap.get(emp.grade) || "n/a",
      }));
      console.log("emp data", resolved);
      setEmployees(resolved);
    } catch (error) {
      console.error("Failed to fetch employees:", error);
    } finally {
      setIsLoading(false);
    }
  }, [roleData, gradeData]);

  useEffect(() => {
    if (roleData && gradeData) {
      fetchEmployees();
    }
  }, [fetchEmployees, roleData, gradeData]);

  // Hide the List/Grid toggle once the table has mounted.
  useEffect(() => {
    if (isLoading || hidGridToggle.current) return;
    const gridButton =
      tableContainerRef.current?.querySelector<HTMLButtonElement>(
        'button[title="Grid View"]',
      );
    if (gridButton?.parentElement) {
      gridButton.parentElement.style.display = "none";
      hidGridToggle.current = true;
    }
  }, [isLoading]);

  const filteredEmployees = currentSearch
    ? employees.filter(
        (emp) =>
          (emp.name || "").toLowerCase().includes(currentSearch) ||
          (emp.empId || "").toLowerCase().includes(currentSearch) ||
          (emp.email || "").toLowerCase().includes(currentSearch) ||
          (emp.roleName || "").toLowerCase().includes(currentSearch) ||
          (emp.gradeName || "").toLowerCase().includes(currentSearch),
      )
    : employees;

  const columns: ColumnDef<ResolvedEmployee>[] = [
    {
      accessorKey: "empId",
      header: "Employee ID",
      cell: (row) => <span>{row.empId || "n/a"}</span>,
    },
    {
      accessorKey: "name",
      header: "Employee Name",
      cell: (row) => <span>{row.name || "n/a"}</span>,
    },
    {
      accessorKey: "roleName",
      header: "Role",
      cell: (row) => <span>{row.roleName || "n/a"}</span>,
    },
    {
      accessorKey: "gradeName",
      header: "Grade",
      cell: (row) => <span>{row.gradeName || "n/a"}</span>,
    },
    {
      accessorKey: "email",
      header: "Email",
      cell: (row) => <span>{row.email || "n/a"}</span>,
    },
    {
      accessorKey: "organizationEmail",
      header: "Organization Email",
      cell: (row) => <span>{row.organizationEmail || "n/a"}</span>,
    },
    {
      accessorKey: "active",
      header: "Status",
      cell: (row) => <span>{row.active ? "Active" : "Inactive"}</span>,
    },
  ];

  return (
    <div ref={tableContainerRef}>
      <DataTableLayout
        data={filteredEmployees}
        columns={columns}
        extraTools={{
          keyExtractor: (row: ResolvedEmployee) => row.empId,
          totalPages: 1,
          currentPage: 1,
          isLoading,
          onReload: fetchEmployees,
        }}
      />
    </div>
  );
}

export default EmployeePage;
