import { useState } from 'react';
import { createFileRoute, Link } from '@tanstack/react-router';
import { Loader2, CheckCircle2 } from 'lucide-react';
import { resetPassword } from '@/lib/wc.functions';
import PasswordStrength from '@/components/PasswordStrength';
import { useT, headLang, localizePath, SITE_URL } from '@/lib/i18n';

type Search = { key?: string; login?: string; id?: string };

export const Route = createFileRoute('/my-account_/lost-password')({
  validateSearch: (s: Record<string, unknown>): Search => ({
    key: typeof s.key === 'string' ? s.key : undefined,
    login: typeof s.login === 'string' ? s.login : undefined,
    id: s.id != null ? String(s.id) : undefined,
  }),
  head: (ctx) => {
    const lang = headLang(ctx);
    const title = lang === 'en' ? 'Set new password | Peptidewinkel' : 'Nieuw wachtwoord instellen | Peptidewinkel';
    const description = lang === 'en' ? 'Set a new password for your Peptidewinkel account.' : 'Stel een nieuw wachtwoord in voor je Peptidewinkel-account.';
    const url = `${SITE_URL}${localizePath('/my-account/lost-password', lang)}`;
    return {
      meta: [
        { title },
        { name: 'description', content: description },
        { property: 'og:title', content: title },
        { property: 'og:description', content: description },
        { property: 'og:type', content: 'website' },
        { property: 'og:url', content: url },
        { name: 'twitter:card', content: 'summary' },
        { name: 'robots', content: 'noindex, nofollow' },
      ],
    };
  },
  component: LostPasswordPage,
});

function LostPasswordPage() {
  const t = useT();
  const { key, login, id } = Route.useSearch();
  const [pw, setPw] = useState('');
  const [pw2, setPw2] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(false);
  const validLink = !!key && (!!login || !!id);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    if (pw.length < 8) return setError(t('Wachtwoord moet minimaal 8 tekens zijn.', 'Password must be at least 8 characters.'));
    if (pw !== pw2) return setError(t('Wachtwoorden komen niet overeen.', 'Passwords do not match.'));
    setBusy(true);
    try {
      const r = await resetPassword({ data: { key: key!, login, id, password: pw } });
      if ('error' in r && r.error) setError(r.error); else setDone(true);
    } catch { setError(t('Er ging iets mis. Probeer het opnieuw.', 'Something went wrong. Please try again.')); }
    finally { setBusy(false); }
  }

  return (
    <div className="container max-w-md mx-auto py-16 px-4">
      <div className="glass-card rounded-3xl p-6 space-y-4">
        <h1 className="text-2xl font-bold">{t('Nieuw wachtwoord instellen', 'Set new password')}</h1>
        {done ? (
          <div className="space-y-4">
            <p className="flex items-center gap-2 text-sm"><CheckCircle2 className="w-5 h-5 text-primary" /> {t('Je wachtwoord is gewijzigd.', 'Your password has been changed.')}</p>
            <Link to="/my-account" className="inline-block gradient-primary text-primary-foreground rounded-xl px-5 py-2.5 font-semibold">{t('Inloggen', 'Log in')}</Link>
          </div>
        ) : !validLink ? (
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">{t('Deze reset-link is ongeldig of onvolledig. Vraag een nieuwe link aan via "Wachtwoord vergeten".', 'This reset link is invalid or incomplete. Request a new link via "Forgot password".')}</p>
            <Link to="/my-account" className="text-primary font-semibold">{t('Naar inloggen', 'Go to log in')}</Link>
          </div>
        ) : (
          <form onSubmit={submit} className="space-y-3">
            <input type="password" autoComplete="new-password" placeholder={t('Nieuw wachtwoord', 'New password')} value={pw} onChange={(e) => setPw(e.target.value)}
              className="w-full rounded-xl border border-border bg-background px-4 py-2.5" />
            <PasswordStrength password={pw} />
            <input type="password" autoComplete="new-password" placeholder={t('Herhaal wachtwoord', 'Repeat password')} value={pw2} onChange={(e) => setPw2(e.target.value)}
              className="w-full rounded-xl border border-border bg-background px-4 py-2.5" />
            {error && <p className="text-sm text-destructive">{error}</p>}
            <button type="submit" disabled={busy} className="w-full gradient-primary text-primary-foreground rounded-xl py-2.5 font-semibold flex items-center justify-center gap-2 disabled:opacity-60">
              {busy && <Loader2 className="w-4 h-4 animate-spin" />} {t('Wachtwoord opslaan', 'Save password')}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}
