import React, { useState, useEffect, useMemo } from "react";
import * as XLSX from "xlsx";
import { formatIST } from "../utils/timeUtils";

import EmployeesHeader from "../components/Employees/EmployeesHeader";
import LoadingState from "../components/Employees/LoadingState";
import ErrorState from "../components/Employees/ErrorState";
import EmployeeStats from "../components/Employees/EmployeeStats";
import EmployeeFilters from "../components/Employees/EmployeeFilters";
import FilterStatusBar from "../components/Employees/FilterStatusBar";
import EmployeesTable from "../components/Employees/EmployeesTable";
import MobileEmployeesView from "../components/Employees/MobileEmployeesView";
import EditEmployeeModal from "../components/Employees/EditEmployeeModal";
import DeleteConfirmModal from "../components/Employees/DeleteConfirmModal";
import AddEmployeeModal from "../components/Employees/AddEmployeeModal";
import { buildApiUrl, API_ENDPOINTS } from "../utils/config";

// Helper function to get current user ID
const getCurrentUserId = () => {
  try {
    const user = JSON.parse(localStorage.getItem("user"));
    return user ? user.user_id : 201; // Default to 201 if no user found
  } catch (error) {
    console.error("Error getting current user:", error);
    return 201; // Default fallback
  }
};

const EmployeesPage = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  // Filter states
  const [divisions, setDivisions] = useState([]);
  const [roles, setRoles] = useState([]);
  const [projects, setProjects] = useState([]);
  const [selectedDivision, setSelectedDivision] = useState("All");
  const [selectedRole, setSelectedRole] = useState("All");
  const [selectedProject, setSelectedProject] = useState("All");
  const [filtersLoading, setFiltersLoading] = useState(true);

  // Edit/Delete modal states
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [selectedEmployee, setSelectedEmployee] = useState(null);
  const [operationLoading, setOperationLoading] = useState(false);
  const [operationMessage, setOperationMessage] = useState("");

  // Add Employee modal state
  const [addEmployeeModalOpen, setAddEmployeeModalOpen] = useState(false);
  
  // Error popup state
  const [errorPopupOpen, setErrorPopupOpen] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  // Fetch employees from employees_details API
  useEffect(() => {
    const fetchEmployees = async () => {
      try {
        setLoading(true);
        const response = await fetch(
          buildApiUrl(API_ENDPOINTS.EMPLOYEES_DETAILS)
        );
        if (!response.ok) {
          throw new Error("Failed to fetch employees");
        }
        const data = await response.json();
        setEmployees(data);
        setError(null);
      } catch (err) {
        setError(err.message);
        console.error("Error fetching employees:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchEmployees();
  }, []);

  // Handle division filter from chart click
  useEffect(() => {
    const fromChart = localStorage.getItem('fromChart');
    const selectedDivision = localStorage.getItem('selectedDivision');
    
    console.log('EmployeesPage: Checking localStorage:', { fromChart, selectedDivision });
    
    if (fromChart === 'true' && selectedDivision) {
      console.log('EmployeesPage: Setting division filter to:', selectedDivision);
      setSelectedDivision(selectedDivision);

      localStorage.removeItem('fromChart');
      localStorage.removeItem('selectedDivision');
    }
  }, []);

  // Fetch filter data (divisions, roles, projects)
  useEffect(() => {
    const fetchFilterData = async () => {
      try {
        setFiltersLoading(true);

        // Fetch divisions
        const divisionsResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.DIVISIONS)
        );
        const divisionsData = divisionsResponse.ok
          ? await divisionsResponse.json()
          : [];

        // Fetch roles
        const rolesResponse = await fetch(buildApiUrl(API_ENDPOINTS.ROLES));
        const rolesData = rolesResponse.ok ? await rolesResponse.json() : [];

        // Fetch projects
        const projectsResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.PROJECTS)
        );
        const projectsData = projectsResponse.ok
          ? await projectsResponse.json()
          : [];

        setDivisions(divisionsData);
        setRoles(rolesData);
        setProjects(projectsData);
      } catch (err) {
        console.error("Error fetching filter data:", err);
      } finally {
        setFiltersLoading(false);
      }
    };

    fetchFilterData();
  }, []);

  const filteredEmployees = useMemo(() => {
    return employees.filter((employee) => {
      const matchesSearch =
        (employee.employee_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (employee.division_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (employee.role_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (employee.project_names || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (employee.employee_id || "").toString().includes(searchTerm);

      const matchesDivision =
        selectedDivision === "All" ||
        (employee.division_name || "").toLowerCase() ===
          selectedDivision.toLowerCase();
      const matchesRole =
        selectedRole === "All" ||
        (employee.role_name || "").toLowerCase() === selectedRole.toLowerCase();
      const matchesProject =
        selectedProject === "All" ||
        (selectedProject === "No Projects" && 
         (!employee.project_names || employee.project_names === "no_projects")) ||
        (selectedProject !== "No Projects" &&
         employee.project_names &&
         employee.project_names !== "no_projects" &&
         employee.project_names
           .toLowerCase()
           .includes(selectedProject.toLowerCase()));

      return matchesSearch && matchesDivision && matchesRole && matchesProject;
    });
  }, [employees, searchTerm, selectedDivision, selectedRole, selectedProject]);

  // Helper function to format project names for display
  const formatProjectNames = (projectNames) => {
    if (!projectNames || projectNames === "no_projects") {
      return "No Projects";
    }
    return projectNames;
  };

  // Pagination calculations
  const totalPages = Math.ceil(filteredEmployees.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentEmployees = filteredEmployees.slice(startIndex, endIndex);

  // Reset to first page when search or filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm, selectedDivision, selectedRole, selectedProject]);

  // Excel export function
  const exportToExcel = () => {
    const exportData = filteredEmployees.map((employee) => ({
      "Employee ID": employee.employee_id,
      "Employee Name": employee.employee_name,
      Division: employee.division_name || "Not Assigned",
      Role: employee.role_name || "Not Assigned",
      "Project Name": formatProjectNames(employee.project_names),
      Remarks: employee.remarks || "No remarks",
    }));

    // Add filter information if any filters are active
    const activeFilters = [];
    if (selectedDivision !== "All")
      activeFilters.push(`Division: ${selectedDivision}`);
    if (selectedRole !== "All") activeFilters.push(`Role: ${selectedRole}`);
    if (selectedProject !== "All")
      activeFilters.push(`Project: ${selectedProject}`);
    if (searchTerm) activeFilters.push(`Search: "${searchTerm}"`);

    let filename = "employees_data.xlsx";
    if (activeFilters.length > 0) {
      filename = `employees_filtered_${formatIST(new Date(), "date").replace(
        /\//g,
        "-"
      )}.xlsx`;
    }

    const ws = XLSX.utils.json_to_sheet(exportData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Employees");
    XLSX.writeFile(wb, filename);
  };

  const goToPage = (page) => {
    setCurrentPage(page);
  };

  const goToPrevious = () => {
    setCurrentPage((prev) => Math.max(prev - 1, 1));
  };

  const goToNext = () => {
    setCurrentPage((prev) => Math.min(prev + 1, totalPages));
  };

  // Calculate statistics from real data
  const totalEmployees = employees.length;

  // Handle Add Employee button click
  const handleAddEmployee = () => {
    setAddEmployeeModalOpen(true);
  };

  // Refresh employees list
  const refreshEmployees = async () => {
    try {
      setLoading(true);
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.EMPLOYEES_DETAILS)
      );
      if (!response.ok) {
        throw new Error("Failed to fetch employees");
      }
      const data = await response.json();
      setEmployees(data);
      setError(null);
    } catch (err) {
      setError(err.message);
      console.error("Error fetching employees:", err);
    } finally {
      setLoading(false);
    }
  };

  // Handle edit employee
  const handleEditEmployee = (employee) => {
    setSelectedEmployee(employee);
    setEditModalOpen(true);
  };

  // Handle delete employee
  const handleDeleteEmployee = (employee) => {
    setSelectedEmployee(employee);
    setDeleteModalOpen(true);
  };

  // Handle add employee success
  const handleAddEmployeeSuccess = async () => {
    await refreshEmployees();
  };



  // Confirm delete employee
  const confirmDeleteEmployee = async () => {
    if (!selectedEmployee) return;

    setOperationLoading(true);
    setOperationMessage("");

    try {
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.EMPLOYEE_BY_ID(selectedEmployee.employee_id)),
        {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            user_id: getCurrentUserId(),
          }),
        }
      );

             if (response.ok) {
         setOperationMessage("Employee deleted successfully!");
         setDeleteModalOpen(false);
         setSelectedEmployee(null);
         await refreshEmployees();
       } else {
         const errorData = await response.json();
         let userFriendlyMessage;

         // Check if the backend returned a specific error message
         if (errorData.error) {
           userFriendlyMessage = errorData.error;
         } else {
           // Fallback error handling
           userFriendlyMessage = "Something went wrong. Please try again.";
         }

                   // Show error in custom popup
          setErrorMessage(userFriendlyMessage);
          setErrorPopupOpen(true);
          // Close the delete confirmation modal even when there's an error
          setDeleteModalOpen(false);
          setSelectedEmployee(null);
       }
         } catch (error) {
       console.error("Error deleting employee:", error);
               // Show network error in custom popup
        setErrorMessage("Network error. Please try again.");
        setErrorPopupOpen(true);
        // Close the delete confirmation modal even when there's a network error
        setDeleteModalOpen(false);
        setSelectedEmployee(null);
     } finally {
      setOperationLoading(false);
    }
  };

  // Handle edit employee save
  const handleSaveEmployee = async (updatedEmployeeData) => {
    if (!selectedEmployee) return;

    setOperationLoading(true);
    setOperationMessage("");

    try {
      // First, update the employee basic information
      const employeeResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.EMPLOYEE_BY_ID(selectedEmployee.employee_id)),
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...updatedEmployeeData,
            employee_id: parseInt(updatedEmployeeData.employee_id),
            division_id: parseInt(updatedEmployeeData.division_id),
            role_id: parseInt(updatedEmployeeData.role_id),
            user_id: getCurrentUserId(),
          }),
        }
      );

      if (!employeeResponse.ok) {
        const errorData = await employeeResponse.json();
        throw new Error(errorData.error || "Failed to update employee");
      }

      // Handle project assignments if selectedProjects is provided
      if (updatedEmployeeData.selectedProjects !== undefined) {
        // Check if employee is a director by division name and role name
        const selectedDivision = divisions.find(
          (div) => div.division_id === updatedEmployeeData.division_id
        );
        const selectedRole = roles.find(
          (role) => role.role_id === updatedEmployeeData.role_id
        );

        const isDirector =
          selectedDivision?.division_name === "Directors" ||
          selectedRole?.role_name === "Director";

        if (isDirector) {
          // Directors cannot be assigned to projects - remove all project assignments
          const currentProjectNames =
            selectedEmployee.project_names &&
            selectedEmployee.project_names !== "no_projects"
              ? selectedEmployee.project_names.split(", ")
              : [];

          const currentProjectIds = projects
            .filter((project) =>
              currentProjectNames.includes(project.project_name)
            )
            .map((project) => project.project_id);

          // Remove all existing project assignments for directors
          for (const projectId of currentProjectIds) {
            await fetch(
              buildApiUrl(
                API_ENDPOINTS.EMPLOYEE_PROJECT_BY_ID(
                  selectedEmployee.employee_id,
                  projectId
                )
              ),
              {
                method: "DELETE",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  user_id: getCurrentUserId(),
                }),
              }
            );
          }
        } else {
          // Non-directors can have project assignments
          const currentProjectNames =
            selectedEmployee.project_names &&
            selectedEmployee.project_names !== "no_projects"
              ? selectedEmployee.project_names.split(", ")
              : [];

          const currentProjectIds = projects
            .filter((project) =>
              currentProjectNames.includes(project.project_name)
            )
            .map((project) => project.project_id);

          const newProjectIds = updatedEmployeeData.selectedProjects;

          // Remove projects that are no longer selected
          const projectsToRemove = currentProjectIds.filter(
            (id) => !newProjectIds.includes(id)
          );
          for (const projectId of projectsToRemove) {
            await fetch(
              buildApiUrl(
                API_ENDPOINTS.EMPLOYEE_PROJECT_BY_ID(
                  selectedEmployee.employee_id,
                  projectId
                )
              ),
              {
                method: "DELETE",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  user_id: getCurrentUserId(),
                }),
              }
            );
          }

          // Add new projects that weren't previously assigned
          const projectsToAdd = newProjectIds.filter(
            (id) => !currentProjectIds.includes(id)
          );
          for (const projectId of projectsToAdd) {
            await fetch(buildApiUrl(API_ENDPOINTS.EMPLOYEE_PROJECTS), {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                employee_id: selectedEmployee.employee_id,
                project_id: projectId,
                user_id: getCurrentUserId(),
              }),
            });
          }
        }
      }

      setOperationMessage("Employee updated successfully!");
      setEditModalOpen(false);
      setSelectedEmployee(null);
      await refreshEmployees();
    } catch (error) {
      console.error("Error updating employee:", error);
      setOperationMessage(`Error updating employee: ${error.message}`);
    } finally {
      setOperationLoading(false);
    }
  };

  return (
    <div className="space-y-3 max-w-full overflow-hidden px-2 sm:px-4 lg:px-6">
      {/* Header */}
      <EmployeesHeader onAddEmployee={handleAddEmployee} />

      {/* Loading State */}
      {loading && <LoadingState />}

      {/* Error State */}
      {error && <ErrorState error={error} />}

      {/* Operation Message */}
      {operationMessage && (
        <div
          className={`rounded-lg p-4 ${
            operationMessage.includes("successfully")
              ? "bg-green-50 border border-green-200 text-green-800"
              : "bg-red-50 border border-red-200 text-red-800"
          }`}
        >
          <div className="flex items-center gap-2">
            <span>{operationMessage}</span>
            <button
              onClick={() => setOperationMessage("")}
              className="ml-auto text-lg font-semibold hover:opacity-70"
            >
              ×
            </button>
          </div>
        </div>
      )}

      {/* Employee Stats & Search */}
      {!loading && !error && (
        <EmployeeStats
          totalEmployees={totalEmployees}
          searchTerm={searchTerm}
          setSearchTerm={setSearchTerm}
          exportToExcel={exportToExcel}
        />
      )}

      {/* Employee Filters */}
      {!loading && !error && (
        <EmployeeFilters
          divisions={divisions}
          roles={roles}
          projects={projects}
          selectedDivision={selectedDivision}
          selectedRole={selectedRole}
          selectedProject={selectedProject}
          onDivisionChange={setSelectedDivision}
          onRoleChange={setSelectedRole}
          onProjectChange={setSelectedProject}
          filtersLoading={filtersLoading}
        />
      )}

      {/* Filter Status Bar */}
      {/* {!loading && !error && (
        <FilterStatusBar 
          filteredEmployees={filteredEmployees}
          totalEmployees={totalEmployees}
          selectedDivision={selectedDivision}
          selectedRole={selectedRole}
          selectedProject={selectedProject}
          setSelectedDivision={setSelectedDivision}
          setSelectedRole={setSelectedRole}
          setSelectedProject={setSelectedProject}
        />
      )} */}

      {/* Employees Table - Desktop View */}
      {!loading && !error && (
        <>
          {/* Desktop Table View */}
          <EmployeesTable
            filteredEmployees={filteredEmployees}
            currentEmployees={currentEmployees}
            currentPage={currentPage}
            totalPages={totalPages}
            startIndex={startIndex}
            endIndex={endIndex}
            goToPage={goToPage}
            goToPrevious={goToPrevious}
            goToNext={goToNext}
            searchTerm={searchTerm}
            setSearchTerm={setSearchTerm}
            onEditEmployee={handleEditEmployee}
            onDeleteEmployee={handleDeleteEmployee}
            projects={projects}
          />

          {/* Mobile Card View */}
          <MobileEmployeesView
            currentEmployees={currentEmployees}
            currentPage={currentPage}
            totalPages={totalPages}
            goToPrevious={goToPrevious}
            goToNext={goToNext}
            onEditEmployee={handleEditEmployee}
            onDeleteEmployee={handleDeleteEmployee}
            projects={projects}
          />
        </>
      )}

      {/* Edit Employee Modal */}
      <EditEmployeeModal
        isOpen={editModalOpen}
        onClose={() => {
          setEditModalOpen(false);
          setSelectedEmployee(null);
          setOperationMessage("");
        }}
        employee={selectedEmployee}
        divisions={divisions}
        roles={roles}
        onSave={handleSaveEmployee}
        loading={operationLoading}
      />

      {/* Delete Confirmation Modal */}
      <DeleteConfirmModal
        isOpen={deleteModalOpen}
        onClose={() => {
          setDeleteModalOpen(false);
          setSelectedEmployee(null);
          setOperationMessage("");
        }}
        employee={selectedEmployee}
        onConfirm={confirmDeleteEmployee}
        loading={operationLoading}
      />

      {/* Add Employee Modal */}
      <AddEmployeeModal
        isOpen={addEmployeeModalOpen}
        onClose={() => setAddEmployeeModalOpen(false)}
        onSuccess={handleAddEmployeeSuccess}
      />

      {/* Custom Error Popup Modal */}
      {errorPopupOpen && (
        <div className="fixed inset-0 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b border-gray-200">
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-full bg-red-100">
                  <svg className="w-5 h-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                  </svg>
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-gray-900">Error</h3>
                  <p className="text-sm text-gray-500">Something went wrong</p>
                </div>
              </div>
            </div>

            {/* Content */}
            <div className="p-4">
              <p className="text-gray-700">{errorMessage}</p>
            </div>

            {/* Footer */}
            <div className="flex justify-end gap-3 p-4 border-t border-gray-200">
              <button
                onClick={() => setErrorPopupOpen(false)}
                className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default EmployeesPage;
