'use client';

import { useState } from 'react';
import Link from 'next/link';
import { Mail, ArrowLeft, CheckCircle, AlertCircle } from 'lucide-react';
import AppLogo from '@client/components/ui/AppLogo';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePublicBranding } from '@client/hooks/usePublicBranding';

export default function ForgotPasswordPage() {
  const { t } = useLanguage();
  const { logoUrl, siteTitle } = usePublicBranding();
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);
  const [resetLink, setResetLink] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email.trim()) { setError(t('auth.emailRequired', 'Email address is required')); return; }
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/auth/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json() as { error?: string; resetLink?: string };
      if (!res.ok) throw new Error(data.error || t('forgotPassword.failedToProcess', 'Failed to process request'));
      if (data.resetLink) setResetLink(data.resetLink);
      setSent(true);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '';
      setError(msg || t('forgotPassword.failedToSend', 'Failed to send reset link. Please try again.'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-6" style={{ backgroundColor: 'hsl(var(--background))' }}>
      <div className="w-full max-w-md">
        <div className="flex items-center gap-2 mb-10">
          <AppLogo src={logoUrl || undefined} size={28} />
          <span className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{siteTitle}</span>
        </div>

        {!sent ? (
          <>
            <div className="mb-8">
              <div className="w-12 h-12 rounded-2xl flex items-center justify-center mb-4" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
                <Mail size={22} style={{ color: 'hsl(var(--primary))' }} />
              </div>
              <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('forgotPassword.title', 'Reset your password')}</h2>
              <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('forgotPassword.subtitle', "Enter the email address associated with your account and we'll send you a reset link.")}
              </p>
            </div>

            {error && (
              <div className="flex items-center gap-2 p-3 rounded-xl mb-4 text-sm" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 90%)' }}>
                <AlertCircle size={15} />
                {error}
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('auth.emailAddress', 'Email Address')}</label>
                <div className="relative">
                  <Mail size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <input
                    type="email"
                    className="input-base pl-9"
                    placeholder={t('auth.emailPlaceholder', 'you@restaurant.com')}
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    required
                  />
                </div>
              </div>

              <button type="submit" disabled={loading} className="btn-primary w-full justify-center py-2.5">
                {loading ? (
                  <span className="flex items-center gap-2">
                    <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                    {t('forgotPassword.sendingDots', 'Sending...')}
                  </span>
                ) : t('forgotPassword.sendLink', 'Send Reset Link')}
              </button>
            </form>
          </>
        ) : (
          <div className="text-center">
            <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4" style={{ backgroundColor: 'hsl(var(--success-bg))' }}>
              <CheckCircle size={32} style={{ color: 'hsl(var(--success))' }} />
            </div>
            <h2 className="text-2xl font-bold mb-2" style={{ color: 'hsl(var(--foreground))' }}>{t('forgotPassword.sentTitle', 'Reset link ready')}</h2>
            {resetLink ? (
              <>
                <p className="text-sm mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('forgotPassword.clickBelow', 'Click the button below to reset your password. The link expires in 30 minutes.')}
                </p>
                <a href={resetLink} className="btn-primary w-full justify-center py-2.5 inline-flex">
                  {t('forgotPassword.resetNow', 'Reset Password Now')}
                </a>
              </>
            ) : (
              <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('forgotPassword.ifAccountExists', 'If an account exists with')} <strong>{email}</strong>{t('forgotPassword.linkGenerated', ', a reset link has been generated.')}
              </p>
            )}
            <p className="text-xs mt-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('forgotPassword.needNew', 'Need a new link?')}{' '}
              <button onClick={() => { setSent(false); setResetLink(''); }} className="font-semibold" style={{ color: 'hsl(var(--primary))' }}>
                {t('forgotPassword.tryAgain', 'Try again')}
              </button>
            </p>
          </div>
        )}

        <div className="mt-8">
          <Link href="/login" className="flex items-center gap-2 text-sm font-medium" style={{ color: 'hsl(var(--muted-foreground))' }}>
            <ArrowLeft size={15} /> {t('auth.backToSignIn', 'Back to sign in')}
          </Link>
        </div>
      </div>
    </div>
  );
}
