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

const EditProjectLeadModal = ({
  isOpen,
  onClose,
  projectLead,
  onSuccess,
  loading = false,
}) => {
  const { isLight } = useTheme();
  const [formData, setFormData] = useState({
    project_id: "",
    project_lead_emp_id: "",
  });
  const [errors, setErrors] = useState({});
  const [submitMessage, setSubmitMessage] = useState("");
  const [success, setSuccess] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Options for dropdowns
  const [employees, setEmployees] = useState([]);
  const [projects, setProjects] = useState([]);

  // Load persisted form data when modal opens
  useEffect(() => {
    if (isOpen && projectLead) {
      const persistedData = getPersistedFormData(
        "editProjectLead",
        projectLead.id
      );
      if (persistedData) {
        setFormData(persistedData);
      } else {
        setFormData({
          project_id:
            projectLead.id?.toString() ||
            projectLead.project_id?.toString() ||
            "",
          project_lead_emp_id:
            projectLead.leadId?.toString() ||
            projectLead.project_lead_emp_id?.toString() ||
            "",
        });
      }
      setErrors({});
      setSubmitMessage("");
      setSuccess(false);
    }
  }, [isOpen, projectLead]);

  // Save form data whenever it changes
  useEffect(() => {
    if (isOpen && projectLead && shouldPersistFormData(formData)) {
      saveFormData("editProjectLead", formData, projectLead.project_lead_name);
    }
  }, [formData, isOpen, projectLead]);

  // Fetch required data for dropdowns
  useEffect(() => {
    if (isOpen) {
      fetchFormData();
    }
  }, [isOpen]);

  const fetchFormData = async () => {
    try {
      // Fetch employees
      const employeesResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.EMPLOYEES)
      );
      if (!employeesResponse.ok) {
        throw new Error("Failed to fetch employees");
      }
      const employeesData = await employeesResponse.json();

      // Filter out directors (role_name = Director)
      const nonDirectorEmployees = employeesData.filter(
        (emp) => emp.role_name !== "Director"
      );
      setEmployees(nonDirectorEmployees);

      // Fetch projects
      const projectsResponse = await fetch(buildApiUrl(API_ENDPOINTS.PROJECTS));
      if (!projectsResponse.ok) {
        throw new Error("Failed to fetch projects");
      }
      const projectsData = await projectsResponse.json();
      setProjects(projectsData);
    } catch (error) {
      console.error("Error fetching form data:", error);
      setSubmitMessage("Error loading form data. Please try again.");
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));

    // Clear error for this field
    if (errors[name]) {
      setErrors((prev) => ({
        ...prev,
        [name]: "",
      }));
    }
  };

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

    if (!formData.project_lead_emp_id) {
      newErrors.project_lead_emp_id = "Project Lead is required";
    }

    if (!formData.project_id) {
      newErrors.project_id = "Project is required";
    }

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

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);
    setSuccess(false);
    setSubmitMessage("");

    try {
      const projectLeadEmpId = parseInt(formData.project_lead_emp_id);
      const projectId = parseInt(formData.project_id);
      const userId = getCurrentUserId();

      console.log("Updating project lead:", {
        project_id: projectId,
        project_lead_emp_id: projectLeadEmpId,
        user_id: userId
      });

      // Update the project with the new project lead
      const projectResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.PROJECT_BY_ID(projectId)),
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            project_lead_emp_id: projectLeadEmpId,
            user_id: userId,
          }),
        }
      );

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

      const responseData = await projectResponse.json();
      console.log("Project update response:", responseData);

      // Try to create employee-project assignment (it will fail if it already exists, which is fine)
      try {
        const employeeProjectResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.EMPLOYEE_PROJECTS),
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              employee_id: projectLeadEmpId,
              project_id: projectId,
              user_id: userId,
            }),
          }
        );

        // If the assignment already exists, that's fine - we don't need to do anything
        if (
          !employeeProjectResponse.ok &&
          employeeProjectResponse.status !== 409
        ) {
          const errorData = await employeeProjectResponse.json();
          console.warn(
            "Warning: Could not create employee-project assignment:",
            errorData.error
          );
        }
      } catch (assignmentError) {
        // If the assignment already exists, that's fine - we don't need to do anything
        console.warn(
          "Warning: Could not create employee-project assignment:",
          assignmentError.message
        );
      }

      setSuccess(true);
      setSubmitMessage("Project lead updated successfully!");

      // Clear persisted data when form is submitted
      if (projectLead) {
        clearPersistedFormData("editProjectLead", projectLead.id);
      }

      // Call success handler first, then close modal
      if (onSuccess) {
        onSuccess();
      }

      // Close modal after success
      setTimeout(() => {
        setSuccess(false);
        setSubmitMessage("");
        onClose();
      }, 2000);
    } catch (error) {
      console.error("Error updating project lead:", error);
      setSubmitMessage(error.message || "Network error. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    setFormData({
      project_id: "",
      project_lead_emp_id: "",
    });
    setErrors({});
    setSuccess(false);
    setSubmitMessage("");
    onClose();
  };

  if (!isOpen) return null;

  const modalBgClass = isLight
    ? "bg-white border border-yellow-200 shadow-2xl"
    : "bg-gradient-to-br from-gray-800 to-slate-800 border border-gray-700 shadow-2xl";

  const labelClass = isLight
    ? "text-amber-800 font-semibold"
    : "text-gray-200 font-semibold";
  const inputClass = isLight
    ? "bg-white text-gray-900 border-gray-300 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-gradient-to-r from-gray-600 to-slate-600 hover:from-gray-500 hover:to-slate-500 text-white";

  return (
    <div
      className="fixed inset-0 flex items-center justify-center z-50 p-4"
      style={{ backgroundColor: "rgba(0, 0, 0, 0.5)" }}
    >
      <div
        className="absolute inset-0"
        onClick={handleClose}
        style={{ cursor: "pointer" }}
        title="Click to close"
      />
      <div
        className={`${modalBgClass} rounded-lg max-w-md w-full max-h-[90vh] overflow-y-auto 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"
                }`}
              >
                <FaUserTie
                  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 Project Lead
                </h2>
                <p
                  className={`text-sm ${
                    isLight ? "text-amber-700" : "text-slate-300"
                  } opacity-75`}
                >
                  Update project lead assignment
                </p>
              </div>
            </div>
            <button
              onClick={handleClose}
              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"
              }`}
            >
              <FaTimes className="flex-shrink-0" />
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Project Selection */}
            <div>
              <label className={`block text-sm font-medium mb-2 ${labelClass}`}>
                Project
              </label>
              <select
                name="project_id"
                value={formData.project_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-offset-0 transition-colors ${inputClass} ${
                  errors.project_id ? "border-red-500" : ""
                }`}
                disabled
              >
                {projects.map((project) => (
                  <option key={project.project_id} value={project.project_id}>
                    {project.project_name} (ID: {project.project_id})
                  </option>
                ))}
              </select>
              {errors.project_id && (
                <p className="text-red-500 text-sm mt-1">{errors.project_id}</p>
              )}
            </div>

            {/* Project Lead Selection */}
            <div>
              <label className={`block text-sm font-medium mb-2 ${labelClass}`}>
                New Project Lead
              </label>
              <select
                name="project_lead_emp_id"
                value={formData.project_lead_emp_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-offset-0 transition-colors ${inputClass} ${
                  errors.project_lead_emp_id ? "border-red-500" : ""
                }`}
              >
                <option value="">
                  {projectLead?.leadName || projectLead?.project_lead_name || "Select a project lead"}
                </option>
                {employees.map((employee) => (
                  <option
                    key={employee.employee_id}
                    value={employee.employee_id}
                  >
                    {employee.employee_name} - {employee.role_name}
                  </option>
                ))}
              </select>
              {errors.project_lead_emp_id && (
                <p className="text-sm mt-1 text-red-500">
                  {errors.project_lead_emp_id}
                </p>
              )}
            </div>

            {/* Submit Message */}
            {submitMessage && (
              <div
                className={`p-3 rounded-lg text-sm ${
                  success
                    ? isLight
                      ? "bg-green-100 text-green-800 border border-green-200"
                      : "bg-green-900 text-green-200 border border-green-700"
                    : isLight
                    ? "bg-red-100 text-red-800 border border-red-200"
                    : "bg-red-900 text-red-200 border border-red-700"
                }`}
              >
                {submitMessage}
              </div>
            )}

            {/* Action Buttons */}
            <div className="flex items-center justify-end gap-3 pt-4">
              <button
                type="button"
                onClick={handleClose}
                className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                  isLight
                    ? "bg-gray-200 hover:bg-gray-300 text-gray-800"
                    : "bg-gray-600 hover:bg-gray-500 text-white"
                }`}
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={isSubmitting || loading}
                className={`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${
                  isSubmitting || loading ? "opacity-50 cursor-not-allowed" : ""
                } ${buttonClass}`}
              >
                {isSubmitting || loading ? (
                  <>
                    <FaSpinner className="animate-spin" />
                    Updating...
                  </>
                ) : (
                  <>
                    <FaSave />
                    Update Project Lead
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default EditProjectLeadModal;
