'use client';

import { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { validatePassword } from '@/lib/password-validation';

type PageState = 'loading' | 'invalid' | 'expired' | 'form' | 'success';

/**
 * Reset Password Content
 *
 * Client component that handles the password reset form.
 * Validates token on mount, shows form or error state.
 */
export default function ResetPasswordContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const token = searchParams.get('token');

  // Initialize state based on token presence to avoid synchronous setState in effect
  const [pageState, setPageState] = useState<PageState>(() => (token ? 'loading' : 'invalid'));
  const [maskedEmail, setMaskedEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  // Validate token on mount (only if token exists)
  useEffect(() => {
    if (!token) {
      return;
    }

    const validateToken = async () => {
      try {
        const response = await fetch(`/api/auth/reset-password?token=${encodeURIComponent(token)}`);
        const data = await response.json();

        if (data.valid) {
          setMaskedEmail(data.email);
          setPageState('form');
        } else if (data.error === 'token_expired') {
          setPageState('expired');
        } else {
          setPageState('invalid');
        }
      } catch {
        setPageState('invalid');
      }
    };

    validateToken();
  }, [token]);

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

    // Validate password
    const passwordValidation = validatePassword(password);
    if (!passwordValidation.valid) {
      setError(passwordValidation.error || 'Invalid password');
      return;
    }

    // Confirm password match
    if (password !== confirmPassword) {
      setError('Passwords do not match');
      return;
    }

    setIsLoading(true);

    try {
      const response = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password }),
      });

      const data = await response.json();

      if (!response.ok) {
        if (response.status === 410) {
          // Token expired
          setPageState('expired');
        } else if (response.status === 404) {
          // Invalid token
          setPageState('invalid');
        } else {
          setError(data.error || 'Failed to reset password. Please try again.');
        }
        setIsLoading(false);
        return;
      }

      // Success - show success state then redirect
      setPageState('success');
      setTimeout(() => {
        router.push('/dashboard');
      }, 2000);
    } catch {
      setError('An unexpected error occurred. Please try again.');
      setIsLoading(false);
    }
  };

  // Loading state
  if (pageState === 'loading') {
    return (
      <div className="space-y-6">
        <div
          className="w-20 h-20 mx-auto rounded-full flex items-center justify-center"
          style={{ backgroundColor: 'rgba(56, 189, 248, 0.1)' }}
        >
          <svg className="w-10 h-10 animate-spin" fill="none" stroke="#38bdf8" viewBox="0 0 24 24">
            <circle
              className="opacity-25"
              cx="12"
              cy="12"
              r="10"
              stroke="currentColor"
              strokeWidth="4"
            />
            <path
              className="opacity-75"
              fill="currentColor"
              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
            />
          </svg>
        </div>
        <p style={{ color: 'var(--reg-text-muted)' }}>Validating reset link...</p>
      </div>
    );
  }

  // Invalid token state
  if (pageState === 'invalid') {
    return (
      <div className="space-y-6">
        <div
          className="w-20 h-20 mx-auto rounded-full flex items-center justify-center"
          style={{ backgroundColor: 'rgba(239, 68, 68, 0.1)' }}
        >
          <svg className="w-10 h-10" fill="none" stroke="#ef4444" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </div>
        <h1 className="text-3xl font-bold" style={{ color: 'var(--reg-text-white)' }}>
          Invalid Link
        </h1>
        <p style={{ color: 'var(--reg-text-muted)' }}>
          This password reset link is invalid or has already been used. Please request a new one.
        </p>
        <Link
          href="/auth/forgot-password"
          className="inline-block w-full py-4 rounded-xl font-bold uppercase tracking-tight transition-all"
          style={{
            backgroundColor: 'var(--reg-accent-cyan)',
            color: 'var(--reg-bg-navy)',
          }}
        >
          Request New Link
        </Link>
      </div>
    );
  }

  // Expired token state
  if (pageState === 'expired') {
    return (
      <div className="space-y-6">
        <div
          className="w-20 h-20 mx-auto rounded-full flex items-center justify-center"
          style={{ backgroundColor: 'rgba(251, 191, 36, 0.1)' }}
        >
          <svg className="w-10 h-10" fill="none" stroke="#fbbf24" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
        </div>
        <h1 className="text-3xl font-bold" style={{ color: 'var(--reg-text-white)' }}>
          Link Expired
        </h1>
        <p style={{ color: 'var(--reg-text-muted)' }}>
          This password reset link has expired. Reset links are valid for 24 hours. Please request a
          new one.
        </p>
        <Link
          href="/auth/forgot-password"
          className="inline-block w-full py-4 rounded-xl font-bold uppercase tracking-tight transition-all"
          style={{
            backgroundColor: 'var(--reg-accent-cyan)',
            color: 'var(--reg-bg-navy)',
          }}
        >
          Request New Link
        </Link>
      </div>
    );
  }

  // Success state
  if (pageState === 'success') {
    return (
      <div className="space-y-6">
        <div
          className="w-20 h-20 mx-auto rounded-full flex items-center justify-center"
          style={{ backgroundColor: 'rgba(34, 197, 94, 0.1)' }}
        >
          <svg className="w-10 h-10" fill="none" stroke="#22c55e" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <h1 className="text-3xl font-bold" style={{ color: 'var(--reg-text-white)' }}>
          Password Reset!
        </h1>
        <p style={{ color: 'var(--reg-text-muted)' }}>
          Your password has been reset successfully. You are now signed in. Redirecting to your
          dashboard...
        </p>
      </div>
    );
  }

  // Form state
  return (
    <div className="space-y-6">
      {/* Icon */}
      <div
        className="w-20 h-20 mx-auto rounded-full flex items-center justify-center"
        style={{ backgroundColor: 'rgba(56, 189, 248, 0.1)' }}
      >
        <svg className="w-10 h-10" fill="none" stroke="#38bdf8" viewBox="0 0 24 24">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"
          />
        </svg>
      </div>

      <h1 className="text-3xl font-bold" style={{ color: 'var(--reg-text-white)' }}>
        Set New Password
      </h1>

      <p style={{ color: 'var(--reg-text-muted)' }}>
        Create a new password for{' '}
        <strong style={{ color: 'var(--reg-text-white)' }}>{maskedEmail}</strong>
      </p>

      <form onSubmit={handleSubmit} className="space-y-4 text-left">
        {/* Error Message */}
        {error && (
          <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
            <p className="text-red-400 text-sm">{error}</p>
          </div>
        )}

        {/* New Password Field */}
        <div className="space-y-1">
          <label
            htmlFor="new-password"
            className="block text-sm font-medium"
            style={{ color: 'var(--reg-text-white)' }}
          >
            New Password
          </label>
          <input
            id="new-password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full h-11 px-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-white/40 focus:ring-1 focus:ring-white/40 transition-colors"
            placeholder="Enter new password"
            disabled={isLoading}
            autoComplete="new-password"
            autoFocus
          />
          <p className="text-[11px]" style={{ color: 'var(--reg-text-muted)' }}>
            8+ chars with uppercase, lowercase, and number
          </p>
        </div>

        {/* Confirm Password Field */}
        <div className="space-y-1">
          <label
            htmlFor="confirm-new-password"
            className="block text-sm font-medium"
            style={{ color: 'var(--reg-text-white)' }}
          >
            Confirm New Password
          </label>
          <input
            id="confirm-new-password"
            type="password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            className="w-full h-11 px-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-white/40 focus:ring-1 focus:ring-white/40 transition-colors"
            placeholder="Confirm new password"
            disabled={isLoading}
            autoComplete="new-password"
          />
        </div>

        {/* Submit Button */}
        <button
          type="submit"
          disabled={isLoading}
          className="w-full py-4 rounded-xl font-bold uppercase tracking-tight transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          style={{
            backgroundColor: 'var(--reg-accent-cyan)',
            color: 'var(--reg-bg-navy)',
          }}
        >
          {isLoading ? 'Resetting Password...' : 'Reset Password'}
        </button>
      </form>
    </div>
  );
}
