"use client";

import { useState, useTransition } from "react";
import { useTranslations } from "next-intl";
import { clientRespondPriceAction, clientCounterPriceAction } from "@/lib/actions/orders";
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);

export function PriceProposalClient({
  orderId,
  phase,
  history,
}: {
  orderId: string;
  phase: Phase;
  history: PriceProposalDoc[];
}) {
  const t = useTranslations("orders");
  const [pending, startTransition] = useTransition();
  const [countering, setCountering] = useState(false);
  const [amount, setAmount] = useState("");
  const [note, setNote] = useState("");

  return (
    <div className="border border-white/10 rounded-xl p-5">
      <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] mb-3">{t("priceTitle")}</p>

      {phase === "none" && <p className="text-sm text-[var(--rk-ink-muted)]">{t("priceNone")}</p>}

      {history.length > 0 && (
        <ul className="flex flex-col gap-1 mb-3">
          {history.map((p) => (
            <li key={String(p._id)} className="text-sm">
              {p.proposedBy === "admin" ? t("priceFromRakku") : t("priceFromYou")}: {fmt(p.amount)}
              {p.note ? ` — ${p.note}` : ""}
            </li>
          ))}
        </ul>
      )}

      {phase === "agreed" && (
        <p className="text-sm text-emerald-400">
          {t("priceAgreed", { amount: fmt(history[history.length - 1].amount) })}
        </p>
      )}

      {phase === "waiting_on_admin" && <p className="text-sm text-[var(--rk-ink-muted)]">{t("priceWaitingOnAdmin")}</p>}
      {phase === "rejected" && <p className="text-sm text-[var(--rk-ink-muted)]">{t("priceRejected")}</p>}

      {phase === "waiting_on_client" && !countering && (
        <div className="flex flex-wrap gap-2">
          <button
            disabled={pending}
            onClick={() => startTransition(() => clientRespondPriceAction(orderId, "accepted"))}
            className="text-xs border border-emerald-400/40 text-emerald-400 rounded-lg px-4 py-2 hover:bg-emerald-400/10 disabled:opacity-50"
          >
            {t("priceAccept")}
          </button>
          <button
            disabled={pending}
            onClick={() => startTransition(() => clientRespondPriceAction(orderId, "rejected"))}
            className="text-xs border border-red-400/40 text-red-400 rounded-lg px-4 py-2 hover:bg-red-400/10 disabled:opacity-50"
          >
            {t("priceReject")}
          </button>
          <button
            disabled={pending}
            onClick={() => setCountering(true)}
            className="text-xs border border-white/20 rounded-lg px-4 py-2 hover:border-white/50 disabled:opacity-50"
          >
            {t("priceCounter")}
          </button>
        </div>
      )}

      {phase === "waiting_on_client" && countering && (
        <form
          onSubmit={(e) => {
            e.preventDefault();
            const amt = Number(amount);
            if (!amt || amt <= 0) return;
            startTransition(() => {
              clientCounterPriceAction(orderId, amt, note);
              setCountering(false);
              setAmount("");
              setNote("");
            });
          }}
          className="flex flex-wrap gap-2 items-center"
        >
          <input
            type="number"
            min="0"
            step="1"
            placeholder="€"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            required
            className="w-24 bg-transparent 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={t("priceNotePlaceholder")}
            value={note}
            onChange={(e) => setNote(e.target.value)}
            className="flex-1 min-w-[8rem] bg-transparent 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"
          >
            {t("priceSendCounter")}
          </button>
        </form>
      )}
    </div>
  );
}
