'use client';

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

export default function LogoutPage({ onLogout, onSetSessionCookie }) {
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();

  const handleLogout = async () => {
    setError('');
    setSuccess('');
    setIsLoading(true);

    try {
      if (onLogout) {
        const result = await onLogout();
        if (result && !result.success) {
          setError(result.error || 'Échec de la déconnexion');
          setIsLoading(false);
          return;
        }
      }

      if (onSetSessionCookie) {
        await onSetSessionCookie('', { expires: new Date(0) });
      }

      setSuccess('Vous avez été déconnecté. Redirection...');
      setIsLoading(false);

      setTimeout(() => router.push('/'), 100);
    } catch (err) {
      console.error('Logout error:', err);
      setError('Une erreur inattendue s\'est produite lors de la déconnexion');
      setIsLoading(false);
    }
  };

  return (
    <Card variant="default" padding="md" spacing="none" className="w-full max-w-md mx-auto">
      <AuthPageHeader title="Prêt à vous déconnecter ?" description="Cela mettra fin à votre session et vous déconnectera de votre compte." />

      {success && (
        <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>
      )}

      {error && !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>
      )}

      <Button
        type="button"
        variant="danger"
        loading={isLoading}
        disabled={!!success}
        onClick={handleLogout}
        className="w-full mt-2"
      >
        Se déconnecter
      </Button>

      <div className="mt-6 text-center">
        <span className="text-sm text-neutral-600 dark:text-neutral-400">Vous avez changé d'avis ? </span>
        <a
          href="/"
          className="text-sm text-neutral-900 hover:text-neutral-600 font-medium transition-colors duration-200 dark:text-white dark:hover:text-neutral-300"
        >
          Retour
        </a>
      </div>
    </Card>
  );
}
