"use client";

import { Tag, BookOpen } from "lucide-react";
import { PoolManager } from "./PoolManager";
import { addTaxonomyValue, removeTaxonomyValue } from "@/app/admin/impostazioni/actions";

type FieldDef = { id: string; label: string };

const OFFER_FIELDS: FieldDef[] = [
  { id: "offer_categoria", label: "Categoria" },
  { id: "offer_ticket", label: "Ticket" },
  { id: "offer_tipo", label: "Tipo" },
  { id: "offer_obiettivo", label: "Obiettivo" },
];

const CATALOG_FIELDS: FieldDef[] = [
  { id: "service_fase", label: "Fase" },
  { id: "service_offerta", label: "Offerta" },
  { id: "service_pacchetto", label: "Pacchetto" },
];

function Section({
  icon,
  title,
  subtitle,
  fields,
  pools,
  gridClass,
}: {
  icon: React.ReactNode;
  title: string;
  subtitle: string;
  fields: FieldDef[];
  pools: Record<string, string[]>;
  gridClass: string;
}) {
  return (
    <section className="rounded-xl border border-border-light bg-card p-6 shadow-card">
      <div className="mb-6 flex items-start gap-3">
        <div className="grid h-9 w-9 shrink-0 place-items-center rounded-lg border border-border-light bg-muted text-muted-foreground">
          {icon}
        </div>
        <div>
          <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">{title}</h2>
          <p className="mt-0.5 text-xs text-tertiary">{subtitle}</p>
        </div>
      </div>

      <div className={`grid gap-6 border-t border-border-light pt-4 ${gridClass}`}>
        {fields.map((f) => (
          <PoolManager
            key={f.id}
            label={f.label}
            pool={pools[f.id] ?? []}
            onAdd={(v) => addTaxonomyValue(f.id, v)}
            onRemove={(v) => removeTaxonomyValue(f.id, v)}
          />
        ))}
      </div>
    </section>
  );
}

export function TaxonomyManager({ pools }: { pools: Record<string, string[]> }) {
  return (
    <div className="space-y-8">
      <Section
        icon={<Tag className="h-5 w-5" />}
        title="Tassonomie Offerte"
        subtitle="Valori dei campi Categoria, Ticket, Tipo e Obiettivo dell'editor offerte."
        fields={OFFER_FIELDS}
        pools={pools}
        gridClass="grid-cols-1 md:grid-cols-2"
      />
      <Section
        icon={<BookOpen className="h-5 w-5" />}
        title="Tassonomie Catalogo"
        subtitle="Valori dei campi Fase, Offerta e Pacchetto del catalogo servizi."
        fields={CATALOG_FIELDS}
        pools={pools}
        gridClass="grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
      />
      <p className="max-w-4xl px-2 text-xs leading-relaxed text-tertiary">
        I valori si sincronizzano ovunque: creandone uno dall&apos;editor offerte o dal catalogo
        comparirà qui automaticamente. Eliminando un valore da qui viene rimosso ovunque sia usato.
      </p>
    </div>
  );
}
