"use client";

import React from "react";
import { FiGift, FiCheckCircle, FiXCircle, FiTag, FiToggleLeft, FiToggleRight } from "react-icons/fi";
import type { AdminBillingStatus } from "@/lib/api/billingAdminApi";

export type RowStatus = AdminBillingStatus | "loading" | null;

function money(a: number | null, c: string | null) {
  return a ? `${(a / 100).toFixed(2)} ${(c || "AED").toUpperCase()}` : "—";
}

const badge = (color: string, bg: string): React.CSSProperties => ({
  display: "inline-block",
  padding: "3px 10px",
  borderRadius: 999,
  fontSize: 12,
  fontWeight: 700,
  color,
  background: bg,
  whiteSpace: "nowrap",
});

// check `active` FIRST — a revoked/canceled comp still has plan='comp' (is_free)
function StatusBadge({ s }: { s: RowStatus }) {
  if (s === "loading") return <span style={badge("#64748b", "#f1f5f9")}>Loading…</span>;
  if (!s) return <span style={badge("#991b1b", "#fef2f2")}>Error</span>;

  if (!s.active) {
    if (s.status === "past_due") return <span style={badge("#b45309", "#fffbeb")}>Past due</span>;
    if (s.status === "canceled") return <span style={badge("#991b1b", "#fef2f2")}>Canceled</span>;
    if (s.status === "expired") return <span style={badge("#991b1b", "#fef2f2")}>Expired</span>;
    return <span style={badge("#475569", "#f1f5f9")}>No subscription</span>;
  }
  if (s.is_free) return <span style={badge("#7c3aed", "#f5f3ff")}>Free (comp)</span>;
  return <span style={badge("#166534", "#f0fdf4")}>Active</span>;
}

// ✅ compact square ICON buttons in ONE row (fixes tall rows)
const iconBtn = (bg: string): React.CSSProperties => ({
  display: "inline-flex",
  alignItems: "center",
  justifyContent: "center",
  width: 30,
  height: 30,
  borderRadius: 7,
  border: "none",
  background: bg,
  color: "#fff",
  cursor: "pointer",
  flexShrink: 0,
});

interface Props {
  company: { id: number; name: string };
  status: RowStatus;
  busy: boolean;
  onGrantFree: () => void;
  onMarkPaid: () => void;
  onRevoke: () => void;
  onSetPrice: () => void;
  onToggleEnabled: () => void;
}

export default function BillingRow({
  company,
  status,
  busy,
  onGrantFree,
  onMarkPaid,
  onRevoke,
  onSetPrice,
  onToggleEnabled,
}: Props) {
  const s = status && status !== "loading" ? status : null;
  return (
    <tr>
      <td style={{ color: "#94a3b8", fontWeight: 600, whiteSpace: "nowrap" }}>#{company.id}</td>
      <td style={{ fontWeight: 600, color: "#0f172a" }}>{company.name}</td>
      <td>
        <StatusBadge s={status} />
      </td>
      <td style={{ color: "#475569", whiteSpace: "nowrap" }}>{s?.plan ?? "—"}</td>
      <td style={{ color: "#475569", whiteSpace: "nowrap" }}>
        {s
          ? s.price_amount
            ? `${money(s.price_amount, s.price_currency)} / ${s.price_interval || "year"}`
            : "default"
          : "—"}
      </td>
      <td>
        <div style={{ display: "flex", gap: 6, flexWrap: "nowrap", alignItems: "center" }}>
          <button
            onClick={onToggleEnabled}
            disabled={busy}
            title={s?.billing_enabled ? "Payment ON — click to turn OFF" : "Payment OFF — click to turn ON"}
            style={{
              display: "inline-flex", alignItems: "center", gap: 5, height: 30, padding: "0 10px",
              borderRadius: 7, border: "none", cursor: "pointer", fontSize: 12, fontWeight: 700,
              color: "#fff", background: s?.billing_enabled ? "#0f766e" : "#94a3b8",
              opacity: busy ? 0.5 : 1, flexShrink: 0, whiteSpace: "nowrap",
            }}
          >
            {s?.billing_enabled ? <FiToggleRight size={16} /> : <FiToggleLeft size={16} />}
            {s?.billing_enabled ? "ON" : "OFF"}
          </button>
          <button style={{ ...iconBtn("#0f766e"), opacity: busy ? 0.5 : 1 }} disabled={busy} onClick={onGrantFree} title="Grant free access (comp)">
            <FiGift size={14} />
          </button>
          <button style={{ ...iconBtn("#2563eb"), opacity: busy ? 0.5 : 1 }} disabled={busy} onClick={onMarkPaid} title="Mark paid (manual / offline)">
            <FiCheckCircle size={14} />
          </button>
          <button style={{ ...iconBtn("#b45309"), opacity: busy ? 0.5 : 1 }} disabled={busy} onClick={onSetPrice} title="Set price">
            <FiTag size={14} />
          </button>
          <button style={{ ...iconBtn("#dc2626"), opacity: busy ? 0.5 : 1 }} disabled={busy} onClick={onRevoke} title="Revoke access">
            <FiXCircle size={14} />
          </button>
        </div>
      </td>
    </tr>
  );
}