'use client';

import { useState, useEffect } from 'react';
import { Card, Input, Button } from '@zen/core/shared/components';
import AuthPageHeader from '../components/AuthPageHeader.js';

export default function ForgotPasswordPage({ onSubmit, onNavigate, currentUser = null }) {
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [success, setSuccess] = useState('');
  const [email, setEmail] = useState('');
  const [honeypot, setHoneypot] = useState('');
  const [formLoadedAt, setFormLoadedAt] = useState(0);

  useEffect(() => {
    setFormLoadedAt(Date.now());
  }, []);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setSuccess('');
    setIsLoading(true);

    const submitData = new FormData();
    submitData.append('email', email);
    submitData.append('_hp', honeypot);
    submitData.append('_t', String(formLoadedAt));

    try {
      const result = await onSubmit(submitData);

      if (result.success) {
        setSuccess(result.message);
        setIsLoading(false);
      } else {
        setError(result.error || 'Échec de l\'envoi de l\'e-mail de réinitialisation');
        setIsLoading(false);
      }
    } catch (err) {
      console.error('Forgot password error:', err);
      setError('Une erreur inattendue s\'est produite');
      setIsLoading(false);
    }
  }

  return (
    <Card variant="default" padding="md" spacing="none" className="w-full max-w-md mx-auto">
      <AuthPageHeader title="Mot de passe oublié" description="Entrez votre adresse e-mail et nous vous enverrons un lien pour réinitialiser votre mot de passe." />

      {currentUser && (
        <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg dark:bg-blue-500/10 dark:border-blue-500/20">
          <div className="flex items-center space-x-2">
            <div className="w-1.5 h-1.5 bg-blue-500 rounded-full flex-shrink-0"></div>
            <span className="text-xs text-blue-700 dark:text-blue-400">
              Vous êtes connecté en tant que <span className="font-medium">{currentUser.name}</span>.{' '}
              <a href="/auth/logout" className="underline hover:text-blue-600 dark:hover:text-blue-300 transition-colors duration-200">
                Se déconnecter ?
              </a>
            </span>
          </div>
        </div>
      )}

      {error && !currentUser && !success && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg dark:bg-red-500/10 dark:border-red-500/20">
          <div className="flex items-center space-x-2">
            <div className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0"></div>
            <span className="text-xs text-red-700 dark:text-red-400">{error}</span>
          </div>
        </div>
      )}

      {success && !currentUser && (
        <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg dark:bg-green-500/10 dark:border-green-500/20">
          <div className="flex items-center space-x-2">
            <div className="w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"></div>
            <span className="text-xs text-green-700 dark:text-green-400">{success}</span>
          </div>
        </div>
      )}

      <form onSubmit={handleSubmit} className={`flex flex-col gap-4 transition-opacity duration-200 ${currentUser ? 'opacity-50 pointer-events-none' : ''}`}>
        <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', top: '-9999px', width: 0, height: 0, overflow: 'hidden' }}>
          <label htmlFor="_hp_forgot">Website</label>
          <input id="_hp_forgot" name="_hp" type="text" tabIndex={-1} autoComplete="off" value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
        </div>

        <Input
          id="email"
          name="email"
          type="email"
          label="Courriel"
          value={email}
          onChange={setEmail}
          placeholder="votre@courriel.com"
          disabled={!!success || !!currentUser}
          autoComplete="email"
          required
        />

        <Button
          type="submit"
          variant="primary"
          size="lg"
          loading={isLoading}
          disabled={!!success || !!currentUser}
          className="w-full mt-2"
        >
          Envoyer le lien de réinitialisation
        </Button>
      </form>

      <div className={`mt-6 flex justify-center transition-opacity duration-200 ${currentUser ? 'opacity-50 pointer-events-none' : ''}`}>
        <Button
          type="button"
          variant="fullghost"
          disabled={!!currentUser}
          onClick={() => { if (!currentUser) onNavigate('login'); }}
        >
          ← Retour à la connexion
        </Button>
      </div>
    </Card>
  );
}
