'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { BrandLogo } from '@/components/crm/BrandLogo';
import { resetPassword } from '@/features/auth/api.client';
import { passwordMatchState, validatePassword } from '@/features/auth/password';
import { PasswordField } from '@/features/auth/ui/PasswordField';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

export function ResetPasswordView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  // Read once from the URL, then strip it from history so a failed reset does not leave the token.
  const [token] = useState(() => (searchParams.get('token') ?? '').trim());
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (!token) return;
    const url = new URL(window.location.href);
    if (!url.searchParams.has('token')) return;
    url.searchParams.delete('token');
    const next = `${url.pathname}${url.search}${url.hash}`;
    window.history.replaceState(window.history.state, '', next || url.pathname);
  }, [token]);

  const rules = useMemo(() => validatePassword(password), [password]);
  const match = passwordMatchState(password, confirm);
  const canSubmit = Boolean(token) && rules.ok && password === confirm && !submitting;

  const onSubmit = useCallback(
    async (event: React.FormEvent) => {
      event.preventDefault();
      setError(null);
      if (!token) {
        setError('This reset link is invalid or incomplete. Request a new one.');
        return;
      }
      if (!rules.ok) {
        setError('Use at least 8 characters with a letter, a number and a special character.');
        return;
      }
      if (password !== confirm) {
        setError('Passwords do not match.');
        return;
      }
      setSubmitting(true);
      try {
        await resetPassword(token, password);
        // Session cookie is set by the API — go straight into the CRM.
        router.replace('/');
        router.refresh();
      } catch (err) {
        if (isApiError(err) && err.code === 'RATE_LIMITED') {
          setError('Too many attempts. Wait a minute and try again.');
        } else {
          setError(errorText(err));
        }
        setSubmitting(false);
      }
    },
    [token, password, confirm, rules.ok, router],
  );

  return (
    <div className="forgot">
      <Link className="brand forgot__brand" href="/login">
        <BrandLogo variant="auto" />
      </Link>

      <div className="forgot__card">
        <h1 className="auth-form__title">Choose a new password</h1>
        <p className="auth-form__sub">
          {token
            ? 'Pick a strong password you have not used elsewhere. You will be signed in after saving.'
            : 'This reset link is missing a token. Open the link from your email, or request a new one.'}
        </p>
        {error ? <Alert tone="danger">{error}</Alert> : null}
        {!token ? (
          <p className="forgot__back">
            <Link className="link" href="/forgot-password">
              Request a new reset link
            </Link>
          </p>
        ) : (
          <form onSubmit={onSubmit} noValidate>
            <div style={{ display: 'grid', gap: 14 }}>
              <PasswordField
                id="reset-password"
                label="New password"
                value={password}
                autoComplete="new-password"
                disabled={submitting}
                onChange={setPassword}
              />
              <p className="signup__rules" aria-live="polite">
                <span className={rules.minLength ? 'is-ok' : undefined}>8+ characters</span>
                <span className="signup__rules-sep" aria-hidden>
                  ·
                </span>
                <span className={rules.hasLetter ? 'is-ok' : undefined}>A letter</span>
                <span className="signup__rules-sep" aria-hidden>
                  ·
                </span>
                <span className={rules.hasNumber ? 'is-ok' : undefined}>A number</span>
                <span className="signup__rules-sep" aria-hidden>
                  ·
                </span>
                <span className={rules.hasSpecial ? 'is-ok' : undefined}>A special character</span>
              </p>
              <PasswordField
                id="reset-confirm"
                label="Confirm password"
                value={confirm}
                autoComplete="new-password"
                disabled={submitting}
                onChange={setConfirm}
              />
              {match === 'matching' ? (
                <p className="signup__match signup__match--ok">Passwords match</p>
              ) : null}
              {match === 'mismatch' ? (
                <p className="signup__match signup__match--bad">Passwords do not match</p>
              ) : null}
              <button
                type="submit"
                className={cn(
                  'btn-crm btn-crm--primary btn-crm--block btn-crm--lg',
                  submitting && 'is-loading',
                )}
                aria-busy={submitting}
                disabled={!canSubmit}
              >
                {submitting ? 'Signing you in…' : 'Save password & sign in'}
              </button>
            </div>
          </form>
        )}
        <p className="forgot__back">
          <Link className="link" href="/login">
            Back to sign in
          </Link>
        </p>
      </div>
    </div>
  );
}
