import { useState, useEffect } from "react";

// ─── Types ─────────────────────────────────────────────────────────

interface LicenseStatus {
  status: string;
  tier?: string;
  email?: string;
  expires?: string;
  features?: string[];
  message?: string;
}

interface OnboardingProgress {
  steps: {
    id: string;
    label: string;
    completed: boolean;
    completed_at?: string;
  }[];
  completed: number;
  total: number;
  pct: number;
  finished: boolean;
  ready_for_live: boolean;
}

interface HealthData {
  ok: boolean;
  timestamp: string;
  subsystems: Record<string, { status: string; [key: string]: unknown }>;
  alerts: { subsystem: string; level: string; status: string }[];
}

// ─── Component ─────────────────────────────────────────────────────

export default function CommercialGate() {
  const [health, setHealth] = useState<HealthData | null>(null);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState(false);
  const [activating, setActivating] = useState(false);
  const [licenseKey, setLicenseKey] = useState("");
  const [activateResult, setActivateResult] = useState<string>("");

  useEffect(() => {
    fetch("/health/full")
      .then((r) => r.json())
      .then((data: HealthData) => {
        setHealth(data);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  if (loading) {
    return null;
  }

  const license = (health?.subsystems?.license as LicenseStatus) || {};
  const onboarding =
    (health?.subsystems?.onboarding as unknown as OnboardingProgress) || {};
  const compliance = health?.subsystems?.compliance || {};
  const trading = health?.subsystems?.trading || {};
  const backup = health?.subsystems?.backup || {};
  const email = health?.subsystems?.email || {};
  const payment = health?.subsystems?.payment || {};
  const apiKey = health?.subsystems?.api_key || {};

  const handleActivate = async () => {
    if (!licenseKey.trim()) return;
    setActivating(true);
    setActivateResult("");
    try {
      const resp = await fetch("/api/license/activate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ license_key: licenseKey.trim() }),
      });
      const data = await resp.json();
      if (data.ok) {
        setActivateResult("Activation successful! Refresh to see changes.");
        setLicenseKey("");
        fetch("/health/full")
          .then((r) => r.json())
          .then((d: HealthData) => setHealth(d));
      } else {
        setActivateResult(data.message || "Activation failed. Check your key.");
      }
    } catch {
      setActivateResult("Network error. Please try again.");
    } finally {
      setActivating(false);
    }
  };

  const isLicensed = license.status === "ACTIVE";
  const isCompliant = (compliance as Record<string, boolean>)
    ?.risk_disclosure_accepted;
  const isLiveBlocked = (compliance as Record<string, boolean>)
    ?.live_trading_blocked;
  const daemonRunning =
    (trading as Record<string, string>)?.daemon === "RUNNING";

  const alerts = health?.alerts || [];
  const hasErrors = alerts.some((a) => a.level === "ERROR");
  const hasWarnings = alerts.some((a) => a.level === "WARNING");

  return (
    <div style={styles.container}>
      {/* Header bar */}
      <div
        style={{
          ...styles.bar,
          background: hasErrors
            ? "linear-gradient(135deg, #dc2626, #991b1b)"
            : hasWarnings
              ? "linear-gradient(135deg, #d4a017, #b8860b)"
              : "linear-gradient(135deg, #16a34a, #15803d)",
        }}
        onClick={() => setExpanded(!expanded)}
      >
        <div style={styles.barLeft}>
          <span style={styles.dot}>
            {hasErrors ? "●" : hasWarnings ? "●" : "●"}
          </span>
          <span style={styles.barTitle}>
            {hasErrors
              ? "Action Required"
              : hasWarnings
                ? "Attention Needed"
                : "System Healthy"}
          </span>
        </div>
        <div style={styles.barRight}>
          <span style={styles.badge}>{daemonRunning ? "LIVE" : "IDLE"}</span>
          <span style={styles.chevron}>{expanded ? "▴" : "▾"}</span>
        </div>
      </div>

      {/* Expanded panel */}
      {expanded && (
        <div style={styles.panel}>
          {/* License */}
          <Section title="License" icon="🔑">
            <Row label="Status">
              <StatusBadge status={license.status} />
            </Row>
            {isLicensed && (
              <>
                <Row label="Tier" value={license.tier} />
                <Row label="Expires" value={license.expires} />
                <Row label="Email" value={license.email} />
              </>
            )}
            {!isLicensed && (
              <div style={styles.actionBox}>
                <div>Enter your license key to activate:</div>
                <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
                  <input
                    type="text"
                    placeholder="GAT-XXXX-XXXX-XXXX-XXXX"
                    value={licenseKey}
                    onChange={(e) => setLicenseKey(e.target.value)}
                    disabled={activating}
                    style={{
                      flex: 1,
                      padding: "6px 10px",
                      border: "1px solid #d4a017",
                      borderRadius: 4,
                      fontSize: 13,
                      outline: "none",
                    }}
                    onKeyDown={(e) => e.key === "Enter" && handleActivate()}
                  />
                  <button
                    onClick={handleActivate}
                    disabled={activating || !licenseKey.trim()}
                    style={{
                      padding: "6px 14px",
                      background: activating ? "#ccc" : "#d4a017",
                      color: "#fff",
                      border: "none",
                      borderRadius: 4,
                      cursor: activating ? "default" : "pointer",
                      fontSize: 13,
                      fontWeight: 600,
                      whiteSpace: "nowrap",
                    }}
                  >
                    {activating ? "..." : "Activate"}
                  </button>
                </div>
                {activateResult && (
                  <div
                    style={{
                      marginTop: 6,
                      fontSize: 12,
                      color: activateResult.includes("success")
                        ? "#16a34a"
                        : "#dc2626",
                    }}
                  >
                    {activateResult}
                  </div>
                )}
              </div>
            )}
          </Section>

          {/* API Key */}
          <Section title="AI API Key (DeepSeek)" icon="🤖">
            <Row label="Status">
              <StatusBadge
                status={
                  (apiKey as Record<string, string>)?.status || "NOT_CONFIGURED"
                }
              />
            </Row>
            {(apiKey as Record<string, string>)?.status !== "CONFIGURED" && (
              <div style={styles.actionBox}>
                DeepSeek API key required for AI-driven trading decisions.{" "}
                <a
                  href="https://platform.deepseek.com/api_keys"
                  target="_blank"
                  rel="noreferrer"
                  style={styles.link}
                >
                  Get API key →
                </a>
                <div style={{ marginTop: 6, fontSize: 11, color: "#888" }}>
                  Configure via Dashboard Settings or set DEEPSEEK_API_KEY
                  environment variable.
                </div>
              </div>
            )}
          </Section>

          {/* Compliance */}
          <Section title="Compliance" icon="⚖️">
            <Row label="Risk Disclosure">
              <StatusBadge status={isCompliant ? "ACCEPTED" : "NOT_ACCEPTED"} />
            </Row>
            <Row label="Live Trading">
              <StatusBadge status={isLiveBlocked ? "BLOCKED" : "ALLOWED"} />
            </Row>
          </Section>

          {/* Onboarding */}
          <Section title="Onboarding" icon="🚀">
            <Row
              label="Progress"
              value={`${onboarding.completed || 0}/${onboarding.total || 6} steps`}
            />
            {onboarding.steps && (
              <div style={styles.stepsList}>
                {onboarding.steps.map((s) => (
                  <div key={s.id} style={styles.step}>
                    <span
                      style={s.completed ? styles.stepDone : styles.stepPending}
                    >
                      {s.completed ? "✓" : "○"}
                    </span>
                    <span style={s.completed ? styles.stepLabelDone : {}}>
                      {s.label}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </Section>

          {/* Trading */}
          <Section title="Trading" icon="📊">
            <Row label="Daemon">
              <StatusBadge status={daemonRunning ? "RUNNING" : "STOPPED"} />
            </Row>
            <Row
              label="Mode"
              value={(trading as Record<string, string>)?.mode || "unknown"}
            />
          </Section>

          {/* Operations */}
          <Section title="Operations" icon="⚙️">
            <Row
              label="Backups"
              value={`${(backup as Record<string, number>)?.total_backups || 0} stored`}
            />
            <Row label="Email">
              <StatusBadge
                status={
                  (email as Record<string, string>)?.status === "CONFIGURED"
                    ? "CONFIGURED"
                    : "PENDING"
                }
              />
            </Row>
          </Section>

          {/* License / Purchase */}
          <Section title="Purchase License" icon="💎">
            <Row
              label="WeChat"
              value={
                (payment as Record<string, string>)?.contact_wechat ||
                "goldautotrade"
              }
            />
            <Row
              label="QQ"
              value={
                (payment as Record<string, string>)?.contact_qq ||
                "goldautotrade"
              }
            />
            <Row
              label="Email"
              value={
                (payment as Record<string, string>)?.contact_email ||
                "support@goldauto.top"
              }
            />
            <div style={styles.actionBox}>
              Trial expires in 14 days. No credit card required.{" "}
              <a href="https://goldauto.top/license" style={styles.link}>
                Purchase license →
              </a>
            </div>
          </Section>

          {/* Alerts */}
          {alerts.length > 0 && (
            <Section title="Alerts" icon="⚠️">
              {alerts.map((a, i) => (
                <div
                  key={i}
                  style={{
                    ...styles.alert,
                    background: a.level === "ERROR" ? "#fef2f2" : "#fefce8",
                    borderLeftColor:
                      a.level === "ERROR" ? "#dc2626" : "#d4a017",
                  }}
                >
                  <strong>{a.subsystem}</strong>: {a.status}
                </div>
              ))}
            </Section>
          )}

          <div style={styles.footer}>
            Last updated: {health?.timestamp?.slice(0, 19) || "unknown"}
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Sub-components ────────────────────────────────────────────────

function Section({
  title,
  icon,
  children,
}: {
  title: string;
  icon: string;
  children: React.ReactNode;
}) {
  return (
    <div style={styles.section}>
      <div style={styles.sectionTitle}>
        {icon} {title}
      </div>
      {children}
    </div>
  );
}

function Row({
  label,
  value,
  children,
}: {
  label: string;
  value?: string;
  children?: React.ReactNode;
}) {
  return (
    <div style={styles.row}>
      <span style={styles.rowLabel}>{label}</span>
      <span style={styles.rowValue}>
        {children || <span style={{ color: "#666" }}>{value || "—"}</span>}
      </span>
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const colorMap: Record<string, string> = {
    ACTIVE: "#16a34a",
    OK: "#16a34a",
    PASS: "#16a34a",
    CONFIGURED: "#16a34a",
    RUNNING: "#16a34a",
    ALLOWED: "#16a34a",
    ACCEPTED: "#16a34a",
    LIVE: "#16a34a",
    COMPLETED: "#16a34a",
    MOCK: "#6b7280",
    IDLE: "#6b7280",
    PENDING: "#d4a017",
    WARNING: "#d4a017",
    NOT_CONFIGURED: "#d4a017",
    NOT_ACCEPTED: "#d4a017",
    NO_BACKUPS: "#d4a017",
    STOPPED: "#d4a017",
    BLOCKED: "#dc2626",
    ERROR: "#dc2626",
    FAIL: "#dc2626",
    EXPIRED: "#dc2626",
    REVOKED: "#dc2626",
    UNLICENSED: "#dc2626",
  };

  const color = colorMap[status] || "#6b7280";
  return (
    <span
      style={{
        display: "inline-block",
        padding: "2px 8px",
        borderRadius: 4,
        fontSize: 11,
        fontWeight: 600,
        letterSpacing: "0.5px",
        color: "#fff",
        background: color,
      }}
    >
      {status}
    </span>
  );
}

// ─── Inline Styles ─────────────────────────────────────────────────

const styles: Record<string, React.CSSProperties> = {
  container: {
    fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    maxWidth: 480,
    margin: "0 auto",
  },
  bar: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    padding: "10px 16px",
    borderRadius: 8,
    color: "#fff",
    cursor: "pointer",
    userSelect: "none",
    fontSize: 14,
    fontWeight: 600,
  },
  barLeft: { display: "flex", alignItems: "center", gap: 8 },
  barRight: { display: "flex", alignItems: "center", gap: 8 },
  barTitle: { letterSpacing: "-0.3px" },
  dot: { fontSize: 8 },
  badge: {
    fontSize: 10,
    padding: "2px 8px",
    borderRadius: 4,
    background: "rgba(255,255,255,0.25)",
    letterSpacing: "1px",
  },
  chevron: { fontSize: 10 },
  panel: {
    marginTop: 8,
    background: "#fff",
    borderRadius: 8,
    border: "1px solid #e5e5e5",
    overflow: "hidden",
  },
  section: {
    padding: "14px 16px",
    borderBottom: "1px solid #f0f0f0",
  },
  sectionTitle: {
    fontSize: 12,
    fontWeight: 600,
    color: "#888",
    textTransform: "uppercase" as const,
    letterSpacing: "1px",
    marginBottom: 10,
  },
  row: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    padding: "4px 0",
    fontSize: 13,
  },
  rowLabel: { color: "#888" },
  rowValue: { fontWeight: 500 },
  actionBox: {
    marginTop: 8,
    padding: "10px 12px",
    background: "#fef2f2",
    borderRadius: 6,
    fontSize: 13,
    color: "#991b1b",
  },
  link: { color: "#d4a017", textDecoration: "none", fontWeight: 600 },
  stepsList: { marginTop: 6 },
  step: {
    display: "flex",
    alignItems: "center",
    gap: 8,
    padding: "3px 0",
    fontSize: 12,
  },
  stepDone: {
    color: "#16a34a",
    fontWeight: 700,
    width: 16,
    textAlign: "center" as const,
  },
  stepPending: { color: "#ccc", width: 16, textAlign: "center" as const },
  stepLabelDone: { color: "#888", textDecoration: "line-through" },
  alert: {
    padding: "8px 12px",
    margin: "4px 0",
    borderRadius: 4,
    borderLeft: "3px solid",
    fontSize: 12,
  },
  footer: {
    padding: "10px 16px",
    fontSize: 10,
    color: "#ccc",
    textAlign: "center" as const,
  },
};
