'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  Button,
  Input,
} from '@/components/ui';

export default function NewSessionPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    const formData = new FormData(e.currentTarget);
    const title = formData.get('title') as string;
    const collaborator = formData.get('collaborator') as string;

    if (!title || !collaborator) {
      setError('Veuillez remplir tous les champs');
      setLoading(false);
      return;
    }

    try {
      const res = await fetch('/api/sessions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title, collaborator }),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || 'Une erreur est survenue');
        setLoading(false);
        return;
      }

      router.push(`/sessions/${data.id}`);
    } catch {
      setError('Une erreur est survenue');
      setLoading(false);
    }
  }

  return (
    <main className="mx-auto max-w-2xl px-4 py-8">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <span>✨</span>
            Nouvelle Session SWOT
          </CardTitle>
          <CardDescription>
            Créez une nouvelle session d&apos;atelier SWOT pour un collaborateur
          </CardDescription>
        </CardHeader>

        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-6">
            {error && (
              <div className="rounded-lg border border-destructive/20 bg-destructive/10 p-3 text-sm text-destructive">
                {error}
              </div>
            )}

            <Input
              label="Titre de la session"
              name="title"
              placeholder="Ex: Entretien annuel 2025"
              required
            />

            <Input
              label="Nom du collaborateur"
              name="collaborator"
              placeholder="Ex: Jean Dupont"
              required
            />

            <div className="flex gap-3 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.back()}
                disabled={loading}
              >
                Annuler
              </Button>
              <Button type="submit" loading={loading} className="flex-1">
                Créer la session
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </main>
  );
}
