/**
 * Reset Password Page
 * Handles password reset with token from email link
 */

import { useState, useEffect } from 'react';
import { Link, useSearchParams, useNavigate } from 'react-router-dom';
import { fetchAPI } from '../../services/api';
import PageMeta from '../../components/common/PageMeta';
import { EyeIcon, EyeCloseIcon, ChevronLeftIcon, CheckCircleIcon, AlertIcon, LockIcon } from '../../icons';

type ResetState = 'form' | 'success' | 'error' | 'expired';

export default function ResetPassword() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const token = searchParams.get('token');

  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [resetState, setResetState] = useState<ResetState>('form');

  // Redirect to forgot-password if no token
  useEffect(() => {
    if (!token) {
      // No token - redirect to forgot password page
      navigate('/forgot-password', { replace: true });
    }
  }, [token, navigate]);

  // Password validation checks
  const passwordChecks = {
    length: password.length >= 8,
    uppercase: /[A-Z]/.test(password),
    lowercase: /[a-z]/.test(password),
    number: /[0-9]/.test(password),
  };

  const isPasswordStrong = Object.values(passwordChecks).every(Boolean);
  const passwordsMatch = password === confirmPassword && confirmPassword.length > 0;
  const isPasswordValid = isPasswordStrong && passwordsMatch;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!token) {
      setResetState('expired');
      return;
    }

    if (!isPasswordValid) {
      setError('Please ensure your password meets all requirements and both passwords match.');
      return;
    }

    setLoading(true);

    try {
      // Correct API endpoint for password reset confirmation
      await fetchAPI('/v1/auth/password-reset/confirm/', {
        method: 'POST',
        body: JSON.stringify({ 
          token, 
          new_password: password,
          new_password_confirm: confirmPassword 
        }),
      });
      setResetState('success');
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { message?: string; detail?: string; error?: string } } };
      const message = errorResponse?.response?.data?.message || 
                      errorResponse?.response?.data?.error ||
                      errorResponse?.response?.data?.detail || 
                      'Failed to reset password. Please try again.';
      
      if (message.toLowerCase().includes('expired') || message.toLowerCase().includes('invalid')) {
        setResetState('expired');
      } else {
        setError(message);
      }
    } finally {
      setLoading(false);
    }
  };

  // Expired/Invalid Token State
  if (resetState === 'expired') {
    return (
      <>
        <PageMeta
          title="Link Expired - IGNY8"
          description="Password reset link has expired"
        />
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 p-4">
          <div className="w-full max-w-md">
            <div className="text-center mb-8">
              <Link to="/">
                <img src="/images/logo/IGNY8_LIGHT_LOGO.png" alt="IGNY8" className="h-10 mx-auto dark:hidden" />
                <img src="/images/logo/IGNY8_DARK_LOGO.png" alt="IGNY8" className="h-10 mx-auto hidden dark:block" />
              </Link>
            </div>
            <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-8 text-center">
              <div className="w-16 h-16 bg-amber-100 dark:bg-amber-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
                <AlertIcon className="w-8 h-8 text-amber-600 dark:text-amber-400" />
              </div>
              <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
                Link Expired
              </h1>
              <p className="text-gray-600 dark:text-gray-300 mb-8">
                This password reset link has expired or is invalid. Please request a new one.
              </p>
              <Link
                to="/signin"
                className="inline-flex items-center justify-center w-full py-3 px-4 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-lg transition-colors"
              >
                Back to Sign In
              </Link>
              <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">
                Need help?{' '}
                <a href="mailto:support@igny8.com" className="text-brand-500 hover:underline">
                  Contact Support
                </a>
              </p>
            </div>
          </div>
        </div>
      </>
    );
  }

  // Success State
  if (resetState === 'success') {
    return (
      <>
        <PageMeta
          title="Password Reset Successful - IGNY8"
          description="Your password has been reset successfully"
        />
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 p-4">
          <div className="w-full max-w-md">
            <div className="text-center mb-8">
              <Link to="/">
                <img src="/images/logo/IGNY8_LIGHT_LOGO.png" alt="IGNY8" className="h-10 mx-auto dark:hidden" />
                <img src="/images/logo/IGNY8_DARK_LOGO.png" alt="IGNY8" className="h-10 mx-auto hidden dark:block" />
              </Link>
            </div>
            <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-8 text-center">
              <div className="w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
                <CheckCircleIcon className="w-8 h-8 text-green-600 dark:text-green-400" />
              </div>
              <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
                Password Reset!
              </h1>
              <p className="text-gray-600 dark:text-gray-300 mb-8">
                Your password has been successfully reset. You can now sign in with your new password.
              </p>
              <button
                onClick={() => navigate('/signin')}
                className="inline-flex items-center justify-center w-full py-3 px-4 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-lg transition-colors"
              >
                Sign In
              </button>
            </div>
          </div>
        </div>
      </>
    );
  }

  // Form State
  return (
    <>
      <PageMeta
        title="Reset Password - IGNY8"
        description="Create a new password for your IGNY8 account"
      />
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 p-4">
        <div className="w-full max-w-md">
          {/* Logo */}
          <div className="text-center mb-8">
            <Link to="/">
              <img src="/images/logo/IGNY8_LIGHT_LOGO.png" alt="IGNY8" className="h-10 mx-auto dark:hidden" />
              <img src="/images/logo/IGNY8_DARK_LOGO.png" alt="IGNY8" className="h-10 mx-auto hidden dark:block" />
            </Link>
          </div>

          {/* Form Card */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-8">
            <Link
              to="/signin"
              className="inline-flex items-center text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 mb-6"
            >
              <ChevronLeftIcon className="w-5 h-5" />
              Back to Sign In
            </Link>

            <div className="w-12 h-12 bg-brand-100 dark:bg-brand-900/30 rounded-full flex items-center justify-center mb-6">
              <LockIcon className="w-6 h-6 text-brand-600 dark:text-brand-400" />
            </div>

            <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
              Reset Your Password
            </h1>
            <p className="text-gray-600 dark:text-gray-300 mb-6">
              Create a strong password for your account.
            </p>

            {error && (
              <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-start gap-3">
                <AlertIcon className="w-5 h-5 text-red-500 dark:text-red-400 flex-shrink-0 mt-0.5" />
                <p className="text-red-600 dark:text-red-400 text-sm">{error}</p>
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-5">
              {/* Password Field */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  New Password
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full px-4 py-3 pr-12 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-colors"
                    placeholder="Enter new password"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 transition-colors"
                  >
                    {showPassword ? <EyeCloseIcon className="w-5 h-5" /> : <EyeIcon className="w-5 h-5" />}
                  </button>
                </div>
                
                {/* Password Requirements - Always visible for clarity */}
                <div className="mt-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg space-y-2">
                  <p className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">Password Requirements:</p>
                  {[
                    { check: passwordChecks.length, label: 'At least 8 characters' },
                    { check: passwordChecks.uppercase, label: 'One uppercase letter' },
                    { check: passwordChecks.lowercase, label: 'One lowercase letter' },
                    { check: passwordChecks.number, label: 'One number' },
                  ].map((req, i) => (
                    <div 
                      key={i} 
                      className={`text-sm flex items-center gap-2 transition-colors ${
                        password.length === 0 
                          ? 'text-gray-400 dark:text-gray-500' 
                          : req.check 
                            ? 'text-green-600 dark:text-green-400' 
                            : 'text-red-500 dark:text-red-400'
                      }`}
                    >
                      <span className={`w-4 h-4 rounded-full flex items-center justify-center text-xs ${
                        password.length === 0
                          ? 'bg-gray-200 dark:bg-gray-600'
                          : req.check 
                            ? 'bg-green-100 dark:bg-green-900/50' 
                            : 'bg-red-100 dark:bg-red-900/50'
                      }`}>
                        {password.length === 0 ? '○' : req.check ? '✓' : '✕'}
                      </span>
                      {req.label}
                    </div>
                  ))}
                </div>
              </div>

              {/* Confirm Password Field */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Confirm Password
                </label>
                <div className="relative">
                  <input
                    type={showConfirmPassword ? 'text' : 'password'}
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    className={`w-full px-4 py-3 pr-12 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent transition-colors ${
                      confirmPassword.length === 0
                        ? 'border-gray-300 dark:border-gray-600'
                        : passwordsMatch
                          ? 'border-green-400 dark:border-green-500'
                          : 'border-red-400 dark:border-red-500'
                    }`}
                    placeholder="Confirm new password"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 transition-colors"
                  >
                    {showConfirmPassword ? <EyeCloseIcon className="w-5 h-5" /> : <EyeIcon className="w-5 h-5" />}
                  </button>
                </div>
                {confirmPassword.length > 0 && (
                  <p className={`mt-2 text-sm flex items-center gap-1.5 ${
                    passwordsMatch 
                      ? 'text-green-600 dark:text-green-400' 
                      : 'text-red-500 dark:text-red-400'
                  }`}>
                    <span className={`w-4 h-4 rounded-full flex items-center justify-center text-xs ${
                      passwordsMatch 
                        ? 'bg-green-100 dark:bg-green-900/50' 
                        : 'bg-red-100 dark:bg-red-900/50'
                    }`}>
                      {passwordsMatch ? '✓' : '✕'}
                    </span>
                    {passwordsMatch ? 'Passwords match' : 'Passwords do not match'}
                  </p>
                )}
              </div>

              {/* Submit Button */}
              <button
                type="submit"
                disabled={loading || !isPasswordValid}
                className="w-full py-3 px-4 bg-brand-500 hover:bg-brand-600 disabled:bg-brand-300 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"
              >
                {loading ? (
                  <span className="flex items-center justify-center gap-2">
                    <svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                    </svg>
                    Resetting Password...
                  </span>
                ) : (
                  'Reset Password'
                )}
              </button>
            </form>
          </div>
        </div>
      </div>
    </>
  );
}
