'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import Swal from 'sweetalert2';
import { 
  Lock, 
  Eye, 
  EyeOff, 
  Key, 
  Shield, 
  CheckCircle, 
  AlertCircle,
  RefreshCw,
  ArrowRight,
  ShieldCheck,
  Zap,
  LockKeyhole,
  CircleCheck,
  Circle,
  AlertTriangle,
  Sparkles
} from 'lucide-react';
import { motion } from 'framer-motion';

const PasswordChange = () => {
  const router = useRouter();
  
  const [form, setForm] = useState({
    current_password: '',
    new_password: '',
    confirm_password: '',
  });

  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const togglePasswordVisibility = (field) => {
    switch (field) {
      case 'current':
        setShowCurrentPassword(!showCurrentPassword);
        break;
      case 'new':
        setShowNewPassword(!showNewPassword);
        break;
      case 'confirm':
        setShowConfirmPassword(!showConfirmPassword);
        break;
    }
  };

  // Password strength checker
  const checkPasswordStrength = (password) => {
    if (!password) return { score: 0, text: 'Very Weak', color: 'gray', class: 'bg-gray-300' };
    
    let score = 0;
    const requirements = {
      length: password.length >= 8,
      uppercase: /[A-Z]/.test(password),
      lowercase: /[a-z]/.test(password),
      number: /[0-9]/.test(password),
      special: /[^A-Za-z0-9]/.test(password),
    };

    Object.values(requirements).forEach(met => {
      if (met) score++;
    });

    const levels = [
      { text: 'Very Weak', color: 'text-red-600', class: 'bg-red-500', bg: 'bg-red-50' },
      { text: 'Weak', color: 'text-red-600', class: 'bg-red-500', bg: 'bg-red-50' },
      { text: 'Fair', color: 'text-amber-600', class: 'bg-amber-500', bg: 'bg-amber-50' },
      { text: 'Good', color: 'text-teal-600', class: 'bg-teal-500', bg: 'bg-teal-50' },
      { text: 'Strong', color: 'text-emerald-600', class: 'bg-emerald-500', bg: 'bg-emerald-50' },
      { text: 'Very Strong', color: 'text-emerald-600', class: 'bg-emerald-500', bg: 'bg-emerald-50' }
    ];
    
    return { ...levels[score], requirements, score };
  };

  const newPasswordStrength = checkPasswordStrength(form.new_password);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
    
    // Clear error for this field
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
    
    // Clear confirm password error if passwords match
    if (name === 'new_password' && form.confirm_password && value === form.confirm_password) {
      setErrors(prev => ({ ...prev, confirm_password: null }));
    }
    
    if (name === 'confirm_password' && value === form.new_password) {
      setErrors(prev => ({ ...prev, confirm_password: null }));
    }
  };

  const validateForm = () => {
    const newErrors = {};
    
    if (!form.current_password) {
      newErrors.current_password = 'Current password is required';
    }
    
    if (!form.new_password) {
      newErrors.new_password = 'New password is required';
    } else {
      const strength = checkPasswordStrength(form.new_password);
      if (strength.score < 3) {
        newErrors.new_password = 'Password is too weak';
      }
    }
    
    if (!form.confirm_password) {
      newErrors.confirm_password = 'Please confirm your new password';
    } else if (form.new_password !== form.confirm_password) {
      newErrors.confirm_password = 'Passwords do not match';
    }
    
    if (form.current_password && form.new_password && 
        form.current_password === form.new_password) {
      newErrors.new_password = 'New password must be different from current password';
    }
    
    return newErrors;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const validationErrors = validateForm();
    
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      
      // Show error summary
      const errorMessages = Object.values(validationErrors).join('\n');
      Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        text: errorMessages,
        confirmButtonColor: '#0B6D76'
      });
      return;
    }
    
    setIsLoading(true);
    setErrors({});

    try {
      const response = await fetch('/api/internal/foreign-student/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          current_password: form.current_password,
          new_password: form.new_password,
          confirm_password: form.confirm_password,
        }),
        credentials: 'include'
      });

      const data = await response.json();

      if (response.ok) {
        // Clear form
        setForm({
          current_password: '',
          new_password: '',
          confirm_password: '',
        });

        // Show success message
        Swal.fire({
          icon: 'success',
          title: 'Password Updated!',
          html: `
            <div class="text-center">
              <div class="w-20 h-20 bg-gradient-to-br from-emerald-100 to-teal-100 rounded-full flex items-center justify-center mx-auto mb-6">
                <svg class="w-10 h-10 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
              </div>
              <h3 class="text-2xl font-bold text-gray-800 mb-3">Password Changed Successfully!</h3>
              <p class="text-gray-600">Your account password has been securely updated.</p>
            </div>
          `,
          confirmButtonColor: '#0B6D76',
          showCancelButton: false,
          confirmButtonText: 'Continue to Login',
        }).then((result) => {
          if (result.isConfirmed) {
            // Redirect to login page
            router.push('/foreign-students/login');
          }
        });

      } else {
        // Handle specific errors
        let errorMessage = data.message || 'Failed to update password';
        
        if (data.errors) {
          setErrors(data.errors);
          errorMessage = Object.values(data.errors).join('\n');
        } else if (response.status === 401) {
          errorMessage = 'Current password is incorrect';
          setErrors({ current_password: 'Current password is incorrect' });
        }

        Swal.fire({
          icon: 'error',
          title: 'Update Failed',
          html: `
            <div class="text-left">
              <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-4">
                <div class="flex items-center">
                  <AlertTriangle class="h-5 w-5 text-red-500 mr-3" />
                  <p class="text-red-800 font-semibold">${errorMessage}</p>
                </div>
              </div>
              <p class="text-sm text-gray-600">Please check your current password and try again.</p>
            </div>
          `,
          confirmButtonColor: '#0B6D76'
        });
      }
    } catch (err) {
      console.error('Password change error:', err);
      Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Please check your connection and try again.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // Password requirements checklist
  const passwordRequirements = [
    { label: 'At least 8 characters', met: form.new_password?.length >= 8, icon: <Key className="w-4 h-4" /> },
    { label: 'One uppercase letter', met: /[A-Z]/.test(form.new_password), icon: <ArrowRight className="w-4 h-4" /> },
    { label: 'One lowercase letter', met: /[a-z]/.test(form.new_password), icon: <ArrowRight className="w-4 h-4" /> },
    { label: 'One number', met: /[0-9]/.test(form.new_password), icon: <Zap className="w-4 h-4" /> },
    { label: 'One special character', met: /[^A-Za-z0-9]/.test(form.new_password), icon: <Sparkles className="w-4 h-4" /> },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white py-8 px-4">
      <div className="max-w-2xl mx-auto">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-10"
        >
          <div className="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 rounded-full border border-blue-200 mb-4">
            <ShieldCheck className="w-4 h-4 text-blue-600" />
            <span className="text-sm font-medium text-blue-700">Account Security</span>
          </div>
          <h1 className="text-4xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-black mb-3">
            Update Your Password
          </h1>
          <p className="text-gray-600 text-lg max-w-md mx-auto">
            Secure your account with a strong, unique password
          </p>
        </motion.div>

        <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
          {/* Security Header */}
          <div className="bg-gradient-to-r from-blue-500 to-cyan-500 p-6 text-white">
            <div className="flex items-center gap-4">
              <div className="p-3 bg-white/20 rounded-xl backdrop-blur-sm">
                <LockKeyhole className="w-8 h-8" />
              </div>
              <div>
                <h2 className="text-xl font-bold">Password Security</h2>
                <p className="text-blue-100 text-sm mt-1">Protect your account with a strong password</p>
              </div>
            </div>
          </div>

          <div className="p-6 md:p-8">
            {/* Security Tips */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="bg-gradient-to-br from-blue-50 to-cyan-50 rounded-xl p-6 mb-8 border border-blue-200"
            >
              <div className="flex items-start gap-4">
                <div className="p-3 bg-white rounded-lg border border-blue-200 flex-shrink-0">
                  <Shield className="w-6 h-6 text-blue-600" />
                </div>
                <div>
                  <h3 className="font-bold text-blue-800 mb-3">Security Best Practices</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                      <span className="text-sm text-gray-700">Use unique passwords</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                      <span className="text-sm text-gray-700">Avoid personal information</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                      <span className="text-sm text-gray-700">Consider a password manager</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                      <span className="text-sm text-gray-700">Update regularly</span>
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>

            <form onSubmit={handleSubmit} className="space-y-8">
              {/* Current Password */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-3">
                  <span className="flex items-center gap-2">
                    <Lock className="w-4 h-4 text-gray-500" />
                    Current Password
                    <span className="text-rose-500">*</span>
                  </span>
                </label>
                <div className="relative">
                  <input
                    type={showCurrentPassword ? 'text' : 'password'}
                    name="current_password"
                    value={form.current_password}
                    onChange={handleChange}
                    placeholder="Enter your current password"
                    className="w-full px-4 py-3 pl-12 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200 text-gray-700 placeholder-gray-400"
                    required
                  />
                  <Lock className="absolute left-4 top-3.5 w-5 h-5 text-gray-400" />
                  <button
                    type="button"
                    onClick={() => togglePasswordVisibility('current')}
                    className="absolute right-4 top-3.5 text-gray-500 hover:text-gray-700 transition-colors"
                  >
                    {showCurrentPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                  </button>
                </div>
                {errors.current_password && (
                  <motion.p 
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="text-sm text-rose-600 mt-2 flex items-center gap-2"
                  >
                    <AlertCircle className="w-4 h-4" />
                    {errors.current_password}
                  </motion.p>
                )}
              </div>

              {/* New Password */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-3">
                  <span className="flex items-center gap-2">
                    <Key className="w-4 h-4 text-gray-500" />
                    New Password
                    <span className="text-rose-500">*</span>
                  </span>
                </label>
                <div className="relative">
                  <input
                    type={showNewPassword ? 'text' : 'password'}
                    name="new_password"
                    value={form.new_password}
                    onChange={handleChange}
                    placeholder="Create a strong new password"
                    className="w-full px-4 py-3 pl-12 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200 text-gray-700 placeholder-gray-400"
                    required
                  />
                  <Key className="absolute left-4 top-3.5 w-5 h-5 text-gray-400" />
                  <button
                    type="button"
                    onClick={() => togglePasswordVisibility('new')}
                    className="absolute right-4 top-3.5 text-gray-500 hover:text-gray-700 transition-colors"
                  >
                    {showNewPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                  </button>
                </div>
                
                {/* Password Strength Indicator */}
                {form.new_password && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    className="mt-4 space-y-3"
                  >
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-gray-700">Password Strength</span>
                      <span className={`text-sm font-bold ${newPasswordStrength.color}`}>
                        {newPasswordStrength.text}
                      </span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2 overflow-hidden">
                      <div 
                        className={`h-2 rounded-full transition-all duration-500 ${newPasswordStrength.class}`}
                        style={{ width: `${(newPasswordStrength.score / 5) * 100}%` }}
                      ></div>
                    </div>
                  </motion.div>
                )}
                
                {errors.new_password && (
                  <motion.p 
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="text-sm text-rose-600 mt-2 flex items-center gap-2"
                  >
                    <AlertCircle className="w-4 h-4" />
                    {errors.new_password}
                  </motion.p>
                )}
              </div>

              {/* Confirm New Password */}
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-3">
                  <span className="flex items-center gap-2">
                    <ShieldCheck className="w-4 h-4 text-gray-500" />
                    Confirm New Password
                    <span className="text-rose-500">*</span>
                  </span>
                </label>
                <div className="relative">
                  <input
                    type={showConfirmPassword ? 'text' : 'password'}
                    name="confirm_password"
                    value={form.confirm_password}
                    onChange={handleChange}
                    placeholder="Confirm your new password"
                    className="w-full px-4 py-3 pl-12 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200 text-gray-700 placeholder-gray-400"
                    required
                  />
                  <ShieldCheck className="absolute left-4 top-3.5 w-5 h-5 text-gray-400" />
                  <button
                    type="button"
                    onClick={() => togglePasswordVisibility('confirm')}
                    className="absolute right-4 top-3.5 text-gray-500 hover:text-gray-700 transition-colors"
                  >
                    {showConfirmPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                  </button>
                </div>
                {errors.confirm_password && (
                  <motion.p 
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="text-sm text-rose-600 mt-2 flex items-center gap-2"
                  >
                    <AlertCircle className="w-4 h-4" />
                    {errors.confirm_password}
                  </motion.p>
                )}
                {form.confirm_password && form.new_password === form.confirm_password && form.new_password && (
                  <motion.p 
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    className="text-sm text-emerald-600 mt-2 flex items-center gap-2"
                  >
                    <CheckCircle className="w-4 h-4" />
                    Passwords match
                  </motion.p>
                )}
              </div>

              {/* Password Requirements */}
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-gray-50 rounded-xl p-6 border border-gray-200"
              >
                <h4 className="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2">
                  <Zap className="w-4 h-4 text-amber-500" />
                  Password Requirements
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {passwordRequirements.map((req, index) => (
                    <motion.div
                      key={index}
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: index * 0.1 }}
                      className={`flex items-center gap-3 p-3 rounded-lg transition-all duration-200 ${
                        req.met ? 'bg-emerald-50 border border-emerald-200' : 'bg-white border border-gray-200'
                      }`}
                    >
                      <div className={`p-2 rounded-lg ${
                        req.met ? 'bg-emerald-100 text-emerald-600' : 'bg-gray-100 text-gray-400'
                      }`}>
                        {req.met ? <CheckCircle className="w-4 h-4" /> : req.icon}
                      </div>
                      <span className={`text-sm font-medium ${
                        req.met ? 'text-emerald-700' : 'text-gray-600'
                      }`}>
                        {req.label}
                      </span>
                    </motion.div>
                  ))}
                </div>
              </motion.div>

              {/* Submit Button */}
              <div className="pt-4">
                <motion.button
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  type="submit"
                  disabled={isLoading}
                  className="w-full flex items-center justify-center gap-3 px-6 py-4 bg-gradient-to-r from-blue-500 to-cyan-500 text-white rounded-xl hover:shadow-lg transition-all duration-200 font-bold text-lg disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLoading ? (
                    <>
                      <RefreshCw className="w-5 h-5 animate-spin" />
                      Updating Password...
                    </>
                  ) : (
                    <>
                      <Lock className="w-5 h-5" />
                      Update Password
                      <ArrowRight className="w-5 h-5" />
                    </>
                  )}
                </motion.button>
              </div>

            </form>
          </div>
        </div>

        {/* Additional Security Info */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.3 }}
          className="mt-8 text-center"
        >
          <p className="text-sm text-gray-500">
            For security reasons, you'll be logged out after password change
          </p>
          <p className="text-xs text-gray-400 mt-1">
            You'll need to sign in again with your new password
          </p>
        </motion.div>
      </div>
    </div>
  );
};

export default PasswordChange;