import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import {
  FaUser,
  FaPlus,
  FaSpinner,
  FaCheck,
  FaTimes,
  FaBuilding,
  FaUserTag,
  FaStickyNote,
  FaIdCard,
  FaInfoCircle,
  FaExclamationTriangle,
  FaUserPlus,
} from "react-icons/fa";
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 AddEmployeePage = ({ onSectionChange }) => {
  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("");
  const [addMoreMode, setAddMoreMode] = useState(false);

  // Fetch divisions and roles on component mount
  useEffect(() => {
    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);
      }
    };

    fetchDivisions();
    fetchRoles();
  }, []);

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

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

    if (!formData.employee_id.trim()) {
      newErrors.employee_id = "Employee ID is required";
    } else if (!/^\d+$/.test(formData.employee_id)) {
      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;
  };

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

    if (!validateForm()) {
      return;
    }

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

    try {
      // Update user_id with current user before sending
      const submitData = {
        ...formData,
        employee_id: parseInt(formData.employee_id),
        division_id: parseInt(formData.division_id),
        role_id: parseInt(formData.role_id),
        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) {
        const result = await response.json();
        setSuccess(true);
        setSubmitMessage(
          shouldAddMore
            ? "Employee added! Ready to add another."
            : "Employee added successfully!"
        );

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

        // Clear success message after time based on mode
        setTimeout(
          () => {
            setSuccess(false);
            setSubmitMessage("");

            // Redirect to employees page after successful submission (not for "Add More" mode)
            if (!shouldAddMore && onSectionChange) {
              onSectionChange("employees");
            }
          },
          shouldAddMore ? 3000 : 2000
        ); // Shorter delay for redirect
      } 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);
    }
  };

  // Theme-based styling
  const cardBgClass = isLight
    ? "bg-white border border-yellow-200 shadow-md hover:shadow-lg"
    : "bg-slate-800 border border-slate-700 shadow-xl hover:shadow-2xl";

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

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

  const inputClass = isLight
    ? "bg-white text-gray-900 border-gray-300 focus:ring-yellow-500 focus:border-yellow-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";

  return (
    <div className="min-h-screen py-4 sm:py-6">
      <div className="max-w-full sm:max-w-2xl mx-auto px-3 sm:px-6 lg:px-8">
        {/* Simple Header */}
        <div className="text-center mb-4 sm:mb-6">
          <div
            className={`inline-flex items-center justify-center w-10 h-10 sm:w-12 sm:h-12 rounded-full mb-3 sm:mb-4 ${
              isLight ? "bg-yellow-100" : "bg-blue-900"
            }`}
          >
            <FaUserPlus
              className={`text-lg sm:text-xl ${
                isLight ? "text-yellow-600" : "text-cyan-400"
              }`}
            />
          </div>
          <h1
            className={`text-xl sm:text-2xl font-semibold ${headingClass} mb-2`}
          >
            Add New Employee
          </h1>
        </div>

        {/* Success/Error Message */}
        {(success || submitMessage) && (
          <div
            className={`mb-4 sm:mb-6 rounded-lg p-3 sm:p-4 ${
              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 ? (
                <FaCheck className="text-sm" />
              ) : (
                <FaTimes className="text-sm" />
              )}
              <span className="text-sm sm:text-base">{submitMessage}</span>
            </div>
          </div>
        )}

        {/* Simple Form */}
        <div className={`${cardBgClass} rounded-lg shadow-sm`}>
          <form
            onSubmit={(e) => handleSubmit(e, false)}
            className="p-4 sm:p-6 space-y-4 sm:space-y-6"
          >
            {/* 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 sm:py-2.5 rounded-md border text-sm sm:text-base ${inputClass} ${
                  errors.employee_id ? "border-red-500" : ""
                }`}
                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`}>
                Full 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 sm:py-2.5 rounded-md border text-sm sm:text-base ${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 and Role */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
              {/* 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 sm:py-2.5 rounded-md border text-sm sm:text-base ${inputClass} ${
                    errors.division_id ? "border-red-500" : ""
                  }`}
                  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>
                {divisionsLoading && (
                  <p className={`text-sm ${textClass} mt-1`}>
                    Loading divisions...
                  </p>
                )}
                {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 sm:py-2.5 rounded-md border text-sm sm:text-base ${inputClass} ${
                    errors.role_id ? "border-red-500" : ""
                  }`}
                  disabled={loading || rolesLoading}
                >
                  <option value="">Select Role</option>
                  {roles
                    .filter(
                      (role) =>
                        role.role_name !== "Director" &&
                        role.role_name !== "Junior-Director"
                    )
                    .map((role) => (
                      <option key={role.role_id} value={role.role_id}>
                        {role.role_name}
                      </option>
                    ))}
                </select>
                {rolesLoading && (
                  <p className={`text-sm ${textClass} mt-1`}>
                    Loading roles...
                  </p>
                )}
                {errors.role_id && (
                  <p className="text-red-500 text-sm mt-1">{errors.role_id}</p>
                )}
              </div>
            </div>

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

            {/* Buttons */}
            <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 pt-3 sm:pt-4">
              <button
                type="button"
                onClick={(e) => handleSubmit(e, true)}
                disabled={loading || divisionsLoading || rolesLoading}
                className={`w-full sm:w-auto px-3 sm:px-4 py-2.5 sm:py-2 rounded-md font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm sm:text-base ${
                  isLight
                    ? "bg-blue-600 hover:bg-blue-700 text-white"
                    : "bg-blue-600 hover:bg-blue-500 text-white"
                }`}
              >
                {loading && addMoreMode ? (
                  <>
                    <FaSpinner className="animate-spin text-sm" />
                    <span className="hidden sm:inline">Adding...</span>
                    <span className="sm:hidden">Adding</span>
                  </>
                ) : (
                  <>
                    <FaPlus className="text-sm" />
                    <span className="hidden sm:inline">Add More Employee</span>
                    <span className="sm:hidden">Add More</span>
                  </>
                )}
              </button>

              <button
                type="submit"
                disabled={loading || divisionsLoading || rolesLoading}
                className={`w-full sm:w-auto px-3 sm:px-4 py-2.5 sm:py-2 rounded-md font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm sm:text-base ${buttonClass}`}
              >
                {loading && !addMoreMode ? (
                  <>
                    <FaSpinner className="animate-spin text-sm" />
                    <span className="hidden sm:inline">Submitting...</span>
                    <span className="sm:hidden">Submit</span>
                  </>
                ) : (
                  <>
                    <FaCheck className="text-sm" />
                    <span className="hidden sm:inline">Submit Employee</span>
                    <span className="sm:hidden">Submit</span>
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default AddEmployeePage;
