"use client";

import { useTransition, useState } from 'react';
import { useRouter } from 'next/navigation';
import { createBlogPost, updateBlogPost } from '@/app/actions/blog';
import { Loader2, ArrowLeft, Save } from 'lucide-react';
import Link from 'next/link';
import { toast } from 'react-hot-toast';
import RichTextEditor from './RichTextEditor';

interface Props {
  initialData?: {
    id: string;
    title: string;
    excerpt: string;
    content: string;
    author: string;
    imageUrl: string;
    slug?: string | null;
    tags?: string[];
    metaTitle?: string | null;
    metaDescription?: string | null;
  };
}

export default function BlogForm({ initialData }: Props) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [content, setContent] = useState(initialData?.content || '');

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    const data = {
      title: formData.get('title') as string,
      slug: formData.get('slug') as string,
      excerpt: formData.get('excerpt') as string,
      content: content,
      author: formData.get('author') as string,
      imageUrl: formData.get('imageUrl') as string,
      tags: (formData.get('tags') as string)?.split(',').map(t => t.trim()).filter(t => t !== ''),
      metaTitle: formData.get('metaTitle') as string,
      metaDescription: formData.get('metaDescription') as string,
    };

    startTransition(async () => {
      const result = initialData 
        ? await updateBlogPost(initialData.id, data)
        : await createBlogPost(data);

      if (result.success) {
        toast.success(initialData ? "Article mis à jour" : "Article publié avec succès");
        router.push('/blog');
        router.refresh();
      } else {
        toast.error(result.error || "Une erreur est survenue");
      }
    });
  };

  return (
    <div className="max-w-4xl mx-auto pb-20">
      <div className="mb-8 flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href="/blog" className="p-2 bg-slate-800 rounded-lg text-slate-400 hover:text-white transition-colors">
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <h1 className="text-3xl font-bold text-white">
            {initialData ? 'Modifier l\'article' : 'Nouvel Article'}
          </h1>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-8">
        <div className="card space-y-6">
          <h2 className="text-xl font-semibold text-white border-b border-slate-800 pb-4">Informations Générales</h2>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-sm font-medium text-slate-400">Titre</label>
              <input 
                name="title" 
                defaultValue={initialData?.title}
                required 
                className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-indigo-500"
                placeholder="Ex: L'essor de la Tech en Afrique"
              />
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium text-slate-400">Auteur</label>
              <input 
                name="author" 
                defaultValue={initialData?.author}
                required 
                className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-indigo-500"
                placeholder="Ex: Jean Dupont"
              />
            </div>
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-400">URL de l'image</label>
            <input 
              name="imageUrl" 
              defaultValue={initialData?.imageUrl}
              required 
              className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-indigo-500"
              placeholder="https://images.unsplash.com/..."
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-400">Extrait (Excerpt)</label>
            <textarea 
              name="excerpt" 
              defaultValue={initialData?.excerpt}
              required 
              rows={2}
              className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-indigo-500"
              placeholder="Un court résumé de l'article..."
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-400">Contenu de l'article</label>
            <RichTextEditor 
              value={content} 
              onChange={setContent} 
              placeholder="Rédigez votre article ici..."
            />
          </div>
        </div>

        {/* SEO SECTION */}
        <div className="card space-y-6">
          <h2 className="text-xl font-semibold text-white border-b border-slate-800 pb-4">Optimisation SEO</h2>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <label className="text-sm font-medium text-slate-400">Slug (URL personnalisée)</label>
              <input 
                name="slug" 
                defaultValue={initialData?.slug || ''}
                className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-indigo-500"
                placeholder="ex: lessor-de-la-tech-afrique"
              />
              <p className="text-xs text-slate-500 italic">Laissez vide pour générer automatiquement à partir du titre.</p>
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium text-slate-400">Mots-clés (tags, séparés par des virgules)</label>
              <input 
                name="tags" 
                defaultValue={initialData?.tags?.join(', ') || ''}
                className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-indigo-500"
                placeholder="tech, afrique, innovation"
              />
            </div>
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-400">Meta Titre (SEO)</label>
            <input 
              name="metaTitle" 
              defaultValue={initialData?.metaTitle || ''}
              className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-indigo-500"
              placeholder="Titre optimisé pour les moteurs de recherche"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-400">Meta Description (SEO)</label>
            <textarea 
              name="metaDescription" 
              defaultValue={initialData?.metaDescription || ''}
              rows={3}
              className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-indigo-500"
              placeholder="Description optimisée pour les moteurs de recherche (max 160 caractères)..."
            />
          </div>
        </div>

        <div className="pt-4">
          <button 
            type="submit" 
            disabled={isPending}
            className="w-full btn-verify flex items-center justify-center gap-2 py-4 text-lg"
          >
            {isPending ? (
              <Loader2 className="w-6 h-6 animate-spin" />
            ) : (
              <Save className="w-6 h-6" />
            )}
            {initialData ? 'Enregistrer les modifications' : 'Publier l\'article'}
          </button>
        </div>
      </form>
    </div>
  );
}
