"use client";

import { useState } from "react";
import {Sparkles } from "lucide-react";
import { discoverInnovation } from "@/lib/api-v2";
import { useCompanyScope } from "@/lib/company-scope";
import { PageContainer, Card } from "@/components/shared/PageContainer";
import { EmptyState } from "@/components/shared/EmptyState";
import { toast } from "sonner";

/** 创新机会项。 */
interface InnovationResult {
  title: string;
  combined_capability: string;
  market_analysis?: string;
}

export default function InnovationPage() {
  const { companyName } = useCompanyScope();
  const [capabilities, setCapabilities] = useState("");
  const [results, setResults] = useState<InnovationResult[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  const handleDiscover = async () => {
    if (!capabilities.trim()) {
      toast.error("请输入 Portfolio 企业能力描述");
      return;
    }
    setIsLoading(true);
    try {
      const resp = await discoverInnovation(capabilities);
      setResults((resp.data as InnovationResult[]) ?? []);
    } catch {
      toast.error("分析失败");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <PageContainer
      title="组合创新实验室"
      description={companyName ? `${companyName} — AI 分析企业能力组合 → 发现联合产品方案` : "AI 分析企业能力组合 → 发现联合产品方案"}
    >
      <Card>
        <textarea
          value={capabilities}
          onChange={(e) => setCapabilities(e.target.value)}
          placeholder="输入 Portfolio 内企业能力描述..."
          className="w-full rounded-md border border-gray-300 p-3 text-sm"
          rows={4}
        />
        <button
          onClick={handleDiscover}
          disabled={isLoading}
          className="mt-2 flex items-center gap-1 rounded-md bg-gray-900 px-3 py-1.5 text-sm text-white hover:bg-gray-700 disabled:opacity-50"
        >
          <Sparkles size={16} /> {isLoading ? "分析中..." : "发现创新机会"}
        </button>
      </Card>

      {results.length > 0 && (
        <div className="space-y-3">
          {results.map((item, i) => (
            <Card key={i}>
              <h3 className="font-medium text-gray-900">{item.title}</h3>
              <p className="mt-1 text-sm text-gray-600">{item.combined_capability}</p>
              {item.market_analysis && <p className="mt-1 text-xs text-gray-400">{item.market_analysis}</p>}
            </Card>
          ))}
        </div>
      )}
      {results.length === 0 && !isLoading && capabilities && (
        <EmptyState description="点击按钮开始分析" />
      )}
    </PageContainer>
  );
}
