import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import { FaTimes, FaSave, FaSpinner } from "react-icons/fa";
import {
  getPersistedFormData,
  saveFormData,
  clearPersistedFormData,
  shouldPersistFormData,
} from "../../utils/formPersistence";
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 : 1; // Default to 1 if no user found
  } catch (error) {
    console.error("Error getting current user:", error);
    return 1; // Default fallback
  }
};

const EditEmployeeModal = ({
  isOpen,
  onClose,
  employee,
  divisions,
  roles,
  onSave,
  loading,
}) => {
  const { isLight } = useTheme();
  const [formData, setFormData] = useState({
    employee_id: "",
    employee_name: "",
    division_id: "",
    role_id: "",
    remarks: "",
  });
  const [errors, setErrors] = useState({});

  // Project-related state
  const [projects, setProjects] = useState([]);
  const [selectedProjects, setSelectedProjects] = useState([]);
  const [projectsLoading, setProjectsLoading] = useState(true);
  const [currentEmployeeProjects, setCurrentEmployeeProjects] = useState([]);

  // Load persisted form data when modal opens
  useEffect(() => {
    if (isOpen && employee) {
      const persistedData = getPersistedFormData(
        "editEmployee",
        employee.employee_id
      );
      if (persistedData) {
        setFormData(persistedData);
        setSelectedProjects(persistedData.selectedProjects || []);
      }
    }
  }, [isOpen, employee]);

  // Save form data whenever it changes
  useEffect(() => {
    if (isOpen && employee && shouldPersistFormData(formData)) {
      const dataToSave = {
        ...formData,
        selectedProjects: selectedProjects,
      };
      saveFormData("editEmployee", dataToSave, employee.employee_id);
    }
  }, [formData, selectedProjects, isOpen, employee]);

  // Populate form when employee changes - handle basic info first
  useEffect(() => {
    if (employee) {
      const persistedData = getPersistedFormData(
        "editEmployee",
        employee.employee_id
      );
      if (persistedData) {
        setFormData(persistedData);
        setSelectedProjects(persistedData.selectedProjects || []);
      } else {
        setFormData((prev) => ({
          ...prev,
          employee_id: employee.employee_id || "",
          employee_name: employee.employee_name || "",
          remarks: employee.remarks || "",
        }));
      }
      setErrors({});
    }
  }, [employee]);

  // Populate division and role when dropdown data is available
  useEffect(() => {
    if (employee && divisions.length > 0 && roles.length > 0) {
      // Find division ID by matching division name
      const selectedDivision = divisions.find(
        (div) => div.division_name === employee.division_name
      );

      // Find role ID by matching role name
      const selectedRole = roles.find(
        (role) => role.role_name === employee.role_name
      );

      setFormData((prev) => ({
        ...prev,
        division_id: selectedDivision
          ? selectedDivision.division_id.toString()
          : "",
        role_id: selectedRole ? selectedRole.role_id.toString() : "",
      }));
    }
  }, [employee, divisions, roles]);

  // Fetch projects when modal opens
  useEffect(() => {
    if (isOpen) {
      fetchProjects();
    }
  }, [isOpen]);

  // Fetch projects from API
  const fetchProjects = async () => {
    try {
      setProjectsLoading(true);
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.PROJECTS_WITH_IDS)
      );
      if (response.ok) {
        const data = await response.json();
        setProjects(data);
      }
    } catch (error) {
      console.error("Error fetching projects:", error);
    } finally {
      setProjectsLoading(false);
    }
  };

  // Set current employee projects when employee data is available
  useEffect(() => {
    if (
      employee &&
      employee.project_names &&
      employee.project_names !== "no_projects"
    ) {
      const projectNames = employee.project_names.split(", ");
      const currentProjects = projects.filter((project) =>
        projectNames.includes(project.project_name)
      );
      setCurrentEmployeeProjects(currentProjects);
      setSelectedProjects(currentProjects.map((p) => p.project_id));
    } else {
      setCurrentEmployeeProjects([]);
      setSelectedProjects([]);
    }
  }, [employee, projects]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
    // Clear error when user starts typing
    if (errors[name]) {
      setErrors((prev) => ({
        ...prev,
        [name]: "",
      }));
    }
  };

  // Handle project selection
  const handleProjectChange = (e) => {
    const selectedOptions = Array.from(e.target.selectedOptions, (option) =>
      parseInt(option.value)
    );
    setSelectedProjects(selectedOptions);
  };

  const validateForm = () => {
    const newErrors = {};

    // Employee ID validation (still validated but not shown to user)
    if (!formData.employee_id.toString().trim()) {
      newErrors.employee_id = "Employee ID is required";
    } else if (!/^\d+$/.test(formData.employee_id.toString())) {
      newErrors.employee_id = "Employee ID must be a number";
    }

    if (!formData.employee_name.trim()) {
      newErrors.employee_name = "Employee name is required";
    } else if (formData.employee_name.trim().length < 2) {
      newErrors.employee_name = "Employee name must be at least 2 characters";
    }

    if (!formData.division_id) {
      newErrors.division_id = "Division is required";
    }

    if (!formData.role_id) {
      newErrors.role_id = "Role is required";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateForm()) {
      return;
    }

    // Add user_id to the form data for logging
    const submitData = {
      ...formData,
      user_id: getCurrentUserId(),
      selectedProjects: selectedProjects,
    };

    // Clear persisted data when form is submitted
    if (employee) {
      clearPersistedFormData("editEmployee", employee.employee_id);
    }
    onSave(submitData);
  };

  // Reset form when modal closes
  useEffect(() => {
    if (!isOpen) {
      setFormData({
        employee_id: "",
        employee_name: "",
        division_id: "",
        role_id: "",
        remarks: "",
      });
      setErrors({});
      setSelectedProjects([]);
      setCurrentEmployeeProjects([]);
      clearPersistedFormData("editEmployee", employee?.employee_id);
    }
  }, [isOpen, employee]);

  if (!isOpen) return null;

  const modalBgClass = isLight ? "bg-white" : "bg-slate-800";

  const inputClass = isLight
    ? "bg-white text-gray-900 border-yellow-200 focus:ring-amber-500 focus:border-amber-500"
    : "bg-slate-700 text-slate-100 border-slate-600 focus:ring-cyan-400 focus:border-cyan-400 hover:border-slate-500";

  const buttonClass = isLight
    ? "bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white"
    : "bg-blue-600 hover:bg-blue-700 text-white shadow-lg";

  const textClass = isLight ? "text-amber-700" : "text-slate-300";

  return (
    <>
      {/* Hide scrollbar CSS */}
      <style>
        {`
          .hide-scrollbar::-webkit-scrollbar {
            display: none;
          }
          .hide-scrollbar {
            -ms-overflow-style: none;
            scrollbar-width: none;
          }
        `}
      </style>

      <div
        className="fixed inset-0 flex items-center justify-center z-50 p-4"
        style={{ backgroundColor: "rgba(0, 0, 0, 0.1)" }}
      >
        <div
          className="absolute inset-0"
          onClick={onClose}
          style={{ cursor: "pointer" }}
          title="Click to close"
        />
        <div
          className={`${modalBgClass} rounded-lg max-w-md w-full max-h-[90vh] overflow-y-auto hide-scrollbar relative z-60 border ${
            isLight ? "border-yellow-200" : "border-slate-600 shadow-2xl"
          }`}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header */}
          <div
            className={`p-6 border-b ${
              isLight ? "border-yellow-200" : "border-slate-600"
            }`}
          >
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div
                  className={`p-2 rounded-full ${
                    isLight ? "bg-yellow-100" : "bg-blue-900"
                  }`}
                >
                  <FaSave
                    className={`text-lg ${
                      isLight ? "text-amber-600" : "text-cyan-400"
                    }`}
                  />
                </div>
                <div>
                  <h2
                    className={`text-xl font-semibold ${
                      isLight ? "text-amber-800" : "text-slate-100"
                    }`}
                  >
                    Edit Employee
                  </h2>
                  <p
                    className={`text-sm ${
                      isLight ? "text-amber-700" : "text-slate-300"
                    } opacity-75`}
                  >
                    Update employee information
                  </p>
                </div>
              </div>
              <button
                onClick={onClose}
                disabled={loading}
                className={`p-2 rounded-md transition-colors flex items-center justify-center w-8 h-8 ${
                  isLight
                    ? "text-gray-400 hover:text-gray-600 hover:bg-gray-100"
                    : "text-gray-400 hover:text-gray-200 hover:bg-gray-700"
                } disabled:opacity-50`}
              >
                <FaTimes className="flex-shrink-0" />
              </button>
            </div>
          </div>

          {/* Form */}
          <form onSubmit={handleSubmit} className="p-6 space-y-4">
            {/* Employee ID - Hidden field */}
            <input
              type="hidden"
              name="employee_id"
              value={formData.employee_id}
            />

            {/* Employee Name */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Employee Name *
              </label>
              <input
                type="text"
                name="employee_name"
                value={formData.employee_name}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.employee_name ? "border-red-500" : ""
                }`}
                placeholder="Enter full name"
                disabled={loading}
              />
              {errors.employee_name && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.employee_name}
                </p>
              )}
            </div>

            {/* Division */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Division *
              </label>
              <select
                name="division_id"
                value={formData.division_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.division_id ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                <option value="">Select Division</option>
                {divisions.map((division) => (
                  <option
                    key={division.division_id}
                    value={division.division_id}
                  >
                    {division.division_name}
                  </option>
                ))}
              </select>
              {errors.division_id && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.division_id}
                </p>
              )}
            </div>

            {/* Role */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Role *
              </label>
              <select
                name="role_id"
                value={formData.role_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.role_id ? "border-red-500" : ""
                }`}
                disabled={loading}
              >
                <option value="">Select Role</option>
                {roles.map((role) => (
                  <option key={role.role_id} value={role.role_id}>
                    {role.role_name}
                  </option>
                ))}
              </select>
              {errors.role_id && (
                <p className="text-red-500 text-sm mt-1">{errors.role_id}</p>
              )}
            </div>

            {/* Projects */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Projects
              </label>

              {/* Check if employee is a director */}
              {(() => {
                // Find division and role names from the IDs
                const selectedDivision = divisions.find(
                  (div) => div.division_id.toString() === formData.division_id
                );
                const selectedRole = roles.find(
                  (role) => role.role_id.toString() === formData.role_id
                );

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

                if (isDirector) {
                  return (
                    <div
                      className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} min-h-[100px] flex items-center justify-center`}
                    >
                      <div className="text-center">
                        <div className={`text-lg mb-2 ${textClass}`}>👑</div>
                        <span className={`text-sm ${textClass} font-medium`}>
                          Directors cannot be assigned to projects
                        </span>
                        <p className={`text-xs ${textClass} opacity-75 mt-1`}>
                          This is a system restriction for director-level
                          employees
                        </p>
                      </div>
                    </div>
                  );
                }

                return (
                  <>
                    {projectsLoading ? (
                      <div
                        className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} min-h-[100px] flex items-center justify-center`}
                      >
                        <span className={`text-sm ${textClass}`}>
                          Loading projects...
                        </span>
                      </div>
                    ) : projects.length > 0 ? (
                      <div
                        className={`w-full max-h-[200px] overflow-y-auto border rounded-md p-3 ${inputClass}`}
                      >
                        <div className="space-y-2">
                          {projects.map((project) => (
                            <label
                              key={project.project_id}
                              className="flex items-center space-x-3 cursor-pointer hover:bg-opacity-10 hover:bg-gray-500 p-2 rounded"
                            >
                              <input
                                type="checkbox"
                                checked={selectedProjects.includes(
                                  project.project_id
                                )}
                                onChange={(e) => {
                                  if (e.target.checked) {
                                    setSelectedProjects((prev) => [
                                      ...prev,
                                      project.project_id,
                                    ]);
                                  } else {
                                    setSelectedProjects((prev) =>
                                      prev.filter(
                                        (id) => id !== project.project_id
                                      )
                                    );
                                  }
                                }}
                                className={`w-4 h-4 rounded border-2 ${
                                  isLight
                                    ? "text-amber-600 border-amber-500 focus:ring-amber-500"
                                    : "text-cyan-400 border-cyan-500 focus:ring-cyan-400"
                                }`}
                                disabled={loading}
                              />
                              <span className={`text-sm ${textClass}`}>
                                {project.project_name}
                              </span>
                            </label>
                          ))}
                        </div>
                      </div>
                    ) : (
                      <div
                        className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} min-h-[100px] flex items-center justify-center`}
                      >
                        <span className={`text-sm ${textClass}`}>
                          No projects available
                        </span>
                      </div>
                    )}
                    {projects.length > 0 && (
                      <p className={`text-xs mt-1 ${textClass} opacity-75`}>
                        {selectedProjects.length} project
                        {selectedProjects.length !== 1 ? "s" : ""} selected
                      </p>
                    )}
                  </>
                );
              })()}
            </div>

            {/* Remarks */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Remarks
              </label>
              <textarea
                name="remarks"
                value={formData.remarks}
                onChange={handleInputChange}
                rows={3}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} resize-none`}
                placeholder="Enter any additional notes..."
                disabled={loading}
              />
            </div>

            {/* Buttons */}
            <div
              className={`flex gap-3 pt-4 mt-4 border-t ${
                isLight ? "border-yellow-200" : "border-slate-600"
              }`}
            >
              <button
                type="button"
                onClick={onClose}
                disabled={loading}
                className={`flex-1 px-4 py-2 rounded-md font-medium text-sm transition-colors border ${
                  isLight
                    ? "border-yellow-300 text-amber-700 hover:bg-yellow-50 bg-white"
                    : "border-slate-600 text-slate-300 hover:bg-slate-700 bg-slate-800 hover:border-slate-500"
                } disabled:opacity-50 disabled:cursor-not-allowed`}
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={loading}
                className={`flex-1 px-4 py-2 rounded-md font-medium text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 ${buttonClass}`}
              >
                {loading ? (
                  <>
                    <FaSpinner className="animate-spin text-sm" />
                    <span>Saving...</span>
                  </>
                ) : (
                  <>
                    <FaSave className="text-sm" />
                    <span>Save Changes</span>
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  );
};

export default EditEmployeeModal;
