"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Input } from "@/components/ui/input";
import { EditableCell } from "@/components/ui/editable-cell";
import { OptionSelect } from "@/components/ui/option-select";
import { OptionMultiSelect } from "@/components/ui/option-multi-select";
import {
  updateServiceField,
  quickAddService,
  addServiceOption,
  removeServiceOption,
  renameServiceOption,
} from "@/app/admin/catalog/actions";
import type { ServiceWithTags, CatalogFieldOptions } from "@/lib/admin-queries";

function formatPrice(raw: string): string {
  const num = parseFloat(raw);
  return `€${(isNaN(num) ? 0 : num).toLocaleString("it-IT", { minimumFractionDigits: 2 })}`;
}

const COLUMN_HEADERS = [
  "Nome",
  "Descrizione",
  "Categoria",
  "Fase",
  "Tag",
  "Pacchetto",
  "Prezzo",
  "Stato",
];
const COL_COUNT = COLUMN_HEADERS.length;

function ServiceRow({
  service,
  options,
}: {
  service: ServiceWithTags;
  options: CatalogFieldOptions;
}) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function run(fn: () => Promise<unknown>) {
    setError(null);
    startTransition(async () => {
      try {
        await fn();
        router.refresh();
      } catch (e) {
        setError(e instanceof Error ? e.message : "Errore nel salvataggio");
      }
    });
  }

  return (
    <>
    <tr
      className={`border-b border-[#e5e7eb] hover:bg-[#f9f9f9] transition-colors duration-150 ${
        !service.active ? "opacity-50" : ""
      }`}
    >
      <td className="py-2 px-3 font-medium text-[#1a1a1a] min-w-[160px]">
        <EditableCell
          value={service.name}
          type="text"
          required
          onSave={(v) => run(() => updateServiceField(service.id, "name", v))}
        />
      </td>
      <td className="py-2 px-3 text-[#71717a] min-w-[200px]">
        <EditableCell
          value={service.description ?? ""}
          type="textarea"
          placeholder="Descrizione..."
          onSave={(v) => run(() => updateServiceField(service.id, "description", v))}
        />
      </td>
      <td className="py-2 px-3 min-w-[140px]">
        <OptionSelect
          value={service.category}
          options={options.categoria}
          onChange={(v) => run(() => updateServiceField(service.id, "category", v ?? ""))}
          onRename={(o, n) => run(() => renameServiceOption("categoria", o, n))}
        />
      </td>
      <td className="py-2 px-3 min-w-[140px]">
        <OptionSelect
          value={service.fase}
          options={options.fase}
          onChange={(v) => run(() => updateServiceField(service.id, "fase", v ?? ""))}
          onRename={(o, n) => run(() => renameServiceOption("fase", o, n))}
        />
      </td>
      <td className="py-2 px-3 min-w-[180px]">
        <OptionMultiSelect
          values={service.tags}
          options={options.tag}
          onAdd={(v) => run(() => addServiceOption("tag", service.id, v))}
          onRemove={(v) => run(() => removeServiceOption("tag", service.id, v))}
          onRename={(o, n) => run(() => renameServiceOption("tag", o, n))}
        />
      </td>
      <td className="py-2 px-3 min-w-[180px]">
        <OptionMultiSelect
          values={service.pacchetto}
          options={options.pacchetto}
          onAdd={(v) => run(() => addServiceOption("pacchetto", service.id, v))}
          onRemove={(v) => run(() => removeServiceOption("pacchetto", service.id, v))}
          onRename={(o, n) => run(() => renameServiceOption("pacchetto", o, n))}
        />
      </td>
      <td className="py-2 px-3 tabular-nums min-w-[100px]">
        <EditableCell
          value={service.unit_price}
          type="number"
          formatDisplay={formatPrice}
          onSave={(v) => run(() => updateServiceField(service.id, "unit_price", v))}
        />
      </td>
      <td className="py-2 px-3 min-w-[100px]">
        <EditableCell
          value={service.active ? "true" : "false"}
          type="toggle"
          onSave={(v) => run(() => updateServiceField(service.id, "active", v))}
        />
      </td>
    </tr>
    {error && (
      <tr>
        <td colSpan={COL_COUNT} className="py-1 px-3 text-xs text-red-600">
          {error}
        </td>
      </tr>
    )}
    </>
  );
}

