import { A, useNavigate, useSearchParams } from '@solidjs/router';
import { createMemo, createSignal, Show } from 'solid-js';
import PublicBackground from '~/components/PublicBackground';
import PublicHeader from '~/components/PublicHeader';
import { isValidEmail } from '~/lib/form-validation';

function PasswordVisibilityIcon(props: { visible: boolean }) {
  if (props.visible) {
    return (
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <path d="M3 3l18 18" />
        <path d="M10.58 10.58a2 2 0 0 0 2.83 2.83" />
        <path d="M9.88 5.09A11 11 0 0 1 12 4.9c5.5 0 10 4.1 10 7.1 0 1.2-.72 2.53-1.95 3.72" />
        <path d="M6.1 6.1C3.54 7.58 2 9.79 2 12c0 3 4.48 7.1 10 7.1 1.72 0 3.36-.4 4.84-1.12" />
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  );
}

export default function ForgotPasswordRoute() {
  const navigate = useNavigate();
  const [search] = useSearchParams();
  const [email, setEmail] = createSignal('');
  const [code, setCode] = createSignal(typeof search.code === 'string' ? search.code : '');
  const [newPassword, setNewPassword] = createSignal('');
  const [confirmPassword, setConfirmPassword] = createSignal('');
  const [showPassword, setShowPassword] = createSignal(false);
  const [showConfirm, setShowConfirm] = createSignal(false);
  const [error, setError] = createSignal('');
  const [success, setSuccess] = createSignal('');
  const [submitting, setSubmitting] = createSignal(false);
  const [step, setStep] = createSignal<'request' | 'reset'>('request');

  const passwordsMatch = createMemo(() => newPassword() === confirmPassword() && newPassword().length >= 8);

  const requestReset = async () => {
    setError('');
    setSuccess('');
    if (!isValidEmail(email())) {
      setError('Enter a valid email address.');
      return;
    }
    setSubmitting(true);
    try {
      const res = await fetch('/api/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email().trim().toLowerCase() }),
      });
      if (res.ok) {
        setSuccess('If an account exists with this email, a 6-digit reset code has been sent.');
        setStep('reset');
      } else {
        setError('Unable to process request. Please try again.');
      }
    } catch {
      setError('Network error. Please check your connection.');
    } finally {
      setSubmitting(false);
    }
  };

  const resetPassword = async () => {
    setError('');
    setSuccess('');
    if (!code().trim()) {
      setError('Enter the reset code from your email.');
      return;
    }
    if (newPassword().length < 8) {
      setError('Password must be at least 8 characters.');
      return;
    }
    if (!passwordsMatch()) {
      setError('Passwords do not match.');
      return;
    }
    setSubmitting(true);
    try {
      const res = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          code: code().trim(),
          new_password: newPassword(),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setSuccess('Password reset successfully. You can now login.');
        setTimeout(() => navigate('/login', { replace: true }), 2000);
      } else {
        setError(String(data?.message || data?.error || 'Reset failed. Code may be invalid or expired.'));
      }
    } catch {
      setError('Network error. Please check your connection.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <main class="auth-page">
      <PublicBackground />
      <PublicHeader />

      <div class="auth-layout">
        <section class="auth-visual card glass-dark">
          <img class="auth-visual-img" src="/images/auth-company-1.jpg" alt="Reset Password" />
          <div class="auth-visual-overlay" />
          <div class="auth-visual-content">
            <p class="eyebrow">Account Recovery</p>
            <h1 class="title light">Reset Your Password</h1>
            <p class="subtitle light">Securely reset your password with email verification.</p>
          </div>
        </section>

        <section class="auth-form card glass-light">
          <Show when={step() === 'request'} fallback={
            <>
              <h2 class="title">Set New Password</h2>
              <p class="subtitle">Enter the 6-digit code sent to your email and choose a new password.</p>

              <div class="field">
                <label class="label" for="reset-code">RESET CODE</label>
                <input
                  id="reset-code"
                  type="text"
                  inputmode="numeric"
                  maxlength="6"
                  class="input"
                  value={code()}
                  onInput={(e) => setCode(e.currentTarget.value.replace(/\D/g, '').slice(0, 6))}
                  placeholder="Enter 6-digit code"
                />
              </div>

              <div class="field">
                <label class="label" for="new-password">NEW PASSWORD</label>
                <div class="auth-password-wrap">
                  <input id="new-password" type={showPassword() ? 'text' : 'password'} class="input" value={newPassword()} onInput={(e) => setNewPassword(e.currentTarget.value)} placeholder="Enter new password" />
                  <button class="auth-toggle-visibility" type="button" onClick={() => setShowPassword((p) => !p)} aria-label={showPassword() ? 'Hide password' : 'Show password'}>
                    <PasswordVisibilityIcon visible={showPassword()} />
                  </button>
                </div>
                <p class="validation-note" style={{ color: newPassword().length >= 8 ? '#fd6116' : '#6e7591' }}>
                  {newPassword().length >= 8 ? '✓ Meets minimum length' : '• Minimum 8 characters required'}
                </p>
              </div>

              <div class="field">
                <label class="label" for="confirm-password">CONFIRM PASSWORD</label>
                <div class="auth-password-wrap">
                  <input id="confirm-password" type={showConfirm() ? 'text' : 'password'} class="input" value={confirmPassword()} onInput={(e) => setConfirmPassword(e.currentTarget.value)} placeholder="Confirm new password" />
                  <button class="auth-toggle-visibility" type="button" onClick={() => setShowConfirm((p) => !p)} aria-label={showConfirm() ? 'Hide password' : 'Show password'}>
                    <PasswordVisibilityIcon visible={showConfirm()} />
                  </button>
                </div>
                <p class="validation-note" style={{ color: passwordsMatch() ? '#fd6116' : '#6e7591' }}>
                  {confirmPassword() && passwordsMatch() ? '✓ Passwords match' : '• Passwords do not match'}
                </p>
              </div>

              <button class="auth-submit-btn" type="button" onClick={() => void resetPassword()} disabled={submitting()}>
                {submitting() ? 'Resetting...' : 'Reset Password'}
              </button>

              <div class="auth-footer-row">
                <p class="note">
                  Didn't get a code?{' '}
                  <button
                    type="button"
                    class="auth-forgot-link"
                    style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}
                    onClick={() => void requestReset()}
                    disabled={submitting()}
                  >
                    Resend code
                  </button>
                </p>
                <p class="note"><A href="/login">Back to Sign In</A></p>
              </div>
            </>
          }>
            <h2 class="title">Forgot Password</h2>
            <p class="subtitle">Enter your email to receive a 6-digit password reset code.</p>

            <div class="field">
              <label class="label" for="reset-email">EMAIL ADDRESS</label>
              <input id="reset-email" type="email" class="input" value={email()} onInput={(e) => setEmail(e.currentTarget.value)} placeholder="Enter your registered email" />
              <p class="validation-note" style={{ color: email().trim() && isValidEmail(email()) ? '#fd6116' : '#6e7591' }}>
                {email().trim() && isValidEmail(email()) ? '✓ Valid email format' : '• Enter a valid email format'}
              </p>
            </div>

            <button class="auth-submit-btn" type="button" onClick={() => void requestReset()} disabled={submitting()}>
              {submitting() ? 'Sending...' : 'Send Reset Code'}
            </button>

            <div class="auth-footer-row">
              <p class="note"><A href="/login">Back to Sign In</A></p>
            </div>
          </Show>

          <Show when={error()}>
            <p class="error">{error()}</p>
          </Show>
          <Show when={success()}>
            <p class="error" style={{ color: '#16A34A' }}>{success()}</p>
          </Show>
        </section>
      </div>
    </main>
  );
}
