"use client";

import { useState, useTransition } from "react";
import { adminProposePriceAction, adminRespondPriceAction } from "@/lib/actions/admin";
import type { PriceProposalDoc } from "@/models/PriceProposal";

type Phase = "none" | "waiting_on_client" | "waiting_on_admin" | "agreed" | "rejected";

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

type PriceTemplateOption = { id: string; name: string; defaultAmount: number; note: string };

export function PriceProposalAdmin({
  orderId,
  phase,
  history,
  templates = [],
}: {
  orderId: string;
  phase: Phase;
  history: PriceProposalDoc[];
  templates?: PriceTemplateOption[];
}) {
  const [pending, startTransition] = useTransition();
  const [amount, setAmount] = useState("");
  const [note, setNote] = useState("");

  function applyTemplate(templateId: string) {
    const tpl = templates.find((t) => t.id === templateId);
    if (!tpl) return;
    setAmount(String(tpl.defaultAmount));
    setNote(tpl.note);
  }

  const canPropose = phase === "none" || phase === "rejected" || phase === "waiting_on_admin";
  const canRespond = phase === "waiting_on_admin";

  return (
    <div className="mt-4 border-t border-white/10 pt-4">
      <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] mb-2">Preis</p>

      {history.length > 0 && (
        <ul className="flex flex-col gap-1 mb-3">
          {history.map((p) => (
            <li key={String(p._id)} className="text-xs text-[var(--rk-ink-muted)]">
              {p.proposedBy === "admin" ? "Du" : "Kunde"}: {fmt(p.amount)}
              {p.note ? ` — ${p.note}` : ""} <StatusTag status={p.status} />
            </li>
          ))}
        </ul>
      )}

      {phase === "agreed" && (
        <p className="text-sm text-emerald-400">Preis vereinbart: {fmt(history[history.length - 1].amount)}</p>
      )}
      {phase === "waiting_on_client" && <p className="text-xs text-[var(--rk-ink-muted)]">Warte auf Antwort vom Kunden.</p>}

      {canRespond && (
        <div className="flex gap-2 mb-3">
          <button
            disabled={pending}
            onClick={() => startTransition(() => adminRespondPriceAction(orderId, "accepted"))}
            className="text-xs border border-emerald-400/40 text-emerald-400 rounded-lg px-3 py-1.5 hover:bg-emerald-400/10 disabled:opacity-50"
          >
            Gegenvorschlag annehmen
          </button>
          <button
            disabled={pending}
            onClick={() => startTransition(() => adminRespondPriceAction(orderId, "rejected"))}
            className="text-xs border border-red-400/40 text-red-400 rounded-lg px-3 py-1.5 hover:bg-red-400/10 disabled:opacity-50"
          >
            Ablehnen
          </button>
        </div>
      )}

      {canPropose && templates.length > 0 && (
        <select
          defaultValue=""
          onChange={(e) => {
            applyTemplate(e.target.value);
            e.target.value = "";
          }}
          className="mb-2 w-full bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:border-white/50"
        >
          <option value="" disabled>
            Vorlage anwenden …
          </option>
          {templates.map((t) => (
            <option key={t.id} value={t.id}>
              {t.name} ({fmt(t.defaultAmount)})
            </option>
          ))}
        </select>
      )}

      {canPropose && (
        <form
          onSubmit={(e) => {
            e.preventDefault();
            const amt = Number(amount);
            if (!amt || amt <= 0) return;
            startTransition(() => {
              adminProposePriceAction(orderId, amt, note);
              setAmount("");
              setNote("");
            });
          }}
          className="flex flex-wrap gap-2 items-center"
        >
          <input
            type="number"
            min="0"
            step="1"
            placeholder="Betrag €"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            required
            className="w-28 bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:border-white/50"
          />
          <input
            type="text"
            placeholder="Notiz (optional)"
            value={note}
            onChange={(e) => setNote(e.target.value)}
            className="flex-1 min-w-[8rem] bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:border-white/50"
          />
          <button
            type="submit"
            disabled={pending}
            className="text-xs border border-white/30 rounded-lg px-3 py-1.5 hover:border-white disabled:opacity-50"
          >
            {phase === "waiting_on_admin" ? "Gegenvorschlag senden" : "Preis vorschlagen"}
          </button>
        </form>
      )}
    </div>
  );
}

function StatusTag({ status }: { status: string }) {
  const labels: Record<string, string> = {
    pending: "offen",
    accepted: "angenommen",
    rejected: "abgelehnt",
    countered: "überboten",
  };
  return <span className="opacity-60"> ({labels[status] ?? status})</span>;
}
