"use client";

import { useActionState, useEffect } from "react";
import { useFormStatus } from "react-dom";
import { Loader2, Save as SaveIcon } from "lucide-react";
import { toast } from "sonner";
import { saveSettingsAction } from "@/app/actions/admin-settings";
import type { AdminFormState } from "@/app/actions/admin-products";
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";

type Field = {
  key: string;
  label: string;
  kind?: "text" | "textarea" | "image" | "money";
  rows?: number;
  hint?: string;
};

type Group = { id: string; label: string; description: string; fields: Field[] };

const groups: Group[] = [
  {
    id: "identity",
    label: "Identité",
    description: "Le nom de la maison, ses signatures et le bandeau d'annonce.",
    fields: [
      { key: "brand.name", label: "Nom de la maison" },
      { key: "brand.tagline.fr", label: "Signature — Français" },
      { key: "brand.tagline.en", label: "Signature — English" },
      { key: "brand.tagline.ar", label: "Signature — العربية" },
      { key: "announcement.text.fr", label: "Bandeau d'annonce — Français", kind: "textarea", rows: 2 },
      { key: "announcement.text.en", label: "Bandeau d'annonce — English", kind: "textarea", rows: 2 },
      { key: "announcement.text.ar", label: "Bandeau d'annonce — العربية", kind: "textarea", rows: 2 },
      { key: "site.currency", label: "Devise affichée", hint: "Code ISO, ex. MAD" },
    ],
  },
  {
    id: "home",
    label: "Accueil",
    description: "Le hero et les textes d'ouverture de la page d'accueil.",
    fields: [
      { key: "hero.eyebrow.fr", label: "Sur-titre — Français" },
      { key: "hero.eyebrow.en", label: "Sur-titre — English" },
      { key: "hero.eyebrow.ar", label: "Sur-titre — العربية" },
      { key: "hero.title.fr", label: "Titre — Français" },
      { key: "hero.title.en", label: "Titre — English" },
      { key: "hero.title.ar", label: "Titre — العربية" },
      { key: "hero.description.fr", label: "Description — Français", kind: "textarea", rows: 3 },
      { key: "hero.description.en", label: "Description — English", kind: "textarea", rows: 3 },
      { key: "hero.description.ar", label: "Description — العربية", kind: "textarea", rows: 3 },
      { key: "hero.caption.fr", label: "Légende — Français" },
      { key: "hero.caption.en", label: "Légende — English" },
      { key: "hero.caption.ar", label: "Légende — العربية" },
      { key: "hero.image", label: "Image du hero", kind: "image" },
    ],
  },
  {
    id: "maison",
    label: "Maison",
    description: "Le récit de la maison, la collection Atlas et les images d'atelier.",
    fields: [
      { key: "story.eyebrow.fr", label: "Histoire — sur-titre FR" },
      { key: "story.eyebrow.en", label: "Histoire — sur-titre EN" },
      { key: "story.eyebrow.ar", label: "Histoire — sur-titre AR" },
      { key: "story.title.fr", label: "Histoire — titre FR" },
      { key: "story.title.en", label: "Histoire — titre EN" },
      { key: "story.title.ar", label: "Histoire — titre AR" },
      { key: "story.text1.fr", label: "Histoire — texte 1 FR", kind: "textarea", rows: 4 },
      { key: "story.text1.en", label: "Histoire — texte 1 EN", kind: "textarea", rows: 4 },
      { key: "story.text1.ar", label: "Histoire — texte 1 AR", kind: "textarea", rows: 4 },
      { key: "story.text2.fr", label: "Histoire — texte 2 FR", kind: "textarea", rows: 4 },
      { key: "story.text2.en", label: "Histoire — texte 2 EN", kind: "textarea", rows: 4 },
      { key: "story.text2.ar", label: "Histoire — texte 2 AR", kind: "textarea", rows: 4 },
      { key: "story.image", label: "Image de l'histoire", kind: "image" },
      { key: "story.stat.artisans", label: "Statistique — artisans" },
      { key: "story.stat.years", label: "Statistique — années" },
      { key: "story.stat.pieces", label: "Statistique — pièces" },
      { key: "collection.eyebrow.fr", label: "Collection — sur-titre FR" },
      { key: "collection.eyebrow.en", label: "Collection — sur-titre EN" },
      { key: "collection.eyebrow.ar", label: "Collection — sur-titre AR" },
      { key: "collection.title.fr", label: "Collection — titre FR" },
      { key: "collection.title.en", label: "Collection — titre EN" },
      { key: "collection.title.ar", label: "Collection — titre AR" },
      { key: "collection.description.fr", label: "Collection — description FR", kind: "textarea", rows: 3 },
      { key: "collection.description.en", label: "Collection — description EN", kind: "textarea", rows: 3 },
      { key: "collection.description.ar", label: "Collection — description AR", kind: "textarea", rows: 3 },
      { key: "collection.image", label: "Image de la collection", kind: "image" },
      { key: "collection.href", label: "Lien de la collection" },
      { key: "craft.image1", label: "Atelier — image 1", kind: "image" },
      { key: "craft.image2", label: "Atelier — image 2", kind: "image" },
      { key: "craft.image3", label: "Atelier — image 3", kind: "image" },
    ],
  },
  {
    id: "contact",
    label: "Contact",
    description: "Coordonnées du showroom, horaires et réseaux sociaux.",
    fields: [
      { key: "contact.phone", label: "Téléphone du showroom" },
      { key: "contact.email", label: "E-mail de contact" },
      { key: "contact.showroom.fr", label: "Adresse — Français", kind: "textarea", rows: 2 },
      { key: "contact.showroom.en", label: "Adresse — English", kind: "textarea", rows: 2 },
      { key: "contact.showroom.ar", label: "Adresse — العربية", kind: "textarea", rows: 2 },
      { key: "contact.hours.fr", label: "Horaires — Français" },
      { key: "contact.hours.en", label: "Horaires — English" },
      { key: "contact.hours.ar", label: "Horaires — العربية" },
      { key: "footer.description.fr", label: "Pied de page — description FR", kind: "textarea", rows: 3 },
      { key: "footer.description.en", label: "Pied de page — description EN", kind: "textarea", rows: 3 },
      { key: "footer.description.ar", label: "Pied de page — description AR", kind: "textarea", rows: 3 },
      { key: "footer.address", label: "Adresse du pied de page" },
      { key: "footer.phone", label: "Téléphone du pied de page" },
      { key: "footer.email", label: "E-mail du pied de page" },
      { key: "footer.hours.fr", label: "Horaires pied de page FR" },
      { key: "footer.hours.en", label: "Horaires pied de page EN" },
      { key: "footer.hours.ar", label: "Horaires pied de page AR" },
      { key: "social.instagram", label: "Instagram" },
      { key: "social.facebook", label: "Facebook" },
      { key: "social.pinterest", label: "Pinterest" },
      { key: "social.whatsapp", label: "WhatsApp" },
    ],
  },
  {
    id: "shipping",
    label: "Livraison",
    description: "Seuil de franco et tarifs appliqués au moment de la commande.",
    fields: [
      { key: "shipping.freeThreshold", label: "Franco de port à partir de (DH)", kind: "money" },
      { key: "shipping.morocco", label: "Maroc (DH)", kind: "money" },
      { key: "shipping.europe", label: "Europe (DH)", kind: "money" },
      { key: "shipping.world", label: "Reste du monde (DH)", kind: "money" },
      { key: "shipping.estimatedDays", label: "Délai estimé", hint: "Ex. 2-4" },
    ],
  },
  {
    id: "seo",
    label: "SEO",
    description: "Titres et descriptions qui apparaissent dans les moteurs de recherche.",
    fields: [
      { key: "seo.title.fr", label: "Titre — Français" },
      { key: "seo.title.en", label: "Titre — English" },
      { key: "seo.title.ar", label: "Titre — العربية" },
      { key: "seo.description.fr", label: "Description — Français", kind: "textarea", rows: 3 },
      { key: "seo.description.en", label: "Description — English", kind: "textarea", rows: 3 },
      { key: "seo.description.ar", label: "Description — العربية", kind: "textarea", rows: 3 },
    ],
  },
];

