import { getTargetHourlyRate, updateSetting, SETTINGS_KEYS } from "@/lib/settings";
import { getAllPools } from "@/lib/taxonomy";
import { TaxonomyManager } from "@/components/admin/impostazioni/TaxonomyManager";
import { PageHeader } from "@/components/admin/PageHeader";

export const revalidate = 0;

export default async function ImpostazioniPage() {
  const [targetRate, pools] = await Promise.all([getTargetHourlyRate(), getAllPools()]);

  async function handleSave(fd: FormData) {
    "use server";
    const raw = fd.get("target_hourly_rate");
    const val = parseFloat(String(raw ?? ""));
    if (isNaN(val) || val < 0) return;
    await updateSetting(SETTINGS_KEYS.TARGET_HOURLY_RATE, val.toFixed(2));
  }

  return (
    <div className="space-y-8">
      <PageHeader
        title="Impostazioni"
        subtitle="Configura le tariffe target e gestisci le tassonomie globali del sistema"
      />

      <section className="rounded-xl border border-border-light bg-card p-6 shadow-card">
        <div className="max-w-2xl">
          <h2 className="mb-1 text-xs font-bold uppercase tracking-wider text-foreground">
            Analytics Profittabilità
          </h2>
          <p className="mb-6 text-xs text-tertiary">
            Tariffa oraria target (€/h). Usata per calcolare il costo ideale e il delta
            profitto/perdita per ogni progetto.
          </p>

          <form action={handleSave} className="flex items-center gap-3">
            <div className="relative rounded-lg border border-border transition-all duration-150 focus-within:border-primary focus-within:ring-1 focus-within:ring-primary">
              <span className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-xs font-medium text-tertiary">
                €
              </span>
              <input
                id="target_hourly_rate"
                name="target_hourly_rate"
                type="number"
                step="0.01"
                min="0"
                defaultValue={targetRate.toFixed(2)}
                aria-label="Tariffa oraria target"
                className="w-36 bg-transparent py-2.5 pl-7 pr-12 font-mono text-xs font-semibold text-foreground focus:outline-none"
              />
              <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-[11px] font-medium text-tertiary">
                /h
              </span>
            </div>

            <button
              type="submit"
              className="rounded-lg bg-primary px-5 py-2.5 text-xs font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary/90"
            >
              Salva
            </button>
          </form>
        </div>
      </section>

      <TaxonomyManager pools={pools} />
    </div>
  );
}
