"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { updateTierAction, setTierActiveAction, deleteTierAction } from "@/lib/actions/services";
import { Input, TextArea } from "@/components/admin/EditServiceForm";
import { TierExtrasFields } from "@/components/admin/TierExtrasFields";

const fmt = (n: number) => new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(n);

export function TierRow({
  serviceId,
  tier,
}: {
  serviceId: string;
  tier: {
    id: string;
    name: string;
    nameEn: string;
    price: number;
    priceFrom: boolean;
    deliverables: string;
    deliverablesEn: string;
    active: boolean;
    addOns: { label: string; labelEn: string; priceSurcharge: number }[];
    promoPrice: number | null;
    promoLabel: string;
    promoFrom: string | null;
    promoUntil: string | null;
  };
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  function submit(form: HTMLFormElement) {
    const data = new FormData(form);
    startTransition(async () => {
      await updateTierAction(serviceId, tier.id, data);
      router.refresh();
    });
  }

  return (
    <details className={`bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 ${tier.active ? "" : "opacity-50"}`}>
      <summary className="flex items-center justify-between gap-3 cursor-pointer list-none">
        <div className="min-w-0">
          <p className="text-sm truncate">
            {tier.name} · {tier.priceFrom ? "ab " : ""}{fmt(tier.price)}
          </p>
          <p className="text-xs text-[var(--rk-ink-muted)] truncate">{tier.deliverables || "Bearbeiten ▾"}</p>
        </div>
        <div className="flex items-center gap-3 shrink-0" onClick={(e) => e.stopPropagation()}>
          <label className="flex items-center gap-1.5 text-xs">
            <input
              type="checkbox"
              checked={tier.active}
              disabled={pending}
              onChange={(e) => startTransition(async () => { await setTierActiveAction(serviceId, tier.id, e.target.checked); router.refresh(); })}
              className="h-3.5 w-3.5"
            />
            Aktiv
          </label>
          <button
            disabled={pending}
            onClick={() => {
              if (confirm(`Preisstufe „${tier.name}" wirklich löschen?`)) {
                startTransition(async () => {
                  await deleteTierAction(serviceId, tier.id);
                  router.refresh();
                });
              }
            }}
            className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
          >
            Löschen
          </button>
        </div>
      </summary>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          submit(e.currentTarget);
        }}
        className="mt-4 flex flex-col gap-3"
      >
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <Input name="name" label="Name (DE)" defaultValue={tier.name} required />
          <Input name="nameEn" label="Name (EN)" defaultValue={tier.nameEn} />
        </div>
        <div className="flex items-end gap-3">
          <label className="flex flex-col gap-1 text-sm">
            <span className="text-xs uppercase tracking-[0.08em] text-[var(--rk-ink-muted)]">Preis in €</span>
            <input
              name="price"
              type="number"
              min="0"
              step="1"
              defaultValue={tier.price}
              required
              className="w-28 bg-transparent border border-white/15 rounded-lg px-3 py-2 focus:outline-none focus:border-white/50"
            />
          </label>
          <label className="flex items-center gap-2 text-sm pb-2.5">
            <input type="checkbox" name="priceFrom" defaultChecked={tier.priceFrom} className="h-3.5 w-3.5" />
            „ab“-Preis
          </label>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <TextArea name="deliverables" label="Leistungen (DE)" defaultValue={tier.deliverables} />
          <TextArea name="deliverablesEn" label="Leistungen (EN)" defaultValue={tier.deliverablesEn} />
        </div>
        <TierExtrasFields
          defaults={{
            addOns: tier.addOns,
            promoPrice: tier.promoPrice,
            promoLabel: tier.promoLabel,
            promoFrom: tier.promoFrom,
            promoUntil: tier.promoUntil,
          }}
        />
        <button
          type="submit"
          disabled={pending}
          className="self-start border border-white/30 rounded-lg px-4 py-2 text-xs uppercase tracking-[0.15em] hover:border-white disabled:opacity-50"
        >
          Speichern
        </button>
      </form>
    </details>
  );
}
