"use client";

import { useState } from "react";
import { useScopeEffect } from "@/lib/company-scope";
import {Plus } from "lucide-react";
import { listOKRs } from "@/lib/api-v2";
import { PageContainer, Badge, Card } from "@/components/shared/PageContainer";
import { LoadingSpinner } from "@/components/shared/LoadingSpinner";
import { EmptyState } from "@/components/shared/EmptyState";

/** OKR 关键结果项。 */
interface KeyResult {
  title?: string;
  objective?: string;
  progress?: number;
}

/** OKR 项。 */
interface OKRItem {
  quarter: string;
  objective: string;
  alignment_score?: number;
  status: string;
  key_results?: KeyResult[];
}

export default function OKRsPage() {
  const [items, setItems] = useState<OKRItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useScopeEffect(() => {
    listOKRs()
      .then((resp) => setItems((resp.data as OKRItem[]) ?? []))
      .catch(() => setItems([]))
      .finally(() => setIsLoading(false));
  });

  return (
    <PageContainer
      title="OKR 管理"
      description="投资人与创始人共同制定 OKR + AI 对齐度评分 + 偏差预警"
      actions={
        <button className="flex items-center gap-1 rounded-md bg-gray-900 px-3 py-1.5 text-sm text-white hover:bg-gray-700">
          <Plus size={16} /> 新建 OKR
        </button>
      }
    >
      {isLoading ? (
        <LoadingSpinner />
      ) : items.length === 0 ? (
        <EmptyState description="暂无 OKR" />
      ) : (
        <div className="space-y-3">
          {items.map((item, i) => (
            <Card key={i}>
              <div className="flex items-center justify-between">
                <div>
                  <Badge color="blue">{item.quarter}</Badge>
                  <h3 className="mt-1 font-medium text-gray-900">{item.objective}</h3>
                </div>
                <div className="flex items-center gap-2">
                  {item.alignment_score != null && (
                    <Badge color={item.alignment_score >= 75 ? "green" : "amber"}>
                      对齐度 {item.alignment_score}
                    </Badge>
                  )}
                  <Badge color={item.status === "active" ? "green" : "gray"}>{item.status}</Badge>
                </div>
              </div>
              {Array.isArray(item.key_results) && (
                <div className="mt-2 space-y-1">
                  {item.key_results.map((kr, ki) => (
                    <div key={ki} className="flex items-center gap-2 text-sm text-gray-600">
                      <span className="h-1.5 w-1.5 rounded-full bg-gray-400" />
                      {String(kr.title ?? kr.objective ?? kr)}
                      {kr.progress != null && <span className="text-gray-400">({kr.progress}%)</span>}
                    </div>
                  ))}
                </div>
              )}
            </Card>
          ))}
        </div>
      )}
    </PageContainer>
  );
}
