'use client';

import { Suspense, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Train, ArrowLeft, ShieldCheck } from 'lucide-react';
import { iamAuthApi } from '@/lib/api/auth';
import { useAuthStore } from '@/lib/auth-store';

// Mirrors the IAM set-password requirement (class-validator @IsStrongPassword defaults):
// min length 8, with lower- and upper-case letters, a number, and a symbol.
function isStrongPassword(pw: string): boolean {
  return (
    pw.length >= 8 &&
    /[a-z]/.test(pw) &&
    /[A-Z]/.test(pw) &&
    /[0-9]/.test(pw) &&
    /[^A-Za-z0-9]/.test(pw)
  );
}

function VerifyAccountContent() {
  const searchParams = useSearchParams();
  const login = useAuthStore((s) => s.login);

  const email = searchParams.get('email') || '';
  const userId = searchParams.get('userId') || '';
  const phone = searchParams.get('phone') || '';
  const linkValid = Boolean(email && userId);

  const [verificationCode, setVerificationCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [resending, setResending] = useState(false);
  const [resent, setResent] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (!verificationCode.trim()) {
      setError('Enter the verification code sent to your phone.');
      return;
    }
    if (!isStrongPassword(newPassword)) {
      setError('Password must be at least 8 characters and include upper- and lower-case letters, a number, and a symbol.');
      return;
    }
    if (newPassword !== confirmPassword) {
      setError('Passwords do not match.');
      return;
    }
    setLoading(true);
    try {
      // Completes signup: PATCH /v1/auth/set-password with the SMS code, which activates
      // the account and sets the password.
      await iamAuthApi.resetPassword({
        userId,
        email,
        verificationCode: verificationCode.trim(),
        newPassword,
        confirmPassword,
      });
      // Auto-login with the freshly-set password; login lazy-provisions the passenger record.
      await login(email, newPassword);
      window.location.href = '/';
    } catch (err: any) {
      const msg = err.response?.data?.message || err.message || '';
      setError(msg || 'Could not verify your account. Check the code and try again, or resend it.');
      setLoading(false);
    }
  };

  const handleResend = async () => {
    setError('');
    setResent(false);
    setResending(true);
    try {
      await iamAuthApi.resendRegistrationCode({ email, phoneNumber: phone });
      setResent(true);
    } catch {
      setError('Could not resend the code. Please try again in a moment.');
    } finally {
      setResending(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-[rgb(20_113_76)] from-10% via-transparent to-[rgb(20_113_76)] to-90% dark:from-gray-900 dark:to-gray-800 flex items-center justify-center py-12 px-4">
      <div className="max-w-md w-full">
        <div className="text-center mb-8">
          <div className="flex justify-center mb-4">
            <div className="w-12 h-12 bg-[rgb(20_113_76)] rounded-lg flex items-center justify-center">
              <Train className="w-6 h-6 text-white" />
            </div>
          </div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">Verify your account</h1>
          {linkValid && (
            <p className="text-gray-600 dark:text-gray-400 mt-2">
              Enter the code we sent to your phone and choose a password for{' '}
              <span className="font-medium">{email}</span>.
            </p>
          )}
        </div>

        <div className="card">
          {!linkValid ? (
            <div className="space-y-4">
              <div className="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 px-4 py-3 rounded">
                This verification link is invalid or incomplete. Please start registration again.
              </div>
              <Link href="/register" className="btn-primary w-full flex items-center justify-center">
                Back to registration
              </Link>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-4">
              {error && (
                <div className="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 px-4 py-3 rounded">
                  {error}
                </div>
              )}
              {resent && !error && (
                <div className="flex items-start gap-3 bg-emerald-50 dark:bg-emerald-900/30 border border-emerald-200 dark:border-emerald-800 text-emerald-700 dark:text-emerald-300 px-4 py-3 rounded">
                  <ShieldCheck className="w-5 h-5 flex-shrink-0 mt-0.5" />
                  <p className="text-sm">A new code has been sent to your phone.</p>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Verification code</label>
                <input
                  type="text"
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  value={verificationCode}
                  onChange={(e) => { setVerificationCode(e.target.value); setError(''); }}
                  className="input-field tracking-widest"
                  placeholder="123456"
                  maxLength={6}
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">New password</label>
                <input
                  type="password"
                  value={newPassword}
                  onChange={(e) => { setNewPassword(e.target.value); setError(''); }}
                  className="input-field"
                  placeholder="••••••••"
                  autoComplete="new-password"
                  minLength={8}
                  required
                />
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  At least 8 characters with upper &amp; lower case, a number, and a symbol.
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Confirm password</label>
                <input
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => { setConfirmPassword(e.target.value); setError(''); }}
                  className="input-field"
                  placeholder="••••••••"
                  autoComplete="new-password"
                  minLength={8}
                  required
                />
              </div>

              <button
                type="submit"
                className="btn-primary w-full"
                disabled={loading || !verificationCode || !newPassword || !confirmPassword}
              >
                {loading ? 'Verifying...' : 'Verify and continue'}
              </button>

              <button
                type="button"
                onClick={handleResend}
                disabled={resending}
                className="w-full text-sm text-gray-600 dark:text-gray-400 hover:text-[rgb(20_113_76)] dark:hover:text-emerald-400 transition-colors disabled:opacity-50"
              >
                {resending ? 'Resending...' : "Didn't get a code? Resend"}
              </button>

              <Link
                href="/register"
                className="flex items-center justify-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-[rgb(20_113_76)] dark:hover:text-emerald-400 transition-colors"
              >
                <ArrowLeft className="w-4 h-4" />
                Back to registration
              </Link>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

export default function VerifyAccountPage() {
  return (
    <Suspense fallback={null}>
      <VerifyAccountContent />
    </Suspense>
  );
}
