// =============================================================================
// WOOO AIOps - AwoooP M1 租戶管理頁面
// =============================================================================
// 顯示所有 tenant 清單，含 migration_mode badge 與 suspended 狀態

"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Building2,
  RefreshCw,
  AlertCircle,
  DollarSign,
  Ban,
  CheckCircle2,
} from "lucide-react";
import { cn } from "@/lib/utils";

// =============================================================================
// Types
// =============================================================================

type MigrationMode =
  | "legacy_awoooi_default"
  | "shadow"
  | "canary"
  | "read_only"
  | "suggest"
  | "auto_remediate";

interface Tenant {
  project_id: string;
  display_name: string;
  migration_mode: MigrationMode;
  budget_limit_usd: number | string | null;
  is_active: boolean;
}

interface ApiResponse {
  tenants?: Tenant[];
  items?: Tenant[];
  total: number;
}

// =============================================================================
// 常數
// =============================================================================

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "";

const MIGRATION_MODE_CONFIG: Record<
  MigrationMode,
  { label: string; bg: string; text: string; border: string }
> = {
  legacy_awoooi_default: {
    label: "Legacy",
    bg: "bg-white",
    text: "text-[#5f5b52]",
    border: "border-[#d8d3c7]",
  },
  shadow: {
    label: "Shadow",
    bg: "bg-[#f4f1e8]",
    text: "text-[#5f5b52]",
    border: "border-[#d8d3c7]",
  },
  canary: {
    label: "Canary",
    bg: "bg-[#fff7e8]",
    text: "text-[#8a5a08]",
    border: "border-[#d9b36f]",
  },
  read_only: {
    label: "Read Only",
    bg: "bg-[#eef5ff]",
    text: "text-[#1f5b9b]",
    border: "border-[#9bb6d9]",
  },
  suggest: {
    label: "Suggest",
    bg: "bg-[#f6f0ff]",
    text: "text-[#6541a5]",
    border: "border-[#baa7de]",
  },
  auto_remediate: {
    label: "Auto Remediate",
    bg: "bg-[#f0faf2]",
    text: "text-[#17602a]",
    border: "border-[#9bc7a4]",
  },
};

// =============================================================================
// Sub Components
// =============================================================================

function MigrationModeBadge({ mode }: { mode: MigrationMode }) {
  const config = MIGRATION_MODE_CONFIG[mode] ?? MIGRATION_MODE_CONFIG.shadow;
  return (
    <span
      className={cn(
        "inline-flex items-center px-2.5 py-0.5 rounded-md text-xs font-mono font-medium border",
        config.bg,
        config.text,
        config.border
      )}
    >
      {config.label}
    </span>
  );
}

function SuspendedBadge({ suspended }: { suspended: boolean }) {
  return suspended ? (
    <span className="inline-flex items-center gap-1 border border-[#e2a29b] bg-[#fff0ef] px-2.5 py-0.5 text-xs font-medium text-[#9f2f25]">
      <Ban className="w-3 h-3" aria-hidden="true" />
      停用
    </span>
  ) : (
    <span className="inline-flex items-center gap-1 border border-[#9bc7a4] bg-[#f0faf2] px-2.5 py-0.5 text-xs font-medium text-[#17602a]">
      <CheckCircle2 className="w-3 h-3" aria-hidden="true" />
      正常
    </span>
  );
}

function TenantRow({ tenant }: { tenant: Tenant }) {
  const budget =
    tenant.budget_limit_usd == null ? null : Number(tenant.budget_limit_usd);

  return (
    <tr className="border-b border-border hover:bg-accent/30 transition-colors">
      <td className="px-4 py-3">
        <span className="font-mono text-sm text-foreground">
          {tenant.project_id}
        </span>
      </td>
      <td className="px-4 py-3">
        <span className="text-sm text-foreground font-medium">{tenant.display_name || "--"}</span>
      </td>
      <td className="px-4 py-3">
        <MigrationModeBadge mode={tenant.migration_mode} />
      </td>
      <td className="px-4 py-3">
        <span className="flex items-center gap-1 text-sm text-muted-foreground font-mono">
          {tenant.budget_limit_usd != null ? (
            <>
              <DollarSign className="w-3.5 h-3.5" aria-hidden="true" />
              {budget?.toLocaleString("en-US", {
                minimumFractionDigits: 2,
              })}
            </>
          ) : (
            "--"
          )}
        </span>
      </td>
      <td className="px-4 py-3">
        <SuspendedBadge suspended={!tenant.is_active} />
      </td>
    </tr>
  );
}

// =============================================================================
// Main Component
// =============================================================================

export default function TenantsPage() {
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchTenants = useCallback(async () => {
    try {
      setError(null);
      const res = await fetch(`${API_BASE}/api/v1/platform/tenants`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data: ApiResponse = await res.json();
      const rows = Array.isArray(data.tenants) ? data.tenants : data.items;
      setTenants(Array.isArray(rows) ? rows : []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "載入失敗");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchTenants();
  }, [fetchTenants]);

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Building2 className="w-5 h-5 text-brand-accent" aria-hidden="true" />
          <div>
            <h2 className="text-lg font-semibold text-foreground">租戶管理</h2>
            <p className="text-xs text-muted-foreground">
              {loading ? "載入中..." : `共 ${tenants.length} 個租戶`}
            </p>
          </div>
        </div>
        <button
          onClick={fetchTenants}
          disabled={loading}
          className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition disabled:opacity-50"
          aria-label="重新整理租戶清單"
        >
          <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} aria-hidden="true" />
          重新整理
        </button>
      </div>

      {/* Error State */}
      {error && (
        <div className="flex items-start gap-3 p-4 bg-red-900/20 border border-red-800/40 rounded-lg">
          <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" aria-hidden="true" />
          <div>
            <p className="text-sm font-medium text-red-300">無法載入租戶資料</p>
            <p className="text-xs text-red-400 mt-1">{error}</p>
          </div>
        </div>
      )}

      {/* Table */}
      <div className="overflow-hidden border border-[#e0ddd4] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.05)]">
        <div className="overflow-x-auto">
          <table className="w-full" role="table" aria-label="租戶清單">
            <thead>
              <tr className="border-b border-border bg-muted/50">
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  Project ID
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  名稱
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  模式
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  預算上限 (USD)
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  狀態
                </th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                // Loading skeleton
                Array.from({ length: 5 }).map((_, i) => (
                  <tr key={i} className="border-b border-border">
                    {Array.from({ length: 5 }).map((_, j) => (
                      <td key={j} className="px-4 py-3">
                        <div className="h-5 bg-muted animate-pulse rounded w-24" />
                      </td>
                    ))}
                  </tr>
                ))
              ) : tenants.length === 0 && !error ? (
                <tr>
                  <td colSpan={5} className="px-4 py-16 text-center">
                    <Building2 className="w-10 h-10 text-muted-foreground/30 mx-auto mb-3" aria-hidden="true" />
                    <p className="text-sm text-muted-foreground">尚無租戶資料</p>
                  </td>
                </tr>
              ) : (
                tenants.map((tenant) => (
                  <TenantRow key={tenant.project_id} tenant={tenant} />
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
