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

const ChangePasswordModal = ({ isOpen, onClose }) => {
  const { isLight } = useTheme();
  const [formData, setFormData] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [submitMessage, setSubmitMessage] = useState("");
  const [success, setSuccess] = useState(false);
  const [showConfirmation, setShowConfirmation] = useState(false);

  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.currentPassword.trim()) {
      newErrors.currentPassword = "Current password is required";
    }

    if (!formData.newPassword.trim()) {
      newErrors.newPassword = "New password is required";
    }

    if (!formData.confirmPassword.trim()) {
      newErrors.confirmPassword = "Please confirm your new password";
    } else if (formData.newPassword !== formData.confirmPassword) {
      newErrors.confirmPassword = "Passwords do not match";
    }

    if (formData.currentPassword === formData.newPassword) {
      newErrors.newPassword = "New password must be different from current password";
    }

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

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

    if (!validateForm()) {
      return;
    }

    // Show confirmation popup instead of submitting immediately
    setShowConfirmation(true);
  };

  const handleConfirmSubmit = async () => {
    setIsSubmitting(true);
    setSubmitMessage("");
    setSuccess(false);
    setShowConfirmation(false);

    try {
      // Get current user data from localStorage
      const userData = localStorage.getItem("user");
      if (!userData) {
        throw new Error("User session not found. Please login again.");
      }
      
      const user = JSON.parse(userData);
      
      
      
      
      // Make API call to change the password
      const apiUrl = buildApiUrl(API_ENDPOINTS.CHANGE_PASSWORD);
      const requestBody = {
        user_id: user.user_id,
        currentPassword: formData.currentPassword,
        newPassword: formData.newPassword,
      };
      
      console.log('Making API call to:', apiUrl);
      console.log('Request body:', requestBody);
      
      let response;
      try {
        response = await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(requestBody),
        });
      } catch (fetchError) {
        console.error('Network error:', fetchError);
        throw new Error('Network error: Unable to connect to the server. Please check if the backend is running.');
      }
      
      console.log('Response status:', response.status);
      console.log('Response headers:', response.headers);
      
      // Check if response has content
      const responseText = await response.text();
      console.log('Response text:', responseText);
      
      // Try to parse as JSON if there's content
      let responseData = null;
      if (responseText.trim()) {
        try {
          responseData = JSON.parse(responseText);
        } catch (parseError) {
          console.error('Failed to parse response as JSON:', parseError);
        }
      }

      if (!response.ok) {
        let errorMessage = 'Failed to change password';
        
        if (responseData && responseData.error) {
          errorMessage = responseData.error;
        } else {
          // If response is not JSON, use status text
          errorMessage = response.statusText || `HTTP ${response.status}: ${errorMessage}`;
        }
        
        throw new Error(errorMessage);
      }

      setSuccess(true);
      setSubmitMessage("Password changed successfully!");

      // Clear form
      setFormData({
        currentPassword: "",
        newPassword: "",
        confirmPassword: "",
      });

      // Close modal after success
      setTimeout(() => {
        setSuccess(false);
        setSubmitMessage("");
        onClose();
      }, 2000);

    } catch (error) {
      console.error("Error changing password:", error);
      setSubmitMessage(error.message || "Failed to change password. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    setFormData({
      currentPassword: "",
      newPassword: "",
      confirmPassword: "",
    });
    setErrors({});
    setSubmitMessage("");
    setSuccess(false);
    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 transition-opacity duration-200 ${
          showConfirmation ? 'opacity-0 pointer-events-none' : 'opacity-100'
        }`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div
          className={`p-6 border-b ${
            isLight ? "border-yellow-200" : "border-gray-700"
          }`}
        >
          <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"
                }`}
              >
                <FaLock
                  className={`text-lg ${
                    isLight ? "text-amber-600" : "text-cyan-400"
                  }`}
                />
              </div>
              <div>
                <h2
                  className={`text-xl font-semibold ${
                    isLight ? "text-amber-800" : "text-gray-100"
                  }`}
                >
                  Change Password
                </h2>
                <p
                  className={`text-sm ${
                    isLight ? "text-amber-700" : "text-gray-300"
                  } opacity-75`}
                >
                  Update your account password
                </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">
            {/* Current Password */}
            <div>
              <label className={`block text-sm font-medium mb-2 ${labelClass}`}>
                Current Password
              </label>
              <div className="relative">
                <input
                  type={showCurrentPassword ? "text" : "password"}
                  name="currentPassword"
                  value={formData.currentPassword}
                  onChange={handleInputChange}
                  className={`w-full px-3 py-2 pr-10 border rounded-lg focus:ring-2 focus:ring-offset-0 transition-colors ${inputClass} ${
                    errors.currentPassword ? "border-red-500" : ""
                  }`}
                  placeholder="Enter current password"
                  disabled={isSubmitting}
                />
                <button
                  type="button"
                  onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 flex items-center justify-center w-6 h-6"
                  disabled={isSubmitting}
                >
                  {showCurrentPassword ? <FaEyeSlash className="flex-shrink-0" /> : <FaEye className="flex-shrink-0" />}
                </button>
              </div>
              {errors.currentPassword && (
                <p className="text-red-500 text-sm mt-1">{errors.currentPassword}</p>
              )}
            </div>

            {/* New Password */}
            <div>
              <label className={`block text-sm font-medium mb-2 ${labelClass}`}>
                New Password
              </label>
              <div className="relative">
                <input
                  type={showNewPassword ? "text" : "password"}
                  name="newPassword"
                  value={formData.newPassword}
                  onChange={handleInputChange}
                  className={`w-full px-3 py-2 pr-10 border rounded-lg focus:ring-2 focus:ring-offset-0 transition-colors ${inputClass} ${
                    errors.newPassword ? "border-red-500" : ""
                  }`}
                  placeholder="Enter new password"
                  disabled={isSubmitting}
                />
                <button
                  type="button"
                  onClick={() => setShowNewPassword(!showNewPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 flex items-center justify-center w-6 h-6"
                  disabled={isSubmitting}
                >
                  {showNewPassword ? <FaEyeSlash className="flex-shrink-0" /> : <FaEye className="flex-shrink-0" />}
                </button>
              </div>
              {errors.newPassword && (
                <p className="text-red-500 text-sm mt-1">{errors.newPassword}</p>
              )}
            </div>

            {/* Confirm New Password */}
            <div>
              <label className={`block text-sm font-medium mb-2 ${labelClass}`}>
                Confirm New Password
              </label>
              <div className="relative">
                <input
                  type={showConfirmPassword ? "text" : "password"}
                  name="confirmPassword"
                  value={formData.confirmPassword}
                  onChange={handleInputChange}
                  className={`w-full px-3 py-2 pr-10 border rounded-lg focus:ring-2 focus:ring-offset-0 transition-colors ${inputClass} ${
                    errors.confirmPassword ? "border-red-500" : ""
                  }`}
                  placeholder="Confirm new password"
                  disabled={isSubmitting}
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 flex items-center justify-center w-6 h-6"
                  disabled={isSubmitting}
                >
                  {showConfirmPassword ? <FaEyeSlash className="flex-shrink-0" /> : <FaEye className="flex-shrink-0" />}
                </button>
              </div>
              {errors.confirmPassword && (
                <p className="text-red-500 text-sm mt-1">{errors.confirmPassword}</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"
                }`}
                disabled={isSubmitting}
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={isSubmitting}
                className={`px-4 py-2 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 ${
                  isSubmitting ? "opacity-50 cursor-not-allowed" : ""
                } ${buttonClass}`}
              >
                {isSubmitting ? (
                  <>
                    <FaSpinner className="animate-spin flex-shrink-0" />
                    <span>Changing...</span>
                  </>
                ) : (
                  <>
                    <FaSave className="flex-shrink-0" />
                    <span>Change Password</span>
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>

      {/* Confirmation Popup */}
      {showConfirmation && (
        <div className="fixed inset-0 flex items-center justify-center z-70 p-4 pointer-events-none">
          <div className={`rounded-lg shadow-2xl max-w-md w-full mx-4 border relative z-10 pointer-events-auto ${
            isLight 
              ? "bg-white border-gray-200" 
              : "bg-slate-800 border-slate-600"
          }`}>
            {/* Header */}
            <div className={`p-6 border-b ${
              isLight ? "border-gray-200" : "border-slate-600"
            }`}>
              <div className="flex items-center gap-3">
                <div className={`p-2 rounded-full ${
                  isLight ? "bg-yellow-100" : "bg-blue-900"
                }`}>
                  <FaLock className={`text-lg ${
                    isLight ? "text-amber-600" : "text-cyan-400"
                  }`} />
                </div>
                <div>
                  <h3 className={`text-lg font-semibold ${
                    isLight ? "text-gray-800" : "text-slate-100"
                  }`}>
                    Confirm Password Change
                  </h3>
                  <p className={`text-sm ${
                    isLight ? "text-gray-500" : "text-slate-300"
                  }`}>
                    Are you sure you want to change your password?
                  </p>
                </div>
              </div>
            </div>

            {/* Content */}
            <div className="p-6">
              <p className={`text-sm mb-4 ${
                isLight ? "text-gray-700" : "text-slate-300"
              }`}>
                This action will update your account password. Please make sure you remember your new password.
              </p>
            </div>

            {/* Footer */}
            <div className={`flex justify-end gap-3 p-6 border-t ${
              isLight ? "border-gray-200" : "border-slate-600"
            }`}>
              <button
                onClick={() => setShowConfirmation(false)}
                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
                onClick={handleConfirmSubmit}
                className="px-4 py-2 rounded-lg font-medium transition-colors bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white"
              >
                Yes, Change Password
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ChangePasswordModal;
