'use client';

import React, { useState } from 'react';
import { 
  Lock, Eye, EyeOff, CheckCircle, 
  AlertCircle, Shield, Key, RefreshCw,
  ArrowLeft, LogOut
} from 'lucide-react';
import Heading from '../../atoms/Heading';
import { useRouter } from 'next/navigation';
import Swal from 'sweetalert2';

const ConsultantPassword = () => {
  const router = useRouter();
  const [form, setForm] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  });
  const [isLoading, setIsLoading] = useState(false);
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [passwordStrength, setPasswordStrength] = useState({
    score: 0,
    criteria: {
      length: false,
      uppercase: false,
      lowercase: false,
      number: false,
      special: false,
    }
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm({
      ...form,
      [name]: value,
    });

    // Check password strength for new password
    if (name === 'newPassword') {
      const criteria = {
        length: value.length >= 8,
        uppercase: /[A-Z]/.test(value),
        lowercase: /[a-z]/.test(value),
        number: /[0-9]/.test(value),
        special: /[^A-Za-z0-9]/.test(value),
      };

      const score = Object.values(criteria).filter(Boolean).length;
      
      setPasswordStrength({
        score,
        criteria,
      });
    }
  };

  const getPasswordStrengthColor = (score) => {
    if (score <= 2) return 'from-red-500 to-red-600';
    if (score === 3) return 'from-yellow-500 to-amber-500';
    if (score === 4) return 'from-blue-500 to-cyan-600';
    return 'from-green-500 to-emerald-600';
  };

  const getStrengthText = (score) => {
    if (score <= 2) return 'Weak';
    if (score === 3) return 'Fair';
    if (score === 4) return 'Good';
    return 'Strong';
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (form.newPassword !== form.confirmPassword) {
      await Swal.fire({
        icon: 'error',
        title: 'Password Mismatch',
        text: 'New password and confirm password do not match.',
        background: '#0B6D76',
        color: 'white',
        confirmButtonColor: '#ffffff',
        confirmButtonText: 'Try Again'
      });
      return;
    }

    if (passwordStrength.score < 3) {
      await Swal.fire({
        icon: 'warning',
        title: 'Weak Password',
        html: `
          <div class="text-left">
            <p class="mb-3">Your password is not strong enough. For better security:</p>
            <ul class="text-sm space-y-1 text-gray-700">
              <li class="flex items-center gap-2">
                ${passwordStrength.criteria.length ? '✓' : '✗'} At least 8 characters
              </li>
              <li class="flex items-center gap-2">
                ${passwordStrength.criteria.uppercase ? '✓' : '✗'} One uppercase letter
              </li>
              <li class="flex items-center gap-2">
                ${passwordStrength.criteria.lowercase ? '✓' : '✗'} One lowercase letter
              </li>
              <li class="flex items-center gap-2">
                ${passwordStrength.criteria.number ? '✓' : '✗'} One number
              </li>
              <li class="flex items-center gap-2">
                ${passwordStrength.criteria.special ? '✓' : '✗'} One special character
              </li>
            </ul>
          </div>
        `,
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'I Understand'
      });
      return;
    }

    setIsLoading(true);

    try {
      const response = await fetch('/api/frontend/consultant/consultantdashboard/password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          currentPassword: form.currentPassword,
          newPassword: form.newPassword,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        await Swal.fire({
          icon: 'success',
          title: 'Password Updated!',
          text: 'Your password has been changed successfully.',
          timer: 3000,
          background: '#0B6D76',
          color: 'white',
          showConfirmButton: false,
          timerProgressBar: true,
        });

        setForm({ currentPassword: '', newPassword: '', confirmPassword: '' });
        setPasswordStrength({ score: 0, criteria: {
          length: false, uppercase: false, lowercase: false, number: false, special: false
        }});
        
      } else {
        const errorMessages = data.message || {};
        
        if (typeof errorMessages === 'object') {
          const errorMessagesString = Object.values(errorMessages).join('\n');
          await Swal.fire({
            icon: 'error',
            title: 'Validation Error',
            html: `
              <div class="text-left">
                <p class="mb-3 font-medium">Please fix the following issues:</p>
                <div class="bg-red-50 p-3 rounded-lg">
                  ${errorMessagesString.split('\n').map(msg => `<p class="text-red-700">• ${msg}</p>`).join('')}
                </div>
              </div>
            `,
            confirmButtonColor: '#0B6D76',
            confirmButtonText: 'Try Again'
          });
        } else {
          await Swal.fire({
            icon: 'error',
            title: 'Update Failed',
            text: data.message || 'Failed to update password. Please try again.',
            confirmButtonColor: '#0B6D76',
            confirmButtonText: 'Retry'
          });
        }
      }
    } catch (err) {
      console.error(err);
      await Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Unable to connect to server. Please check your connection.',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'Retry'
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* Header */}
        <div className="text-center mb-10">
          <div className="flex items-center justify-center gap-4 mb-6">
            <div className="p-3 bg-gradient-to-r from-[#0B6D76] to-teal-600 rounded-xl shadow-lg">
              <Shield size={32} className="text-white" />
            </div>
            <div>
              <Heading level={4} className="text-3xl md:text-4xl font-bold text-gray-900">
                Security & Password
              </Heading>
              <p className="text-gray-600 mt-2">
                Update your password to keep your account secure
              </p>
            </div>
          </div>
          
          <div className="inline-flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-100 to-cyan-100 rounded-full">
            <Key size={16} className="text-blue-600" />
            <span className="text-blue-700 font-medium">
              🔐 Secure password updates
            </span>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left Column - Security Tips */}
          <div className="lg:col-span-1 space-y-6">
            {/* Security Tips Card */}
            <div className="bg-white rounded-2xl shadow-xl p-6 border border-gray-200">
              <div className="flex items-center gap-3 mb-4">
                <div className="p-2 bg-gradient-to-r from-green-100 to-emerald-100 rounded-lg">
                  <CheckCircle size={24} className="text-green-600" />
                </div>
                <h3 className="font-bold text-gray-900 text-lg">Security Tips</h3>
              </div>
              
              <div className="space-y-4">
                <div className="flex items-start gap-3">
                  <div className="p-1.5 bg-blue-100 rounded-md">
                    <Lock size={14} className="text-blue-600" />
                  </div>
                  <div>
                    <h4 className="font-medium text-gray-800">Use a Strong Password</h4>
                    <p className="text-sm text-gray-600">Include uppercase, lowercase, numbers & special characters</p>
                  </div>
                </div>
                
                <div className="flex items-start gap-3">
                  <div className="p-1.5 bg-green-100 rounded-md">
                    <RefreshCw size={14} className="text-green-600" />
                  </div>
                  <div>
                    <h4 className="font-medium text-gray-800">Update Regularly</h4>
                    <p className="text-sm text-gray-600">Change your password every 90 days for better security</p>
                  </div>
                </div>
                
                <div className="flex items-start gap-3">
                  <div className="p-1.5 bg-amber-100 rounded-md">
                    <AlertCircle size={14} className="text-amber-600" />
                  </div>
                  <div>
                    <h4 className="font-medium text-gray-800">Keep it Private</h4>
                    <p className="text-sm text-gray-600">Never share your password with anyone</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Password Requirements Card */}
            <div className="bg-gradient-to-r from-blue-50 to-cyan-50 rounded-2xl p-6 border border-blue-200">
              <h3 className="font-bold text-blue-800 text-lg mb-4">Password Requirements</h3>
              
              <div className="space-y-3">
                {[
                  { label: 'Minimum 8 characters', met: passwordStrength.criteria.length },
                  { label: 'At least one uppercase letter', met: passwordStrength.criteria.uppercase },
                  { label: 'At least one lowercase letter', met: passwordStrength.criteria.lowercase },
                  { label: 'At least one number', met: passwordStrength.criteria.number },
                  { label: 'At least one special character', met: passwordStrength.criteria.special },
                ].map((req, index) => (
                  <div key={index} className="flex items-center gap-3">
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center ${
                      req.met ? 'bg-green-500' : 'bg-gray-300'
                    }`}>
                      {req.met ? (
                        <CheckCircle size={12} className="text-white" />
                      ) : (
                        <div className="w-2 h-2 bg-gray-400 rounded-full" />
                      )}
                    </div>
                    <span className={`text-sm ${req.met ? 'text-green-700 font-medium' : 'text-gray-600'}`}>
                      {req.label}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Right Column - Password Form */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-2xl shadow-xl p-6 md:p-8 border border-gray-200">
              <div className="mb-8">
                <div className="flex items-center gap-3 mb-2">
                  <div className="p-2 bg-gradient-to-r from-[#0B6D76] to-teal-600 rounded-lg">
                    <Key size={24} className="text-white" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-gray-900">Change Password</h2>
                    <p className="text-gray-600">Enter your current and new password below</p>
                  </div>
                </div>
                
                {/* Password Strength Meter */}
                {form.newPassword && (
                  <div className="mt-6">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-medium text-gray-700">Password Strength</span>
                      <span className={`font-bold ${getPasswordStrengthColor(passwordStrength.score).includes('green') ? 'text-green-600' : 
                        getPasswordStrengthColor(passwordStrength.score).includes('blue') ? 'text-blue-600' :
                        getPasswordStrengthColor(passwordStrength.score).includes('yellow') ? 'text-amber-600' : 'text-red-600'
                      }`}>
                        {getStrengthText(passwordStrength.score)}
                      </span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2 overflow-hidden">
                      <div 
                        className={`h-full bg-gradient-to-r ${getPasswordStrengthColor(passwordStrength.score)} transition-all duration-500`}
                        style={{ width: `${(passwordStrength.score / 5) * 100}%` }}
                      />
                    </div>
                  </div>
                )}
              </div>

              <form onSubmit={handleSubmit} className="space-y-6">
                {/* Current Password */}
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <Lock size={16} className="text-gray-400" />
                    Current Password
                  </label>
                  <div className="relative">
                    <input
                      type={showCurrentPassword ? "text" : "password"}
                      name="currentPassword"
                      value={form.currentPassword}
                      onChange={handleChange}
                      className="w-full px-4 py-3 pl-12 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6D76] focus:border-[#0B6D76] text-gray-700"
                      required
                      placeholder="Enter your current password"
                    />
                    <Lock size={20} className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
                    <button
                      type="button"
                      onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                      className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showCurrentPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                    </button>
                  </div>
                </div>

                {/* New Password */}
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <Key size={16} className="text-gray-400" />
                    New Password
                  </label>
                  <div className="relative">
                    <input
                      type={showNewPassword ? "text" : "password"}
                      name="newPassword"
                      value={form.newPassword}
                      onChange={handleChange}
                      className="w-full px-4 py-3 pl-12 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6D76] focus:border-[#0B6D76] text-gray-700"
                      required
                      placeholder="Create a strong new password"
                    />
                    <Key size={20} className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
                    <button
                      type="button"
                      onClick={() => setShowNewPassword(!showNewPassword)}
                      className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showNewPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                    </button>
                  </div>
                </div>

                {/* Confirm Password */}
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <CheckCircle size={16} className="text-gray-400" />
                    Confirm New Password
                  </label>
                  <div className="relative">
                    <input
                      type={showConfirmPassword ? "text" : "password"}
                      name="confirmPassword"
                      value={form.confirmPassword}
                      onChange={handleChange}
                      className={`w-full px-4 py-3 pl-12 bg-gray-50 border rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0B6D76] focus:border-[#0B6D76] text-gray-700 ${
                        form.confirmPassword && form.newPassword !== form.confirmPassword 
                          ? 'border-red-300' 
                          : 'border-gray-300'
                      }`}
                      required
                      placeholder="Re-enter your new password"
                    />
                    <CheckCircle 
                      size={20} 
                      className={`absolute left-4 top-1/2 transform -translate-y-1/2 ${
                        form.confirmPassword && form.newPassword === form.confirmPassword 
                          ? 'text-green-500' 
                          : 'text-gray-400'
                      }`} 
                    />
                    <button
                      type="button"
                      onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                      className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showConfirmPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                    </button>
                  </div>
                  {form.confirmPassword && form.newPassword !== form.confirmPassword && (
                    <p className="text-sm text-red-600 flex items-center gap-1">
                      <AlertCircle size={14} />
                      Passwords do not match
                    </p>
                  )}
                </div>

                {/* Submit Button */}
                <button
                  type="submit"
                  disabled={isLoading}
                  className="w-full bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white font-bold py-3.5 rounded-xl hover:shadow-xl transition-all hover:scale-[1.02] disabled:opacity-70 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {isLoading ? (
                    <>
                      <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      Updating Password...
                    </>
                  ) : (
                    <>
                      <Lock size={20} />
                      Update Password
                    </>
                  )}
                </button>

                {/* Additional Info */}
                <div className="text-center">
                  <p className="text-sm text-gray-500">
                    After changing your password, you'll be logged out of all other devices.
                  </p>
                </div>
              </form>
            </div>

            {/* Security Notice */}
            <div className="mt-6 bg-gradient-to-r from-amber-50 to-orange-50 rounded-2xl p-5 border border-amber-200">
              <div className="flex items-start gap-3">
                <AlertCircle size={24} className="text-amber-600 mt-0.5" />
                <div>
                  <h4 className="font-bold text-amber-800 mb-1">Security Notice</h4>
                  <p className="text-amber-700 text-sm">
                    For your security, we recommend using a unique password that you don't use on other websites. 
                    Changing your password will log you out of all other devices.
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ConsultantPassword;