'use client';
/**
 * BenchmarksTab — 标杆笔记管理（使用 BenchmarkForm 子组件）
 */
import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { Benchmark, Product } from '@/types/index';
import { PaginatedResponse } from '@/types/index';
import { BenchmarkForm } from './BenchmarkForm';

export function BenchmarksTab() {
  const [products, setProducts] = useState<Product[]>([]);
  const [selectedProductId, setSelectedProductId] = useState<number | null>(null);
  const [benchmarks, setBenchmarks] = useState<Benchmark[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [loading, setLoading] = useState(false);

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

  async function loadProducts() {
    try {
      const data = await api.get<PaginatedResponse<Product>>('/api/v1/products');
      setProducts(data.items);
      if (data.items.length > 0) setSelectedProductId(data.items[0].id);
    } catch { /* ignore */ }
  }

  useEffect(() => {
    if (!selectedProductId) return;
    loadBenchmarks(selectedProductId);
  }, [selectedProductId]);

  async function loadBenchmarks(productId: number) {
    setLoading(true);
    try {
      const data = await api.get<PaginatedResponse<Benchmark>>(
        `/api/v1/products/${productId}/benchmarks`
      );
      setBenchmarks(data.items);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <label htmlFor="benchmark-product" className="text-sm font-medium text-text-primary">
          关联产品
        </label>
        <select id="benchmark-product"
          value={selectedProductId ?? ''}
          onChange={(e) => setSelectedProductId(Number(e.target.value))}
          className="border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange"
        >
          {products.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
        </select>
        <button onClick={() => setShowForm(true)} aria-label="添加标杆笔记"
          className="bg-brand-orange text-white rounded-lg px-3 py-2 text-sm hover:bg-orange-600">
          + 传成品包
        </button>
      </div>

      {loading ? (
        <div className="text-text-secondary text-sm" aria-busy="true">加载中…</div>
      ) : (
        <div className="grid grid-cols-3 gap-4">
          {benchmarks.map((b) => (
            <div key={b.id} className="border border-border-default rounded-xl overflow-hidden bg-surface-primary">
              <img src={b.screenshot_url} alt="标杆笔记截图"
                className="w-full h-32 object-cover bg-surface-tertiary" />
              <div className="p-3">
                <p className="text-xs text-text-secondary line-clamp-2">{b.highlights}</p>
                {b.link_url && (
                  <a href={b.link_url} target="_blank" rel="noopener noreferrer"
                    className="text-xs text-brand-orange hover:underline mt-1 block">查看原帖</a>
                )}
              </div>
            </div>
          ))}
          {benchmarks.length === 0 && (
            <p className="col-span-3 text-text-tertiary text-sm py-4 text-center">
              暂无标杆笔记，点击"传成品包"上传截图
            </p>
          )}
        </div>
      )}

      {showForm && selectedProductId && (
        <BenchmarkForm
          productId={selectedProductId}
          onSaved={() => { setShowForm(false); loadBenchmarks(selectedProductId!); }}
          onCancel={() => setShowForm(false)}
        />
      )}
    </div>
  );
}
