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

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>
      <h1 className="text-2xl font-bold text-[#1a1a1a] mb-6">Impostazioni</h1>

      <div className="space-y-6 max-w-4xl">
        <div className="bg-white rounded-xl border border-[#e5e7eb] p-6 max-w-md">
          <h2 className="text-base font-semibold text-[#1a1a1a] mb-4">Analytics Profittabilità</h2>

          <form action={handleSave} className="space-y-4">
            <div>
              <label
                htmlFor="target_hourly_rate"
                className="block text-sm font-medium text-[#1a1a1a] mb-1"
              >
                Tariffa oraria target (€/h)
              </label>
              <p className="text-xs text-[#71717a] mb-2">
                Usata per calcolare il costo ideale e il delta profitto/perdita per ogni progetto.
              </p>
              <div className="flex items-center gap-2">
                <span className="text-sm text-[#71717a]">€</span>
                <input
                  id="target_hourly_rate"
                  name="target_hourly_rate"
                  type="number"
                  step="0.01"
                  min="0"
                  defaultValue={targetRate.toFixed(2)}
                  className="border border-[#e5e7eb] rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#1A463C]/20 w-32"
                />
                <span className="text-sm text-[#71717a]">/h</span>
              </div>
            </div>

            <button
              type="submit"
              className="bg-[#1A463C] text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-[#1A463C]/90 transition-colors"
            >
              Salva
            </button>
          </form>
        </div>

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