"use client";

import { useActionState } from "react";
import { useFormStatus } from "react-dom";
import Link from "next/link";
import { Loader2 } from "lucide-react";
import { saveJournalAction } from "@/app/actions/admin-journal";
import type { AdminFormState } from "@/app/actions/admin-products";
import type { Locale } from "@/lib/i18n/config";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";

export type JournalFormValues = {
  id?: string;
  slug: string;
  image: string;
  author: string;
  isPublished: boolean;
  publishedAt: string;
  translations: Record<Locale, { title: string; excerpt: string; content: string }>;
};

const initial: AdminFormState = { status: "idle" };
const labels: Record<Locale, string> = { fr: "Français", en: "English", ar: "العربية" };

function Submit() {
  const { pending } = useFormStatus();
  return (
    <Button type="submit" disabled={pending} className="w-full">
      {pending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
      {pending ? "Enregistrement…" : "Enregistrer l'article"}
    </Button>
  );
}

export function JournalForm({ initialValues }: { initialValues: JournalFormValues }) {
  const [state, action] = useActionState(saveJournalAction, initial);
  const isEdit = Boolean(initialValues.id);

  return (
    <form action={action} className="grid gap-4 xl:grid-cols-[1fr_300px]">
      <input type="hidden" name="id" value={initialValues.id ?? ""} />

      <div className="space-y-4">
        {state.status === "error" && state.message && (
          <p className="border border-terracotta/25 bg-terracotta/5 px-4 py-3 text-[14px] text-terracotta">
            {state.message}
          </p>
        )}

        <section className="border border-line bg-cream p-4 md:p-5">
          <h2 className="font-serif text-xl font-light">Article</h2>
          <p className="mt-1 text-[13px] text-pebble">
            Séparez les paragraphes par une ligne vide. Le premier paragraphe reçoit une lettrine.
          </p>
          <div className="mt-4">
            <Tabs defaultValue="fr">
              <TabsList>
                {(["fr", "en", "ar"] as Locale[]).map((locale) => (
                  <TabsTrigger key={locale} value={locale}>{labels[locale]}</TabsTrigger>
                ))}
              </TabsList>
              {(["fr", "en", "ar"] as Locale[]).map((locale) => (
                <TabsContent key={locale} value={locale} forceMount className="space-y-4">
                  {locale !== "fr" && (
                    <p className="border border-line bg-cream/50 px-3 py-2 text-[13px] text-pebble">
                      Laissez vide pour reprendre automatiquement le contenu français.
                    </p>
                  )}
                  <div>
                    <Label htmlFor={`title.${locale}`} className="field-label">Titre *</Label>
                    <Input id={`title.${locale}`} name={`title.${locale}`} defaultValue={initialValues.translations[locale].title} className="h-10" />
                  </div>
                  <div>
                    <Label htmlFor={`excerpt.${locale}`} className="field-label">Chapeau *</Label>
                    <Textarea id={`excerpt.${locale}`} name={`excerpt.${locale}`} defaultValue={initialValues.translations[locale].excerpt} rows={2} />
                  </div>
                  <div>
                    <Label htmlFor={`content.${locale}`} className="field-label">Contenu *</Label>
                    <Textarea id={`content.${locale}`} name={`content.${locale}`} defaultValue={initialValues.translations[locale].content} rows={18} className="font-serif text-[15px] leading-relaxed" />
                  </div>
                </TabsContent>
              ))}
            </Tabs>
          </div>
        </section>
      </div>

      <aside className="space-y-4">
        <section className="border border-line bg-cream p-4">
          <h2 className="font-serif text-lg font-light">Publication</h2>
          <div className="mt-3 space-y-3">
            <label className="flex items-start gap-2.5 text-[14px] text-walnut">
              <input type="checkbox" name="isPublished" defaultChecked={initialValues.isPublished} className="mt-0.5 h-3.5 w-3.5 accent-charcoal" />
              <span>
                Article publié
                <span className="mt-0.5 block text-[12px] text-pebble">Décochez pour le garder en brouillon.</span>
              </span>
            </label>
            <div>
              <Label htmlFor="publishedAt" className="field-label">Date de publication</Label>
              <Input id="publishedAt" name="publishedAt" type="date" defaultValue={initialValues.publishedAt} className="h-10 rounded-none text-[14px]" />
            </div>
          </div>
        </section>

        <section className="border border-line bg-cream p-4">
          <h2 className="font-serif text-lg font-light">Métadonnées</h2>
          <div className="mt-3 space-y-3">
            <div>
              <Label htmlFor="author" className="field-label">Auteur *</Label>
              <Input id="author" name="author" defaultValue={initialValues.author} placeholder="Maison Dar Zellige" className="h-10" />
            </div>
            <div>
              <Label htmlFor="slug" className="field-label">Slug</Label>
              <Input id="slug" name="slug" defaultValue={initialValues.slug} placeholder="le-geste-du-tissage" className="h-10 rounded-none font-mono text-[13px]" />
            </div>
            <div>
              <Label htmlFor="image" className="field-label">Image de couverture *</Label>
              <Input id="image" name="image" defaultValue={initialValues.image} placeholder="/images/journal-01.jpg" className="h-10 rounded-none text-[13px]" />
              {initialValues.image && (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={initialValues.image} alt="" className="mt-2 aspect-[16/9] w-full object-cover" />
              )}
            </div>
          </div>
        </section>

        <div className="border border-line bg-cream p-4">
          <Submit />
          <Link href="/admin/content" className="mt-2 block text-center text-[12px] uppercase tracking-[0.12em] text-pebble hover:text-charcoal">
            Annuler
          </Link>
          {isEdit && (
            <Link href={`/fr/journal/${initialValues.slug}`} target="_blank" className="mt-3 block border-t border-line pt-3 text-center text-[12px] uppercase tracking-[0.12em] text-pebble hover:text-charcoal">
              Lire en boutique
            </Link>
          )}
        </div>
      </aside>
    </form>
  );
}