import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import { FaTimes, FaUserTie, FaSpinner, FaSave } from "react-icons/fa";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

const AssignLeadModal = ({ isOpen, onClose, onSuccess }) => {
  const { isLight } = useTheme();
  const [loading, setLoading] = useState(false);
  const [submitMessage, setSubmitMessage] = useState("");
  const [success, setSuccess] = useState(false);

  // Form data
  const [formData, setFormData] = useState({
    project_lead_emp_id: "",
    project_id: "",
  });

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

  // Form validation errors
  const [errors, setErrors] = useState({});

  // 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
    }
  };

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

  const fetchFormData = async () => {
    try {
      setLoading(true);

      // Fetch employees
      const employeesResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.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));
      const projectsData = await projectsResponse.json();
      setProjects(projectsData);
    } catch (error) {
      console.error("Error fetching form data:", error);
      setSubmitMessage("Error loading form data. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  // Handle input changes
  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]: "",
      }));
    }
  };

  // Validate form
  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;
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

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

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

      // Step 1: 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: projectLeadId,
            project_id: projectId,
            user_id: userId,
          }),
        }
      );

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

      // Step 2: Create employee-project assignment in employees_projects table
      const employeeProjectResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.EMPLOYEE_PROJECTS),
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            employee_id: projectLeadId,
            project_id: projectId,
            user_id: userId,
          }),
        }
      );

      if (!employeeProjectResponse.ok) {
        const errorData = await employeeProjectResponse.json();
        throw new Error(
          errorData.error || "Failed to create employee-project assignment"
        );
      }

      setSuccess(true);
      setSubmitMessage(
        "Project lead assigned successfully and employee project assignment created!"
      );

      // Reset form
      setFormData({
        project_lead_emp_id: "",
        project_id: "",
      });

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

  // Reset form when modal closes
  const handleClose = () => {
    setFormData({
      project_lead_emp_id: "",
      project_id: "",
    });
    setErrors({});
    setSuccess(false);
    setSubmitMessage("");
    onClose();
  };

  // Theme-based styling
  const modalBgClass = isLight ? "bg-white" : "bg-slate-800";

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

  const inputClass = isLight
    ? "bg-white border-gray-300 text-gray-900 focus:border-amber-500 focus:ring-amber-500"
    : "bg-slate-700 border-slate-600 text-gray-100 focus:border-blue-500 focus:ring-blue-500";

  const headingClass = isLight ? "text-amber-800" : "text-gray-100";

  if (!isOpen) return null;

  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-4xl w-full max-h-[90vh] overflow-y-auto relative z-60 border ${
          isLight ? "border-gray-200" : "border-slate-600 shadow-2xl"
        }`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div
          className={`p-6 border-b ${
            isLight ? "border-gray-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-amber-100" : "bg-amber-900"
                }`}
              >
                <FaUserTie className={`text-lg ${headingClass}`} />
              </div>
              <div>
                <h2 className={`text-xl font-semibold ${headingClass}`}>
                  Assign Project Lead
                </h2>
                <p className={`text-sm ${textClass} opacity-75`}>
                  Assign a lead to an existing project
                </p>
              </div>
            </div>
            <button
              onClick={handleClose}
              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>

        {/* Content */}
        <div className="p-6">
          {/* Success/Error Message */}
          {submitMessage && (
            <div
              className={`mb-6 rounded-lg p-4 ${
                success
                  ? "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>{submitMessage}</span>
                <button
                  onClick={() => setSubmitMessage("")}
                  className="ml-auto text-lg font-semibold hover:opacity-70"
                >
                  ×
                </button>
              </div>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Row 1: Project Lead, Project */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Project Lead */}
              <div>
                <label
                  className={`block text-sm font-medium ${textClass} mb-2`}
                >
                  Project Lead *
                </label>
                <select
                  name="project_lead_emp_id"
                  value={formData.project_lead_emp_id}
                  onChange={handleInputChange}
                  className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                    errors.project_lead_emp_id ? "border-red-500" : ""
                  }`}
                  disabled={loading}
                >
                  <option value="">Select Project Lead</option>
                  {employees.map((employee) => (
                    <option
                      key={employee.employee_id}
                      value={employee.employee_id}
                    >
                      {employee.employee_name}
                    </option>
                  ))}
                </select>
                {errors.project_lead_emp_id && (
                  <p className="text-red-500 text-sm mt-1">
                    {errors.project_lead_emp_id}
                  </p>
                )}
              </div>

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

            {/* Buttons */}
            <div
              className={`flex gap-3 pt-4 mt-6 border-t ${
                isLight ? "border-gray-200" : "border-slate-600"
              }`}
            >
              <button
                type="button"
                onClick={handleClose}
                disabled={loading}
                className={`flex-1 px-4 py-2 rounded-md font-medium text-sm transition-colors border ${
                  isLight
                    ? "border-gray-300 text-gray-700 hover:bg-gray-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 bg-amber-600 hover:bg-amber-700 text-white shadow-lg"
              >
                {loading ? (
                  <>
                    <FaSpinner className="animate-spin text-sm" />
                    <span>Assigning...</span>
                  </>
                ) : (
                  <>
                    <FaSave className="text-sm" />
                    <span>Assign Project Lead</span>
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default AssignLeadModal;
