// =============================================================================
// WOOO AIOps - AwoooP M3 合約儀表板
// =============================================================================
// 顯示所有 contract revisions，支援 project_id 篩選

"use client";

import { useState, useEffect, useCallback } from "react";
import {
  FileText,
  RefreshCw,
  AlertCircle,
  Filter,
  ChevronDown,
} from "lucide-react";
import { cn } from "@/lib/utils";

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

type ContractStatus = "draft" | "published" | "active" | "revoked";

interface Contract {
  contract_id: string;
  contract_family: string;
  project_id: string;
  lifecycle_status: ContractStatus;
  body_hash: string;
  created_at: string;
}

interface Tenant {
  project_id: string;
  display_name: string;
}

interface ContractsResponse {
  contracts?: Contract[];
  items?: Contract[];
}

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

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

const STATUS_CONFIG: Record<
  ContractStatus,
  { label: string; bg: string; text: string; border: string }
> = {
  draft: {
    label: "草稿",
    bg: "bg-[#f4f1e8]",
    text: "text-[#5f5b52]",
    border: "border-[#d8d3c7]",
  },
  published: {
    label: "已發佈",
    bg: "bg-[#eef5ff]",
    text: "text-[#1f5b9b]",
    border: "border-[#9bb6d9]",
  },
  active: {
    label: "生效中",
    bg: "bg-[#f0faf2]",
    text: "text-[#17602a]",
    border: "border-[#9bc7a4]",
  },
  revoked: {
    label: "已撤銷",
    bg: "bg-[#fff0ef]",
    text: "text-[#9f2f25]",
    border: "border-[#e2a29b]",
  },
};

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

function StatusBadge({ status }: { status: ContractStatus }) {
  const config = STATUS_CONFIG[status] ?? STATUS_CONFIG.draft;
  return (
    <span
      className={cn(
        "inline-flex items-center px-2.5 py-0.5 rounded-md text-xs font-medium border",
        config.bg,
        config.text,
        config.border
      )}
    >
      {config.label}
    </span>
  );
}

function ContractRow({ contract }: { contract: Contract }) {
  const formattedDate = contract.created_at
    ? new Date(contract.created_at).toLocaleDateString("zh-TW", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      })
    : "--";

  return (
    <tr className="border-b border-border hover:bg-accent/30 transition-colors">
      <td className="px-4 py-3">
        <span className="text-sm text-foreground font-medium">
          {contract.contract_family || "--"}
        </span>
      </td>
      <td className="px-4 py-3">
        <span className="font-mono text-sm text-muted-foreground">
          {contract.project_id || "--"}
        </span>
      </td>
      <td className="px-4 py-3">
        <StatusBadge status={contract.lifecycle_status} />
      </td>
      <td className="px-4 py-3">
        <span className="font-mono text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded">
          {contract.body_hash ? contract.body_hash.slice(0, 8) : "--"}
        </span>
      </td>
      <td className="px-4 py-3">
        <span className="text-sm text-muted-foreground font-mono">
          {formattedDate}
        </span>
      </td>
    </tr>
  );
}

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

export default function ContractsPage() {
  const [contracts, setContracts] = useState<Contract[]>([]);
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [projectFilter, setProjectFilter] = useState<string>("");

  // 取得租戶清單供篩選
  useEffect(() => {
    fetch(`${API_BASE}/api/v1/platform/tenants`)
      .then((r) => r.json())
      .then((data) => {
        const rows = Array.isArray(data.tenants) ? data.tenants : data.items;
        setTenants(Array.isArray(rows) ? rows : []);
      })
      .catch(() => {});
  }, []);

  const fetchContracts = useCallback(async () => {
    try {
      setError(null);
      setLoading(true);
      const params = new URLSearchParams();
      if (projectFilter) params.set("project_id", projectFilter);
      const res = await fetch(
        `${API_BASE}/api/v1/platform/contracts?${params.toString()}`
      );
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data: ContractsResponse = await res.json();
      const rows = Array.isArray(data.contracts) ? data.contracts : data.items;
      setContracts(Array.isArray(rows) ? rows : []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "載入失敗");
    } finally {
      setLoading(false);
    }
  }, [projectFilter]);

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

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <FileText 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 ? "載入中..." : `共 ${contracts.length} 筆合約版本`}
            </p>
          </div>
        </div>
        <button
          onClick={fetchContracts}
          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>

      {/* Filters */}
      <div className="flex items-center gap-3 border border-[#e0ddd4] bg-white p-4">
        <Filter className="w-4 h-4 text-muted-foreground flex-shrink-0" aria-hidden="true" />
        <span className="text-sm text-muted-foreground">篩選：</span>
        <div className="relative">
          <select
            value={projectFilter}
            onChange={(e) => setProjectFilter(e.target.value)}
            className="appearance-none pl-3 pr-8 py-1.5 text-sm bg-background border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-brand-accent/50 cursor-pointer"
            aria-label="選擇租戶"
          >
            <option value="">所有租戶</option>
            {tenants.map((t) => (
              <option key={t.project_id} value={t.project_id}>
                {t.display_name || t.project_id}
              </option>
            ))}
          </select>
          <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" aria-hidden="true" />
        </div>
      </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">
                  合約類型
                </th>
                <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">
                  Hash
                </th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  建立時間
                </th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                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>
                ))
              ) : contracts.length === 0 && !error ? (
                <tr>
                  <td colSpan={5} className="px-4 py-16 text-center">
                    <FileText className="w-10 h-10 text-muted-foreground/30 mx-auto mb-3" aria-hidden="true" />
                    <p className="text-sm text-muted-foreground">
                      {projectFilter ? "此租戶尚無合約資料" : "尚無合約資料"}
                    </p>
                  </td>
                </tr>
              ) : (
                contracts.map((contract) => (
                  <ContractRow key={contract.contract_id + contract.body_hash} contract={contract} />
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