const initial: AdminFormState = { status: "idle" };

function SaveButton() {
  const { pending } = useFormStatus();
  return (
    <button
      type="submit"
      disabled={pending}
      className="flex h-10 items-center gap-2 bg-charcoal px-5 text-[12px] uppercase tracking-[0.14em] text-ivory hover:opacity-90 disabled:opacity-60"
    >
      {pending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <SaveIcon className="h-3.5 w-3.5" />}
      {pending ? "Enregistrement…" : "Enregistrer les réglages"}
    </button>
  );
}

export function SettingsForm({ values }: { values: Record<string, string> }) {
  const [state, action] = useActionState(saveSettingsAction, initial);

  useEffect(() => {
    if (state.status === "success") toast.success(state.message ?? "Réglages enregistrés.");
    if (state.status === "error" && state.message) toast.error(state.message);
  }, [state]);

  return (
    <form action={action} className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <p className="max-w-xl text-[13px] leading-relaxed text-pebble">
          Les modifications s'appliquent immédiatement à la boutique publique. Les images acceptent une URL locale
          (/images/…) ou Cloudinary.
        </p>
        <SaveButton />
      </div>

      {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>
      )}
      {state.status === "success" && (
        <p className="border border-olive/25 bg-olive/5 px-4 py-3 text-[14px] text-olive">
          {state.message}
        </p>
      )}

      <Tabs defaultValue="identity">
        <TabsList className="flex-wrap">
          {groups.map((group) => (
            <TabsTrigger key={group.id} value={group.id}>{group.label}</TabsTrigger>
          ))}
        </TabsList>

        {groups.map((group) => (
          <TabsContent key={group.id} value={group.id} forceMount>
            <section className="border border-line bg-cream p-4 md:p-6">
              <div className="mb-5 border-b border-line pb-4">
                <h2 className="font-serif text-2xl font-light">{group.label}</h2>
                <p className="mt-1 text-[13px] text-pebble">{group.description}</p>
              </div>

              <div className="grid gap-5 md:grid-cols-2">
                {group.fields.map((field) => {
                  const value = values[field.key] ?? "";
                  const wide = field.kind === "textarea" || field.kind === "image";
                  return (
                    <div key={field.key} className={wide ? "md:col-span-2" : undefined} dir={field.key.endsWith(".ar") ? "rtl" : undefined}>
                      <Label htmlFor={field.key} className="field-label">{field.label}</Label>
                      {field.kind === "textarea" ? (
                        <Textarea id={field.key} name={`setting.${field.key}`} defaultValue={value} rows={field.rows ?? 3} className={field.key.endsWith(".ar") ? "text-right" : undefined} />
                      ) : (
                        <Input
                          id={field.key}
                          name={`setting.${field.key}`}
                          defaultValue={field.kind === "money" ? String(Number(value) / 100) : value}
                          inputMode={field.kind === "money" ? "decimal" : undefined}
                          className={field.kind === "money" ? "h-10 rounded-none tabular-nums" : field.kind === "image" ? "h-10 rounded-none font-mono text-[13px]" : "h-10 rounded-none"}
                        />
                      )}
                      {field.hint && <p className="mt-1 text-[12px] text-pebble">{field.hint}</p>}
                      {field.kind === "image" && value && (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={value} alt="" className="mt-2 h-28 w-full max-w-sm object-cover" />
                      )}
                    </div>
                  );
                })}
              </div>
            </section>
          </TabsContent>
        ))}
      </Tabs>

      <div className="flex justify-end border-t border-line pt-4">
        <SaveButton />
      </div>
    </form>
  );
}