function QuickAddRow({ options }: { options: CatalogFieldOptions }) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [category, setCategory] = useState("");
  const [fase, setFase] = useState("");
  const [price, setPrice] = useState("");
  const [, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  function submit() {
    const trimmed = name.trim();
    if (!trimmed) return;
    setError(null);
    startTransition(async () => {
      try {
        await quickAddService({
          name: trimmed,
          description: description || undefined,
          category: category || undefined,
          fase: fase || undefined,
          unit_price: price || undefined,
        });
        setName("");
        setDescription("");
        setCategory("");
        setFase("");
        setPrice("");
        router.refresh();
      } catch (err) {
        setError(err instanceof Error ? err.message : "Errore nel salvataggio");
      }
    });
  }

  function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter") {
      e.preventDefault();
      submit();
    }
  }

  const cellInput =
    "border-0 bg-transparent shadow-none h-8 text-sm placeholder:text-[#71717a] focus-visible:ring-1 focus-visible:ring-primary";

  return (
    <>
    <tr className="border-b border-[#e5e7eb] bg-[#f9f9f9]">
      <td className="py-2 px-3">
        <Input
          value={name}
          onChange={(e) => setName(e.target.value)}
          onKeyDown={onKeyDown}
          placeholder="+ Aggiungi servizio"
          className={cellInput}
        />
      </td>
      <td className="py-2 px-3">
        <Input
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          onKeyDown={onKeyDown}
          placeholder="Descrizione..."
          className={cellInput}
        />
      </td>
      <td className="py-2 px-3">
        <Input
          value={category}
          onChange={(e) => setCategory(e.target.value)}
          onKeyDown={onKeyDown}
          placeholder="Categoria..."
          list="catalog-categoria-pool"
          className={cellInput}
        />
      </td>
      <td className="py-2 px-3">
        <Input
          value={fase}
          onChange={(e) => setFase(e.target.value)}
          onKeyDown={onKeyDown}
          placeholder="Fase..."
          list="catalog-fase-pool"
          className={cellInput}
        />
      </td>
      <td className="py-2 px-3 text-xs text-[#a1a1aa]" colSpan={2}>
        Tag e pacchetto dopo la creazione
      </td>
      <td className="py-2 px-3">
        <Input
          value={price}
          onChange={(e) => setPrice(e.target.value)}
          onKeyDown={onKeyDown}
          placeholder="0,00"
          inputMode="decimal"
          className={`${cellInput} tabular-nums`}
        />
      </td>
      <td className="py-2 px-3 text-xs text-[#a1a1aa]">Invio ↵</td>
      <datalist id="catalog-categoria-pool">
        {options.categoria.map((c) => (
          <option key={c} value={c} />
        ))}
      </datalist>
      <datalist id="catalog-fase-pool">
        {options.fase.map((f) => (
          <option key={f} value={f} />
        ))}
      </datalist>
    </tr>
    {error && (
      <tr>
        <td colSpan={COL_COUNT} className="py-1 px-3 text-xs text-red-600">
          {error}
        </td>
      </tr>
    )}
    </>
  );
}

export function ServiceTable({
  services,
  options,
}: {
  services: ServiceWithTags[];
  options: CatalogFieldOptions;
}) {
  const activeServices = services.filter((s) => s.active);
  const inactiveServices = services.filter((s) => !s.active);

  return (
    <div className="bg-white rounded-xl border border-[#e5e7eb] overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead className="bg-[#f9f9f9] border-b border-[#e5e7eb] sticky top-0 z-[1]">
            <tr>
              {COLUMN_HEADERS.map((header) => (
                <th
                  key={header}
                  className="text-left py-2 px-3 font-semibold text-[#71717a]"
                >
                  {header}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {activeServices.map((service) => (
              <ServiceRow key={service.id} service={service} options={options} />
            ))}
            <QuickAddRow options={options} />
            {inactiveServices.length > 0 && (
              <>
                <tr className="bg-[#fafafa]">
                  <td
                    colSpan={COL_COUNT}
                    className="py-1.5 px-3 text-xs font-medium uppercase tracking-wide text-[#a1a1aa]"
                  >
                    Servizi disattivati
                  </td>
                </tr>
                {inactiveServices.map((service) => (
                  <ServiceRow key={service.id} service={service} options={options} />
                ))}
              </>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
