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

"use client";

import { useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import { Link } from "@/i18n/routing";
import {
  ArrowRight,
  FileText,
  RefreshCw,
  AlertCircle,
  Filter,
  ChevronDown,
  ClipboardCheck,
  ShieldCheck,
  GitBranch,
} 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>
  );
}

function SecurityContractCandidatePanel() {
  const t = useTranslations("awooop.contracts.securityContractCandidate");
  const metrics = [
    {
      label: t("metrics.totalContracts"),
      value: "36",
      detail: t("metrics.totalContractsDetail"),
    },
    {
      label: t("metrics.readyForMirror"),
      value: "33",
      detail: t("metrics.readyForMirrorDetail"),
    },
    {
      label: t("metrics.partialReady"),
      value: "2",
      detail: t("metrics.partialReadyDetail"),
    },
    {
      label: t("metrics.activeRuntimeGates"),
      value: "0",
      detail: t("metrics.activeRuntimeGatesDetail"),
    },
  ];
  const contracts = [
    {
      name: "security_mirror_status_rollup_v1",
      detail: t("contractRefs.statusRollup"),
    },
    {
      name: "iwooos_posture_projection_v1",
      detail: t("contractRefs.postureProjection"),
    },
    {
      name: "source_control_owner_response_validation_rollup_v1",
      detail: t("contractRefs.ownerValidation"),
    },
    {
      name: "security_rollout_policy_v1",
      detail: t("contractRefs.rolloutPolicy"),
    },
  ];

  return (
    <section className="overflow-hidden border border-[#e0ddd4] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
        <div className="flex items-start gap-2">
          <ShieldCheck className="mt-0.5 h-4 w-4 text-[#d97757]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#77736a]">{t("subtitle")}</p>
          </div>
        </div>
        <span className="inline-flex border border-[#9bb6d9] bg-[#eef5ff] px-2 py-0.5 text-xs font-semibold text-[#1f5b9b]">
          {t("badge")}
        </span>
      </div>

      <div className="grid gap-px bg-[#e0ddd4] md:grid-cols-2 xl:grid-cols-4">
        {metrics.map((item) => (
          <div key={item.label} className="bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#77736a]">{item.label}</p>
            <p className="mt-2 font-mono text-2xl font-semibold text-[#141413]">{item.value}</p>
            <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{item.detail}</p>
          </div>
        ))}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="min-w-0 border border-[#e0ddd4] bg-white">
          <div className="border-b border-[#e0ddd4] bg-[#faf9f3] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("contractRefsTitle")}
          </div>
          <div className="divide-y divide-[#eee9dd]">
            {contracts.map((item) => (
              <div key={item.name} className="px-4 py-3">
                <p className="break-all font-mono text-xs font-semibold text-[#141413]">{item.name}</p>
                <p className="mt-1 text-xs leading-5 text-[#5f5b52]">{item.detail}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="min-w-0 border border-[#e0ddd4] bg-[#faf9f3] px-4 py-3">
          <p className="text-xs font-semibold text-[#77736a]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 text-xs leading-5 text-[#5f5b52]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
            <span>contract_publish_authorized=false</span>
            <span>contract_mutation_authorized=false</span>
            <span>runtime_execution_authorized=false</span>
            <span>action_buttons_allowed=false</span>
          </div>
          <Link
            href="/iwooos"
            className="mt-4 inline-flex items-center gap-2 border border-[#d8d3c7] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#d97757]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#77736a]" aria-hidden="true" />
          </Link>
        </div>
      </div>
    </section>
  );
}

function GitHubPrimaryReadinessContractCandidatePanel() {
  const t = useTranslations("awooop.contracts.githubPrimaryReadinessCandidate");
  const metrics = [
    {
      label: t("metrics.candidateRepos"),
      value: "8",
      detail: t("metrics.candidateReposDetail"),
    },
    {
      label: t("metrics.inScopeRepos"),
      value: "7",
      detail: t("metrics.inScopeReposDetail"),
    },
    {
      label: t("metrics.primaryReady"),
      value: "0",
      detail: t("metrics.primaryReadyDetail"),
    },
    {
      label: t("metrics.ownerResponses"),
      value: "0/22",
      detail: t("metrics.ownerResponsesDetail"),
    },
    {
      label: t("metrics.workflowInventory"),
      value: "0/7",
      detail: t("metrics.workflowInventoryDetail"),
    },
  ];
  const contracts = [
    {
      name: "source_control_primary_readiness_gate_v1",
      detail: t("contractRefs.primaryReadiness"),
    },
    {
      name: "source_control_owner_response_validation_rollup_v1",
      detail: t("contractRefs.ownerValidation"),
    },
    {
      name: "source_control_primary_rollback_adr_v1",
      detail: t("contractRefs.rollbackAdr"),
    },
    {
      name: "source_control_workflow_secret_name_inventory_v1",
      detail: t("contractRefs.workflowInventory"),
    },
    {
      name: "iwooos_posture_projection_v1",
      detail: t("contractRefs.postureProjection"),
    },
  ];

  return (
    <section className="overflow-hidden border border-[#d7e2e0] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#d7e2e0] bg-[#f5fbf9] px-4 py-3">
        <div className="flex items-start gap-2">
          <GitBranch className="mt-0.5 h-4 w-4 text-[#2f7d72]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#5f6f6b]">{t("subtitle")}</p>
          </div>
        </div>
        <span className="inline-flex border border-[#8bb9b0] bg-white px-2 py-0.5 text-xs font-semibold text-[#1f6b61]">
          {t("badge")}
        </span>
      </div>

      <div className="grid gap-px bg-[#d7e2e0] md:grid-cols-2 xl:grid-cols-5">
        {metrics.map((item) => (
          <div key={item.label} className="bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#5f6f6b]">{item.label}</p>
            <p className="mt-2 font-mono text-2xl font-semibold text-[#141413]">{item.value}</p>
            <p className="mt-2 text-xs leading-5 text-[#4f5f5b]">{item.detail}</p>
          </div>
        ))}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="min-w-0 border border-[#d7e2e0] bg-white">
          <div className="border-b border-[#d7e2e0] bg-[#f5fbf9] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("contractRefsTitle")}
          </div>
          <div className="divide-y divide-[#e3eeec]">
            {contracts.map((item) => (
              <div key={item.name} className="px-4 py-3">
                <p className="break-all font-mono text-xs font-semibold text-[#141413]">{item.name}</p>
                <p className="mt-1 text-xs leading-5 text-[#4f5f5b]">{item.detail}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="min-w-0 border border-[#d7e2e0] bg-[#f5fbf9] px-4 py-3">
          <p className="text-xs font-semibold text-[#5f6f6b]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 text-xs leading-5 text-[#4f5f5b]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
            <span>repo_creation_authorized=false</span>
            <span>refs_mutation_authorized=false</span>
            <span>secret_value_collection_allowed=false</span>
            <span>github_primary_switch_authorized=false</span>
            <span>gitea_disablement_authorized=false</span>
            <span>runtime_execution_authorized=false</span>
            <span>action_buttons_allowed=false</span>
          </div>
          <Link
            href="/iwooos"
            className="mt-4 inline-flex items-center gap-2 border border-[#8bb9b0] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#2f7d72]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#5f6f6b]" aria-hidden="true" />
          </Link>
        </div>
      </div>
    </section>
  );
}

function OwnerResponseValidationContractCandidatePanel() {
  const t = useTranslations("awooop.contracts.ownerResponseValidationCandidate");
  const metrics = [
    {
      label: t("metrics.packets"),
      value: "4",
      detail: t("metrics.packetsDetail"),
    },
    {
      label: t("metrics.templates"),
      value: "22",
      detail: t("metrics.templatesDetail"),
    },
    {
      label: t("metrics.received"),
      value: "0",
      detail: t("metrics.receivedDetail"),
    },
    {
      label: t("metrics.accepted"),
      value: "0",
      detail: t("metrics.acceptedDetail"),
    },
    {
      label: t("metrics.displaySections"),
      value: "8",
      detail: t("metrics.displaySectionsDetail"),
    },
  ];
  const contracts = [
    {
      name: "source_control_owner_response_validation_rollup_v1",
      detail: t("contractRefs.validationRollup"),
    },
    {
      name: "gitea_inventory_owner_attestation_response_v1",
      detail: t("contractRefs.giteaAttestation"),
    },
    {
      name: "github_target_owner_decision_response_v1",
      detail: t("contractRefs.githubTarget"),
    },
    {
      name: "source_control_ref_truth_owner_response_v1",
      detail: t("contractRefs.refsTruth"),
    },
    {
      name: "source_control_workflow_secret_name_owner_response_v1",
      detail: t("contractRefs.workflowSecret"),
    },
  ];

  return (
    <section className="overflow-hidden border border-[#ded8e8] bg-white">
      <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[#ded8e8] bg-[#fbf8ff] px-4 py-3">
        <div className="flex items-start gap-2">
          <ClipboardCheck className="mt-0.5 h-4 w-4 text-[#7561a8]" aria-hidden="true" />
          <div>
            <h3 className="text-sm font-semibold text-[#141413]">{t("title")}</h3>
            <p className="mt-1 max-w-3xl text-xs leading-5 text-[#665f73]">{t("subtitle")}</p>
          </div>
        </div>
        <span className="inline-flex border border-[#b7aad6] bg-white px-2 py-0.5 text-xs font-semibold text-[#5e4b93]">
          {t("badge")}
        </span>
      </div>

      <div className="grid gap-px bg-[#ded8e8] md:grid-cols-2 xl:grid-cols-5">
        {metrics.map((item) => (
          <div key={item.label} className="bg-white px-4 py-3">
            <p className="text-xs font-semibold text-[#665f73]">{item.label}</p>
            <p className="mt-2 font-mono text-2xl font-semibold text-[#141413]">{item.value}</p>
            <p className="mt-2 text-xs leading-5 text-[#585260]">{item.detail}</p>
          </div>
        ))}
      </div>

      <div className="grid min-w-0 gap-4 p-4 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="min-w-0 border border-[#ded8e8] bg-white">
          <div className="border-b border-[#ded8e8] bg-[#fbf8ff] px-4 py-3 text-xs font-semibold text-[#141413]">
            {t("contractRefsTitle")}
          </div>
          <div className="divide-y divide-[#ece7f3]">
            {contracts.map((item) => (
              <div key={item.name} className="px-4 py-3">
                <p className="break-all font-mono text-xs font-semibold text-[#141413]">{item.name}</p>
                <p className="mt-1 text-xs leading-5 text-[#585260]">{item.detail}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="min-w-0 border border-[#ded8e8] bg-[#fbf8ff] px-4 py-3">
          <p className="text-xs font-semibold text-[#665f73]">{t("boundaryLabel")}</p>
          <p className="mt-2 text-sm font-semibold text-[#141413]">{t("boundaryTitle")}</p>
          <p className="mt-2 text-xs leading-5 text-[#585260]">{t("boundaryDetail")}</p>
          <div className="mt-4 grid gap-2 break-all font-mono text-xs text-[#141413]">
            <span>owner_response_validation_received_count=0</span>
            <span>owner_response_validation_accepted_count=0</span>
            <span>approval_record_created=false</span>
            <span>repo_creation_authorized=false</span>
            <span>refs_sync_authorized=false</span>
            <span>workflow_modification_authorized=false</span>
            <span>secret_value_collection_allowed=false</span>
            <span>github_primary_switch_authorized=false</span>
            <span>runtime_execution_authorized=false</span>
            <span>action_buttons_allowed=false</span>
          </div>
          <Link
            href="/iwooos"
            className="mt-4 inline-flex items-center gap-2 border border-[#b7aad6] bg-white px-3 py-1.5 text-xs font-semibold text-[#141413] hover:border-[#7561a8]"
          >
            {t("openIwooos")}
            <ArrowRight className="h-3.5 w-3.5 text-[#665f73]" aria-hidden="true" />
          </Link>
        </div>
      </div>
    </section>
  );
}

// =============================================================================
// 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>

      <SecurityContractCandidatePanel />
      <GitHubPrimaryReadinessContractCandidatePanel />
      <OwnerResponseValidationContractCandidatePanel />

      {/* 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">
                  專案 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">
                  建立時間
                </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>
  );
}
