'use client';

import { useState, Suspense } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { Eye, EyeOff, Lock, CheckCircle, Check, X, AlertCircle } from 'lucide-react';
import AppLogo from '@client/components/ui/AppLogo';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePublicBranding } from '@client/hooks/usePublicBranding';

function ResetPasswordForm() {
  const { t } = useLanguage();
  const searchParams = useSearchParams();
  const token = searchParams.get('token') || '';
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState('');

  const rules = [
    { label: t('auth.rule.minChars', 'At least 8 characters'), pass: password.length >= 8 },
    { label: t('auth.rule.uppercase', 'One uppercase letter'), pass: /[A-Z]/.test(password) },
    { label: t('auth.rule.number', 'One number'), pass: /[0-9]/.test(password) },
  ];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirm) return;
    if (!token) {
      setError(t('resetPassword.noToken', 'Reset token is missing. Please use the link from your email.'));
      return;
    }
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password }),
      });
      const data = await res.json() as { error?: string };
      if (!res.ok) throw new Error(data.error || t('resetPassword.failedToUpdate', 'Failed to update password'));
      setDone(true);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '';
      setError(msg || t('resetPassword.failedToUpdateTryAgain', 'Failed to update password. Please try again.'));
    } finally {
      setLoading(false);
    }
  };

  if (!done) {
    return (
      <>
        <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))' }}>
            <Lock size={22} style={{ color: 'hsl(var(--primary))' }} />
          </div>
          <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('resetPassword.title', 'Set new password')}</h2>
          <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('resetPassword.subtitle', 'Choose a strong password for your account.')}</p>
        </div>

        {!token && (
          <div className="flex items-center gap-2 p-3 rounded-xl mb-4 text-sm" style={{ backgroundColor: 'hsl(38, 92%, 96%)', color: 'hsl(38, 92%, 30%)', border: '1px solid hsl(38, 92%, 82%)' }}>
            <AlertCircle size={15} />
            {t('resetPassword.noTokenWarning', 'No reset token found. Please use the link from your password reset email.')}
          </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('resetPassword.newPassword', 'New Password')}</label>
            <div className="relative">
              <Lock size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <input
                type={showPassword ? 'text' : 'password'}
                className="input-base pl-9 pr-10"
                placeholder="••••••••"
                value={password}
                onChange={e => setPassword(e.target.value)}
                required
              />
              <button type="button" className="absolute right-3 top-1/2 -translate-y-1/2" onClick={() => setShowPassword(!showPassword)} style={{ color: 'hsl(var(--muted-foreground))' }}>
                {showPassword ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            </div>
            {password && (
              <div className="mt-2 space-y-1">
                {rules.map(r => (
                  <div key={r.label} className="flex items-center gap-2 text-xs">
                    {r.pass ? <Check size={12} style={{ color: 'hsl(var(--success))' }} /> : <X size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                    <span style={{ color: r.pass ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>{r.label}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('resetPassword.confirmPassword', 'Confirm Password')}</label>
            <div className="relative">
              <Lock size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <input
                type={showConfirm ? 'text' : 'password'}
                className="input-base pl-9 pr-10"
                placeholder="••••••••"
                value={confirm}
                onChange={e => setConfirm(e.target.value)}
                required
              />
              <button type="button" className="absolute right-3 top-1/2 -translate-y-1/2" onClick={() => setShowConfirm(!showConfirm)} style={{ color: 'hsl(var(--muted-foreground))' }}>
                {showConfirm ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            </div>
            {confirm && password !== confirm && (
              <p className="text-xs mt-1" style={{ color: 'hsl(var(--danger))' }}>{t('resetPassword.noMatch', 'Passwords do not match')}</p>
            )}
          </div>

          <button
            type="submit"
            disabled={loading || password !== confirm || !rules.every(r => r.pass) || !token}
            className="btn-primary w-full justify-center py-2.5 disabled:opacity-50"
          >
            {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('resetPassword.updatingDots', 'Updating...')}
              </span>
            ) : t('resetPassword.updatePassword', 'Update Password')}
          </button>
        </form>
      </>
    );
  }

  return (
    <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('resetPassword.successTitle', 'Password updated!')}</h2>
      <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('resetPassword.successDesc', 'Your password has been changed successfully.')}</p>
      <Link href="/login" className="btn-primary justify-center">{t('auth.signInNow', 'Sign in now')}</Link>
    </div>
  );
}

export default function ResetPasswordPage() {
  const { t } = useLanguage();
  const { logoUrl, siteTitle } = usePublicBranding();
  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>
        <Suspense fallback={<div className="text-center py-8" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.loadingDots', 'Loading…')}</div>}>
          <ResetPasswordForm />
        </Suspense>
      </div>
    </div>
  );
}
