import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  FaArrowLeft, 
  FaSave, 
  FaUser, 
  FaEnvelope, 
  FaKey, 
  FaEye, 
  FaEyeSlash,
  FaSpinner,
  FaCheckCircle,
  FaTimesCircle,
  FaExclamationTriangle,
  FaUserTag,
  FaIdBadge,
  FaShieldAlt
} from 'react-icons/fa';
import { toast, ToastContainer, Bounce } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import LinkField from '../components/LinkField';
import {
  fetchCurrentUserProfile,
  updateUserProfile,
  changeUserPassword,
  type UserProfile,
  type UpdateUserProfileData
} from '../services/userProfileService';

const UserProfilePage: React.FC = () => {
  const navigate = useNavigate();
  
  // State
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [isSystemManager, setIsSystemManager] = useState(false);
  const [changingPassword, setChangingPassword] = useState(false);
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [error, setError] = useState<string | null>(null);
  
  // Form state
  const [formData, setFormData] = useState({
    first_name: '',
    middle_name: '',
    last_name: '',
    role_profile_name: '',
    custom_user_id : '',
  });
  
  // Password change state
  const [showPasswordSection, setShowPasswordSection] = useState(false);
  const [passwordData, setPasswordData] = useState({
    old_password: '',
    new_password: '',
    confirm_password: '',
  });
  const [showOldPassword, setShowOldPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  
  // Fetch user profile and check role on mount
  useEffect(() => {
    const loadProfile = async () => {
      try {
        setLoading(true);
        
        // NEW: Check if user is System Manager
        const roleResponse = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include',
          body: JSON.stringify({
            roles: 'System Manager'
          })
        });
        const roleData = await roleResponse.json();
        const isSysManager = roleData.message?.has_role || false;
        setIsSystemManager(isSysManager);
        console.log('Is System Manager:', isSysManager);
        
        // Fetch profile data
        const data = await fetchCurrentUserProfile();

        // Debug: Log everything
        console.log('Full profile data:', JSON.stringify(data, null, 2));
        console.log('role_profile_name:', data.role_profile_name);
        console.log('All keys:', Object.keys(data));

        setProfile(data);
        setFormData({
          first_name: data.first_name || '',
          middle_name: data.middle_name || '',
          last_name: data.last_name || '',
          role_profile_name: data.role_profile_name || '',
          custom_user_id: data.custom_user_id || '',
        });

        // Debug: Log formData after setting
        console.log('FormData role_profile_name:', data.role_profile_name || '');

      } catch (err) {
        const errorMsg = err instanceof Error ? err.message : 'Failed to load profile';
        setError(errorMsg);
        toast.error(errorMsg, {
          position: "top-right",
          autoClose: 5000,
          icon: <FaTimesCircle />
        });
      } finally {
        setLoading(false);
      }
    };
    
    loadProfile();
  }, []);
  
  // Handle form input changes
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };
  
  // Handle password input changes
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setPasswordData(prev => ({ ...prev, [name]: value }));
  };
  
  // Save profile changes
  const handleSaveProfile = async () => {
    if (!profile?.email) return;
    
    try {
      setSaving(true);
      
      const updateData: UpdateUserProfileData = {
        first_name: formData.first_name,
        middle_name: formData.middle_name,
        last_name: formData.last_name,
        role_profile_name: formData.role_profile_name,
      };
      
      const updatedProfile = await updateUserProfile(profile.email, updateData);
      setProfile(prev => prev ? { ...prev, ...updatedProfile } : updatedProfile);
      
      toast.success('Profile updated successfully!', {
        position: "top-right",
        autoClose: 3000,
        icon: <FaCheckCircle />
      });
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Failed to update profile';
      toast.error(errorMsg, {
        position: "top-right",
        autoClose: 5000,
        icon: <FaTimesCircle />
      });
    } finally {
      setSaving(false);
    }
  };
  
  // Change password
  const handleChangePassword = async () => {
    // Validation
    if (!passwordData.old_password) {
      toast.error('Please enter your current password', {
        position: "top-right",
        autoClose: 3000,
        icon: <FaExclamationTriangle />
      });
      return;
    }
    
    if (!passwordData.new_password) {
      toast.error('Please enter a new password', {
        position: "top-right",
        autoClose: 3000,
        icon: <FaExclamationTriangle />
      });
      return;
    }
    
    if (passwordData.new_password.length < 8) {
      toast.error('Password must be at least 8 characters long', {
        position: "top-right",
        autoClose: 3000,
        icon: <FaExclamationTriangle />
      });
      return;
    }
    
    if (passwordData.new_password !== passwordData.confirm_password) {
      toast.error('New passwords do not match', {
        position: "top-right",
        autoClose: 3000,
        icon: <FaExclamationTriangle />
      });
      return;
    }
    
    try {
      setChangingPassword(true);
      
      await changeUserPassword(passwordData.new_password, passwordData.old_password);
      
      toast.success('Password changed successfully!', {
        position: "top-right",
        autoClose: 3000,
        icon: <FaCheckCircle />
      });
      
      // Clear password fields
      setPasswordData({
        old_password: '',
        new_password: '',
        confirm_password: '',
      });
      setShowPasswordSection(false);
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Failed to change password';
      toast.error(errorMsg, {
        position: "top-right",
        autoClose: 5000,
        icon: <FaTimesCircle />
      });
    } finally {
      setChangingPassword(false);
    }
  };
  
  // Loading state
  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <FaSpinner className="animate-spin text-blue-500 text-4xl mx-auto" />
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading profile...</p>
        </div>
      </div>
    );
  }
  
  // Error state
  if (error && !profile) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">
            <FaTimesCircle className="inline mr-2" />
            Error Loading Profile
          </h2>
          <p className="text-red-700 dark:text-red-400">{error}</p>
          <button 
            onClick={() => navigate(-1)}
            className="mt-4 bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded"
          >
            Go Back
          </button>
        </div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-6">
      <ToastContainer
        position="top-right"
        autoClose={4000}
        hideProgressBar={false}
        newestOnTop
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="colored"
        transition={Bounce}
      />
      
      {/* Header */}
      <div className="mb-6 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <button
            onClick={() => navigate(-1)}
            className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 flex items-center gap-2"
          >
            <FaArrowLeft />
            <span className="text-gray-900 dark:text-white text-xl font-semibold">User Profile</span>
          </button>
        </div>
        
        <button
          onClick={handleSaveProfile}
          disabled={saving}
          className="bg-green-600 hover:bg-green-700 text-white px-6 py-2 rounded-lg flex items-center gap-2 disabled:opacity-50 shadow-lg transition-all"
        >
          {saving ? (
            <>
              <FaSpinner className="animate-spin" />
              Saving...
            </>
          ) : (
            <>
              <FaSave />
              Save Changes
            </>
          )}
        </button>
      </div>
      
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Profile Card */}
        <div className="lg:col-span-1">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-200 dark:border-gray-700 overflow-hidden">
            {/* Profile Header */}
            <div className="bg-gradient-to-r from-blue-500 to-blue-600 p-6 text-center">
              <div className="w-24 h-24 bg-white/20 rounded-full mx-auto flex items-center justify-center mb-4">
                {profile?.user_image ? (
                  <img 
                    src={profile.user_image} 
                    alt="Profile" 
                    className="w-20 h-20 rounded-full object-cover"
                  />
                ) : (
                  <FaUser className="text-white text-4xl" />
                )}
              </div>
              <h2 className="text-xl font-bold text-white">{profile?.full_name || 'User'}</h2>
              <p className="text-white/80 text-sm mt-1">{profile?.email}</p>
            </div>
            
            {/* Profile Stats */}
            <div className="p-4 space-y-3">
              <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <FaIdBadge className="text-blue-500" />
                <div>
                  <p className="text-xs text-gray-500 dark:text-gray-400">Username</p>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">
                    {profile?.username || '-'}
                  </p>
                </div>
              </div>
              
              <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <FaUserTag className="text-green-500" />
                <div>
                  <p className="text-xs text-gray-500 dark:text-gray-400">Role Profile</p>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">
                    {profile?.role_profile_name || '-'}
                  </p>
                </div>
              </div>
              
              <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <FaShieldAlt className="text-purple-500" />
                <div>
                  <p className="text-xs text-gray-500 dark:text-gray-400">Status</p>
                  <p className={`text-sm font-medium ${profile?.enabled ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}>
                    {profile?.enabled ? 'Active' : 'Inactive'}
                  </p>
                </div>
              </div>
            </div>
            
            {/* User Roles */}
            {/* {profile?.roles && profile.roles.length > 0 && (
              <div className="p-4 border-t border-gray-200 dark:border-gray-700">
                <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                  Assigned Roles
                </h3>
                <div className="flex flex-wrap gap-2">
                  {profile.roles.map((role, index) => (
                    <span 
                      key={index}
                      className="px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-full text-xs font-medium"
                    >
                      {role.role}
                    </span>
                  ))}
                </div>
              </div>
            )} */}
          </div>
        </div>
        
        {/* Right Column - Edit Forms */}
        <div className="lg:col-span-2 space-y-6">
          {/* Basic Information */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-200 dark:border-gray-700 p-6">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaUser className="text-blue-500" />
              Basic Information
            </h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Email (Read-only) */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Email
                  <span className="ml-1 text-gray-400">(Read-only)</span>
                </label>
                <div className="relative">
                  <FaEnvelope className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={14} />
                  <input
                    type="email"
                    value={profile?.email || ''}
                    disabled
                    className="w-full pl-10 pr-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed"
                  />
                </div>
              </div>
              
              {/* Full Name (Read-only) */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Full Name
                  <span className="ml-1 text-gray-400">(Auto-generated)</span>
                </label>
                <input
                  type="text"
                  value={profile?.full_name || ''}
                  disabled
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed"
                />
              </div>
              
              {/* First Name */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  First Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  name="first_name"
                  value={formData.first_name}
                  onChange={handleInputChange}
                  placeholder="Enter first name"
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              
              {/* Middle Name */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Middle Name
                </label>
                <input
                  type="text"
                  name="middle_name"
                  value={formData.middle_name}
                  onChange={handleInputChange}
                  placeholder="Enter middle name"
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              
              {/* Last Name */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Last Name
                </label>
                <input
                  type="text"
                  name="last_name"
                  value={formData.last_name}
                  onChange={handleInputChange}
                  placeholder="Enter last name"
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  User ID No
                </label>
                <input
                  type="text"
                  name="custom_user_id"
                  value={formData.custom_user_id}
                  onChange={handleInputChange}
                  placeholder="Enter User No"
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              
              {/* Role Profile */}
              {/* <div>
                <LinkField
                  label="Role Profile"
                  doctype="Role Profile"
                  value={formData.role_profile_name}
                  onChange={(val) => setFormData(prev => ({ ...prev, role_profile_name: val }))}
                  placeholder="Select Role Profile"
                  disabled={false}
                />
              </div> */}

              {/* Role Profile - Only System Manager can edit */}
              <div>
                <LinkField
                  label="Role Profile"
                  doctype="Role Profile"
                  value={formData.role_profile_name}
                  onChange={(val) => setFormData(prev => ({ ...prev, role_profile_name: val }))}
                  placeholder="Select Role Profile"
                  disabled={!isSystemManager}
                />
              </div>
            </div>
          </div>
          
          {/* Password Section */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-200 dark:border-gray-700 p-6">
            <div className="flex items-center justify-between mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white flex items-center gap-2">
                <FaKey className="text-orange-500" />
                Change Password
              </h2>
              <button
                onClick={() => setShowPasswordSection(!showPasswordSection)}
                className="text-sm text-blue-600 dark:text-blue-400 hover:underline"
              >
                {showPasswordSection ? 'Cancel' : 'Change Password'}
              </button>
            </div>
            
            {showPasswordSection ? (
              <div className="space-y-4">
                {/* Current Password */}
                <div>
                  <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Current Password <span className="text-red-500">*</span>
                  </label>
                  <div className="relative">
                    <input
                      type={showOldPassword ? 'text' : 'password'}
                      name="old_password"
                      value={passwordData.old_password}
                      onChange={handlePasswordChange}
                      placeholder="Enter current password"
                      className="w-full px-3 py-2 pr-10 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                    <button
                      type="button"
                      onClick={() => setShowOldPassword(!showOldPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showOldPassword ? <FaEyeSlash size={14} /> : <FaEye size={14} />}
                    </button>
                  </div>
                </div>
                
                {/* New Password */}
                <div>
                  <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                    New Password <span className="text-red-500">*</span>
                  </label>
                  <div className="relative">
                    <input
                      type={showNewPassword ? 'text' : 'password'}
                      name="new_password"
                      value={passwordData.new_password}
                      onChange={handlePasswordChange}
                      placeholder="Enter new password (min 8 characters)"
                      className="w-full px-3 py-2 pr-10 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                    <button
                      type="button"
                      onClick={() => setShowNewPassword(!showNewPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showNewPassword ? <FaEyeSlash size={14} /> : <FaEye size={14} />}
                    </button>
                  </div>
                  {passwordData.new_password && passwordData.new_password.length < 8 && (
                    <p className="mt-1 text-xs text-red-500">Password must be at least 8 characters</p>
                  )}
                </div>
                
                {/* Confirm New Password */}
                <div>
                  <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Confirm New Password <span className="text-red-500">*</span>
                  </label>
                  <div className="relative">
                    <input
                      type={showConfirmPassword ? 'text' : 'password'}
                      name="confirm_password"
                      value={passwordData.confirm_password}
                      onChange={handlePasswordChange}
                      placeholder="Confirm new password"
                      className="w-full px-3 py-2 pr-10 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                    <button
                      type="button"
                      onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showConfirmPassword ? <FaEyeSlash size={14} /> : <FaEye size={14} />}
                    </button>
                  </div>
                  {passwordData.confirm_password && passwordData.new_password !== passwordData.confirm_password && (
                    <p className="mt-1 text-xs text-red-500">Passwords do not match</p>
                  )}
                  {passwordData.confirm_password && passwordData.new_password === passwordData.confirm_password && passwordData.new_password.length >= 8 && (
                    <p className="mt-1 text-xs text-green-500 flex items-center gap-1">
                      <FaCheckCircle size={10} /> Passwords match
                    </p>
                  )}
                </div>
                
                {/* Change Password Button */}
                <div className="pt-2">
                  <button
                    onClick={handleChangePassword}
                    disabled={changingPassword}
                    className="w-full bg-orange-600 hover:bg-orange-700 text-white px-4 py-2.5 rounded-lg flex items-center justify-center gap-2 disabled:opacity-50 transition-colors"
                  >
                    {changingPassword ? (
                      <>
                        <FaSpinner className="animate-spin" />
                        Changing Password...
                      </>
                    ) : (
                      <>
                        <FaKey />
                        Change Password
                      </>
                    )}
                  </button>
                </div>
              </div>
            ) : (
              <div className="text-center py-6 text-gray-500 dark:text-gray-400">
                <FaKey className="mx-auto text-3xl mb-2 text-gray-300 dark:text-gray-600" />
                <p className="text-sm">Click "Change Password" to update your password</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default UserProfilePage;