"use client";

import { useActionState, useState } from "react";
import { useFormStatus } from "react-dom";
import Link from "next/link";
import { ArrowDown, ArrowUp, ImagePlus, Loader2, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { saveProductAction, type AdminFormState } from "@/app/actions/admin-products";
import { slugify } from "@/lib/utils";
import type { Locale } from "@/lib/i18n/config";
import { type ProductFormValues } from "@/lib/product-form";
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";

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

function SaveButton({ isEdit }: { isEdit: boolean }) {
  const { pending } = useFormStatus();
  return (
    <Button type="submit" disabled={pending} className="w-full">
      {pending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
      {pending ? "Enregistrement…" : isEdit ? "Enregistrer les modifications" : "Créer le produit"}
    </Button>
  );
}

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

export function ProductForm({
  initialValues,
  categories,
}: {
  initialValues: ProductFormValues;
  categories: { id: string; name: string }[];
}) {
  const [state, action] = useActionState(saveProductAction, initial);
  const [images, setImages] = useState(initialValues.images);
  const [variants, setVariants] = useState(initialValues.variants);
  const [slug, setSlug] = useState(initialValues.slug);
  const [uploading, setUploading] = useState(false);
  const isEdit = Boolean(initialValues.id);

  async function handleUpload(files: FileList | null) {
    if (!files || files.length === 0) return;
    setUploading(true);
    try {
      for (const file of Array.from(files)) {
        const body = new FormData();
        body.append("file", file);
        const response = await fetch("/api/admin/upload", { method: "POST", body });
        const data = (await response.json()) as { url?: string; provider?: string; error?: string };
        if (!response.ok || !data.url) {
          toast.error(data.error ?? "L'upload a échoué.");
          continue;
        }
        setImages((current) => [...current, { url: data.url as string, alt: "" }]);
        toast.success(data.provider === "cloudinary" ? "Image envoyée sur Cloudinary." : "Image enregistrée localement.");
      }
    } catch {
      toast.error("Impossible d'envoyer l'image.");
    } finally {
      setUploading(false);
    }
  }

  function moveImage(index: number, direction: -1 | 1) {
    setImages((current) => {
      const target = index + direction;
      if (target < 0 || target >= current.length) return current;
      const next = [...current];
      [next[index], next[target]] = [next[target], next[index]];
      return next;
    });
  }

  const payloadImages = JSON.stringify(images.filter((image) => image.url.trim()));
  const payloadVariants = JSON.stringify(
    variants
      .filter((variant) => variant.name.trim() && variant.sku.trim())
      .map((variant) => ({
        id: variant.id,
        sku: variant.sku.trim(),
        name: variant.name.trim(),
        priceDelta: Math.round((Number.parseFloat(variant.priceDelta.replace(",", ".")) || 0) * 100),
        stock: Number.parseInt(variant.stock, 10) || 0,
      })),
  );

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

      <div className="space-y-4">
        {state.status === "error" && state.message && (
          <div className="border border-terracotta/30 bg-terracotta/5 px-4 py-3">
            <p className="text-[14px] text-terracotta">{state.message}</p>
            {state.fieldErrors && (
              <ul className="mt-2 list-inside list-disc space-y-0.5 text-[13px] text-terracotta/75">
                {Array.from(new Set(Object.values(state.fieldErrors).flat())).slice(0, 5).map((message) => (
                  <li key={message}>{message}</li>
                ))}
              </ul>
            )}
          </div>
        )}

        <section className="border border-line bg-cream p-4 md:p-5">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="font-serif text-xl font-light">Contenu éditorial</h2>
            <p className="text-[12px] uppercase tracking-[0.12em] text-pebble">3 langues</p>
          </div>
          <Tabs defaultValue="fr">
            <TabsList>
              {(["fr", "en", "ar"] as Locale[]).map((locale) => (
                <TabsTrigger key={locale} value={locale}>
                  {localeLabels[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={`name.${locale}`} className="field-label">
                    Nom de la pièce *
                  </Label>
                  <Input
                    id={`name.${locale}`}
                    name={`name.${locale}`}
                    defaultValue={initialValues.translations[locale].name}
                    onBlur={(event) => {
                      if (locale === "fr" && !slug) setSlug(slugify(event.target.value));
                    }}
                    className="h-10"
                  />
                </div>
                <div>
                  <Label htmlFor={`shortDescription.${locale}`} className="field-label">
                    Description courte *
                  </Label>
                  <Textarea
                    id={`shortDescription.${locale}`}
                    name={`shortDescription.${locale}`}
                    defaultValue={initialValues.translations[locale].shortDescription}
                    rows={2}
                  />
                </div>
                <div>
                  <Label htmlFor={`description.${locale}`} className="field-label">
                    Description complète *
                  </Label>
                  <Textarea
                    id={`description.${locale}`}
                    name={`description.${locale}`}
                    defaultValue={initialValues.translations[locale].description}
                    rows={7}
                  />
                </div>
                <div className="grid gap-4 sm:grid-cols-3">
                  <div>
                    <Label htmlFor={`materials.${locale}`} className="field-label">Matières *</Label>
                    <Input id={`materials.${locale}`} name={`materials.${locale}`} defaultValue={initialValues.translations[locale].materials} className="h-10" />
                  </div>
                  <div>
                    <Label htmlFor={`dimensions.${locale}`} className="field-label">Dimensions *</Label>
                    <Input id={`dimensions.${locale}`} name={`dimensions.${locale}`} defaultValue={initialValues.translations[locale].dimensions} className="h-10" />
                  </div>
                  <div>
                    <Label htmlFor={`origin.${locale}`} className="field-label">Origine *</Label>
                    <Input id={`origin.${locale}`} name={`origin.${locale}`} defaultValue={initialValues.translations[locale].origin} className="h-10" />
                  </div>
                </div>
                <div className="grid gap-4 sm:grid-cols-2">
                  <div>
                    <Label htmlFor={`artisanName.${locale}`} className="field-label">Artisan *</Label>
                    <Input id={`artisanName.${locale}`} name={`artisanName.${locale}`} defaultValue={initialValues.translations[locale].artisanName} className="h-10" />
                  </div>
                  <div>
                    <Label htmlFor={`artisanBio.${locale}`} className="field-label">Biographie de l'artisan *</Label>
                    <Textarea id={`artisanBio.${locale}`} name={`artisanBio.${locale}`} defaultValue={initialValues.translations[locale].artisanBio} rows={3} />
                  </div>
                </div>
                <div>
                  <Label htmlFor={`care.${locale}`} className="field-label">Entretien *</Label>
                  <Textarea id={`care.${locale}`} name={`care.${locale}`} defaultValue={initialValues.translations[locale].care} rows={3} />
                </div>
              </TabsContent>
            ))}
          </Tabs>
        </section>

        <section className="border border-line bg-cream p-4 md:p-5">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div>
              <h2 className="font-serif text-xl font-light">Images</h2>
              <p className="mt-0.5 text-[13px] text-pebble">La première image sert de visuel principal.</p>
            </div>
            <div className="flex items-center gap-2">
              <label className="inline-flex h-9 cursor-pointer items-center gap-2 border border-line px-3 text-[12px] uppercase tracking-[0.12em] text-pebble hover:border-charcoal/40">
                {uploading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <ImagePlus className="h-3.5 w-3.5" />}
                {uploading ? "Envoi…" : "Téléverser"}
                <input
                  type="file"
                  accept="image/jpeg,image/png,image/webp,image/avif"
                  multiple
                  className="sr-only"
                  disabled={uploading}
                  onChange={(event) => {
                    void handleUpload(event.target.files);
                    event.target.value = "";
                  }}
                />
              </label>
              <button
                type="button"
                onClick={() => setImages((current) => [...current, { url: "", alt: "" }])}
                className="flex h-9 items-center gap-2 border border-line px-3 text-[12px] uppercase tracking-[0.12em] text-pebble hover:border-charcoal/40"
              >
                <Plus className="h-3.5 w-3.5" />
                URL
              </button>
            </div>
          </div>

          <div className="mt-4 space-y-3">
            {images.map((image, index) => (
              <div key={index} className="grid gap-2 border border-line p-2 sm:grid-cols-[48px_1fr_1fr_auto] sm:items-center">
                <div className="relative h-12 w-12 overflow-hidden bg-cream">
                  {image.url ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={image.url} alt="" className="h-full w-full object-cover" />
                  ) : (
                    <div className="flex h-full items-center justify-center text-[12px] text-pebble">—</div>
                  )}
                </div>
                <Input
                  value={image.url}
                  onChange={(event) =>
                    setImages((current) => current.map((item, i) => (i === index ? { ...item, url: event.target.value } : item)))
                  }
                  placeholder="/images/p-rug-01.jpg ou https://…"
                  className="h-9 rounded-none text-[14px]"
                />
                <Input
                  value={image.alt}
                  onChange={(event) =>
                    setImages((current) => current.map((item, i) => (i === index ? { ...item, alt: event.target.value } : item)))
                  }
                  placeholder="Texte alternatif"
                  className="h-9 rounded-none text-[14px]"
                />
                <div className="flex items-center gap-0.5">
                  <button type="button" onClick={() => moveImage(index, -1)} disabled={index === 0} className="p-1.5 text-pebble disabled:opacity-20" aria-label="Monter">
                    <ArrowUp className="h-3 w-3" />
                  </button>
                  <button type="button" onClick={() => moveImage(index, 1)} disabled={index === images.length - 1} className="p-1.5 text-pebble disabled:opacity-20" aria-label="Descendre">
                    <ArrowDown className="h-3 w-3" />
                  </button>
                  <button type="button" onClick={() => setImages((current) => current.filter((_, i) => i !== index))} className="p-1.5 text-terracotta/60 hover:text-terracotta" aria-label="Supprimer">
                    <Trash2 className="h-3 w-3" />
                  </button>
                </div>
              </div>
            ))}
            {images.length === 0 && (
              <p className="border border-dashed border-line px-4 py-8 text-center text-[14px] text-pebble">
                Aucune image. Téléversez un fichier (Cloudinary ou stockage local) ou collez une URL.
              </p>
            )}
          </div>
        </section>

        <section className="border border-line bg-cream p-4 md:p-5">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div>
              <h2 className="font-serif text-xl font-light">Variantes</h2>
              <p className="mt-0.5 text-[13px] text-pebble">Dimensions, finitions ou tailles. Prix en supplément (ou en moins).</p>
            </div>
            <button
              type="button"
              onClick={() =>
                setVariants((current) => [
                  ...current,
                  {
                    sku: `${slug.toUpperCase().slice(0, 12) || "VAR"}-${current.length + 1}`,
                    name: "",
                    priceDelta: "0",
                    stock: "0",
                  },
                ])
              }
              className="flex h-9 items-center gap-2 border border-line px-3 text-[12px] uppercase tracking-[0.12em] text-pebble hover:border-charcoal/40"
            >
              <Plus className="h-3.5 w-3.5" />
              Variante
            </button>
          </div>

          <div className="mt-4 space-y-2">
            {variants.map((variant, index) => (
              <div key={index} className="grid gap-2 border border-line p-2 sm:grid-cols-[1.3fr_1fr_1fr_90px_auto] sm:items-center">
                <Input
                  value={variant.name}
                  onChange={(event) => setVariants((current) => current.map((item, i) => (i === index ? { ...item, name: event.target.value } : item)))}
                  placeholder="Nom (ex. 200 × 300 cm)"
                  className="h-9 rounded-none text-[14px]"
                />
                <Input
                  value={variant.sku}
                  onChange={(event) => setVariants((current) => current.map((item, i) => (i === index ? { ...item, sku: event.target.value } : item)))}
                  placeholder="SKU"
                  className="h-9 rounded-none text-[14px]"
                />
                <Input
                  value={variant.priceDelta}
                  onChange={(event) => setVariants((current) => current.map((item, i) => (i === index ? { ...item, priceDelta: event.target.value } : item)))}
                  placeholder="+0 DH"
                  inputMode="decimal"
                  className="h-9 rounded-none text-[14px]"
                />
                <Input
                  value={variant.stock}
                  onChange={(event) => setVariants((current) => current.map((item, i) => (i === index ? { ...item, stock: event.target.value } : item)))}
                  placeholder="Stock"
                  inputMode="numeric"
                  className="h-9 rounded-none text-[14px]"
                />
                <div className="flex justify-end">
                  <button
                    type="button"
                    onClick={() => setVariants((current) => current.filter((_, i) => i !== index))}
                    className="p-1.5 text-terracotta/60 hover:text-terracotta"
                    aria-label="Supprimer la variante"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>
            ))}
            {variants.length === 0 && (
              <p className="text-[13px] text-pebble">Aucune variante : la pièce est vendue en taille unique.</p>
            )}
          </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>
                Visible en boutique
                <span className="mt-0.5 block text-[12px] text-pebble">Décochez pour enregistrer en brouillon.</span>
              </span>
            </label>
            <label className="flex items-start gap-2.5 text-[14px] text-walnut">
              <input type="checkbox" name="isFeatured" defaultChecked={initialValues.isFeatured} className="mt-0.5 h-3.5 w-3.5 accent-charcoal" />
              <span>
                Pièce mise en avant
                <span className="mt-0.5 block text-[12px] text-pebble">Apparaît dans la sélection de la maison.</span>
              </span>
            </label>
          </div>
        </section>

        <section className="border border-line bg-cream p-4">
          <h2 className="font-serif text-lg font-light">Organisation</h2>
          <div className="mt-3 space-y-3">
            <div>
              <Label htmlFor="categoryId" className="field-label">Catégorie *</Label>
              <select
                id="categoryId"
                name="categoryId"
                defaultValue={initialValues.categoryId}
                className="h-10 w-full border border-line bg-transparent px-2.5 text-[14px] focus:border-charcoal focus:outline-none"
                required
              >
                <option value="">Choisir…</option>
                {categories.map((category) => (
                  <option key={category.id} value={category.id}>{category.name}</option>
                ))}
              </select>
            </div>
            <div>
              <Label htmlFor="slug" className="field-label">Slug</Label>
              <Input
                id="slug"
                name="slug"
                value={slug}
                onChange={(event) => setSlug(event.target.value)}
                placeholder="tapis-atlas"
                className="h-10 rounded-none font-mono text-[13px]"
              />
            </div>
            <div>
              <Label htmlFor="sku" className="field-label">SKU *</Label>
              <Input id="sku" name="sku" defaultValue={initialValues.sku} placeholder="DZ-RUG-001" className="h-10 rounded-none font-mono text-[13px]" />
            </div>
          </div>
        </section>

        <section className="border border-line bg-cream p-4">
          <h2 className="font-serif text-lg font-light">Tarification</h2>
          <div className="mt-3 space-y-3">
            <div>
              <Label htmlFor="price" className="field-label">Prix de vente (DH) *</Label>
              <Input id="price" name="price" defaultValue={initialValues.price} inputMode="decimal" className="h-10 rounded-none tabular-nums" />
            </div>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <Label htmlFor="compareAtPrice" className="field-label">Prix barré</Label>
                <Input id="compareAtPrice" name="compareAtPrice" defaultValue={initialValues.compareAtPrice} inputMode="decimal" className="h-10 rounded-none tabular-nums" />
              </div>
              <div>
                <Label htmlFor="costPrice" className="field-label">Coût d'achat</Label>
                <Input id="costPrice" name="costPrice" defaultValue={initialValues.costPrice} inputMode="decimal" className="h-10 rounded-none tabular-nums" />
              </div>
            </div>
          </div>
        </section>

        <section className="border border-line bg-cream p-4">
          <h2 className="font-serif text-lg font-light">Stock</h2>
          <div className="mt-3 grid grid-cols-2 gap-2">
            <div>
              <Label htmlFor="stock" className="field-label">Quantité *</Label>
              <Input id="stock" name="stock" defaultValue={initialValues.stock} inputMode="numeric" className="h-10 rounded-none tabular-nums" />
            </div>
            <div>
              <Label htmlFor="lowStockThreshold" className="field-label">Seuil d'alerte</Label>
              <Input id="lowStockThreshold" name="lowStockThreshold" defaultValue={initialValues.lowStockThreshold} inputMode="numeric" className="h-10 rounded-none tabular-nums" />
            </div>
          </div>
          {isEdit && (
            <Link href="/admin/inventory" className="mt-3 inline-block text-[12px] uppercase tracking-[0.12em] text-pebble underline-offset-4 hover:underline">
              Historique des mouvements
            </Link>
          )}
        </section>

        <div className="border border-line bg-cream p-4">
          <SaveButton isEdit={isEdit} />
          <Link href="/admin/products" className="mt-2 block text-center text-[12px] uppercase tracking-[0.12em] text-pebble hover:text-charcoal">
            Annuler
          </Link>
        </div>
      </aside>
    </form>
  );
}