import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import { FaPlus, FaSpinner, FaSave, FaTimes, FaUserPlus } 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 AddEmployeeModal = ({ isOpen, onClose, onSuccess }) => {
  const { isLight } = useTheme();
  const [loading, setLoading] = useState(false);
  const [divisions, setDivisions] = useState([]);
  const [roles, setRoles] = useState([]);
  const [divisionsLoading, setDivisionsLoading] = useState(true);
  const [rolesLoading, setRolesLoading] = useState(true);

  // Form state
  const [formData, setFormData] = useState({
    employee_id: "",
    employee_name: "",
    division_id: "",
    role_id: "",
    remarks: "",
    user_id: getCurrentUserId(), // Get current user ID
  });

  // Form validation and feedback
  const [errors, setErrors] = useState({});
  const [success, setSuccess] = useState(false);
  const [submitMessage, setSubmitMessage] = useState("");

  // Load persisted form data when modal opens
  useEffect(() => {
    if (isOpen) {
      const persistedData = getPersistedFormData("addEmployee");
      if (persistedData) {
        setFormData(persistedData);
      }
      fetchDivisions();
      fetchRoles();
    }
  }, [isOpen]);

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

  const fetchDivisions = async () => {
    try {
      const response = await fetch(buildApiUrl(API_ENDPOINTS.DIVISIONS));
      if (response.ok) {
        const data = await response.json();
        setDivisions(data);
      }
    } catch (error) {
      console.error("Error fetching divisions:", error);
    } finally {
      setDivisionsLoading(false);
    }
  };

  const fetchRoles = async () => {
    try {
      const response = await fetch(buildApiUrl(API_ENDPOINTS.ROLES));
      if (response.ok) {
        const data = await response.json();
        setRoles(data);
      }
    } catch (error) {
      console.error("Error fetching roles:", error);
    } finally {
      setRolesLoading(false);
    }
  };

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

    // Clear specific error when user starts typing
    if (errors[name]) {
      setErrors((prev) => ({
        ...prev,
        [name]: "",
      }));
    }
  };

  // Form validation
  const validateForm = () => {
    const newErrors = {};

    if (!formData.employee_id.trim()) {
      newErrors.employee_id = "Employee ID is required";
    }

    if (!formData.employee_name.trim()) {
      newErrors.employee_name = "Employee name is required";
    }

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

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

    if (!validateForm()) {
      return;
    }

    setLoading(true);
    setSubmitMessage("");

    try {
      // Update user_id with current user before sending
      const submitData = {
        ...formData,
        user_id: getCurrentUserId(),
      };

      const response = await fetch(buildApiUrl(API_ENDPOINTS.EMPLOYEES), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(submitData),
      });

      if (response.ok) {
        setSuccess(true);
        setSubmitMessage(
          shouldAddMore
            ? "Employee added! Ready to add another."
            : "Employee added successfully!"
        );

        // Clear persisted data when form is submitted
        clearPersistedFormData("addEmployee");

        // Reset form
        setFormData({
          employee_id: "",
          employee_name: "",
          division_id: "",
          role_id: "",
          remarks: "",
          user_id: getCurrentUserId(),
        });

        // Clear success message and handle completion
        setTimeout(
          () => {
            setSuccess(false);
            setSubmitMessage("");

            if (!shouldAddMore) {
              // Close modal and notify parent of success
              onClose();
              if (onSuccess) {
                onSuccess();
              }
            }
          },
          shouldAddMore ? 3000 : 2000
        );
      } else {
        const errorData = await response.json();
        setSubmitMessage(errorData.error || "Failed to add employee");
      }
    } catch (error) {
      console.error("Error adding employee:", error);
      setSubmitMessage("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  // Reset form when modal closes
  const handleClose = () => {
    setFormData({
      employee_id: "",
      employee_name: "",
      division_id: "",
      role_id: "",
      remarks: "",
      user_id: getCurrentUserId(),
    });
    setErrors({});
    setSuccess(false);
    setSubmitMessage("");
    onClose();
  };

  // Theme-based styling to match website colors
  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";

  // Don't render if not open
  if (!isOpen) return null;

  return (
    <>
      {/* Hide scrollbar CSS */}
      <style>
        {`
          .hide-scrollbar::-webkit-scrollbar {
            display: 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={handleClose}
          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()}
          style={{
            scrollbarWidth: "none" /* Firefox */,
            msOverflowStyle: "none" /* Internet Explorer 10+ */,
          }}
        >
          {/* 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"
                  }`}
                >
                  <FaUserPlus
                    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"
                    }`}
                  >
                    Add New Employee
                  </h2>
                  <p
                    className={`text-sm ${
                      isLight ? "text-amber-700" : "text-slate-300"
                    } opacity-75`}
                  >
                    Create a new team member profile
                  </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>

          {/* Success/Error Message */}
          {(success || submitMessage) && (
            <div
              className={`mx-6 mt-4 rounded-lg p-3 ${
                success
                  ? isLight
                    ? "bg-green-50 border border-green-200 text-green-800"
                    : "bg-green-900/20 border border-green-700 text-green-300"
                  : isLight
                  ? "bg-red-50 border border-red-200 text-red-800"
                  : "bg-red-900/20 border border-red-700 text-red-300"
              }`}
            >
              <div className="flex items-center gap-2">
                {success ? (
                  <FaSave className="text-sm flex-shrink-0" />
                ) : (
                  <FaTimes className="text-sm flex-shrink-0" />
                )}
                <span className="text-sm">{submitMessage}</span>
              </div>
            </div>
          )}

          {/* Form */}
          <form
            onSubmit={(e) => handleSubmit(e, false)}
            className="p-6 space-y-5"
          >
            {/* Employee ID */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Employee ID <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                name="employee_id"
                value={formData.employee_id}
                onChange={handleInputChange}
                className={`w-full px-3 py-2 rounded-md border text-sm ${inputClass} ${
                  errors.employee_id ? "border-red-500" : ""
                } ${loading ? "opacity-60" : ""}`}
                placeholder="Enter employee ID"
                disabled={loading}
              />
              {errors.employee_id && (
                <p className="text-red-500 text-sm mt-1">
                  {errors.employee_id}
                </p>
              )}
            </div>

            {/* Employee Name */}
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Employee Name <span className="text-red-500">*</span>
              </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" : ""
                } ${loading ? "opacity-60" : ""}`}
                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 <span className="text-red-500">*</span>
              </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" : ""
                } ${loading || divisionsLoading ? "opacity-60" : ""}`}
                disabled={loading || divisionsLoading}
              >
                <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 <span className="text-red-500">*</span>
              </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" : ""
                } ${loading || rolesLoading ? "opacity-60" : ""}`}
                disabled={loading || rolesLoading}
              >
                <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>

            {/* 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 ${
                  loading ? "opacity-60" : ""
                }`}
                placeholder="Any additional notes about the employee..."
                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={(e) => handleSubmit(e, true)}
                disabled={loading || divisionsLoading || rolesLoading}
                className={`flex-1 px-4 py-2.5 rounded-md font-medium text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 ${
                  isLight
                    ? "bg-gray-600 hover:bg-gray-700 text-white"
                    : "bg-gray-600 hover:bg-gray-500 text-white"
                }`}
              >
                {loading ? (
                  <>
                    <FaSpinner className="animate-spin text-sm" />
                    <span>Adding...</span>
                  </>
                ) : (
                  <>
                    <FaPlus className="text-sm" />
                    <span>Add More</span>
                  </>
                )}
              </button>

              <button
                type="submit"
                disabled={loading || divisionsLoading || rolesLoading}
                className={`flex-1 px-4 py-2.5 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 Employee</span>
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  );
};

export default AddEmployeeModal;
