'use client';
/**
 * ProductsTab — 产品档案管理
 * 品类不写死（基石A），客户自助加
 */
import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { Product } from '@/types/index';
import { PaginatedResponse } from '@/types/index';
import { ProductCard, ProductForm, ProductsSkeleton } from './ProductSubComponents';

export function ProductsTab() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);

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

  async function loadProducts() {
    setLoading(true);
    try {
      const data = await api.get<PaginatedResponse<Product>>('/api/v1/products');
      setProducts(data.items);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="space-y-6">
      {loading ? (
        <ProductsSkeleton />
      ) : (
        <>
          {/* 内置产品库（preset，平台预置，带参考图，开箱即用） */}
          {products.some((p) => p.source === 'preset') && (
            <section>
              <h3 className="text-sm font-semibold text-text-secondary mb-3">
                内置产品库 <span className="font-normal text-text-tertiary">（平台预置，可直接选用）</span>
              </h3>
              <div className="grid grid-cols-3 gap-4">
                {products.filter((p) => p.source === 'preset').map((p) => (
                  <ProductCard key={p.id} product={p} onUpdated={loadProducts} />
                ))}
              </div>
            </section>
          )}

          {/* 我的产品（custom，自建+上传参考图） */}
          <section>
            <h3 className="text-sm font-semibold text-text-secondary mb-3">
              我的产品 <span className="font-normal text-text-tertiary">（自建，上传产品图后可生图入镜）</span>
            </h3>
            <div className="grid grid-cols-3 gap-4">
              {products.filter((p) => p.source !== 'preset').map((p) => (
                <ProductCard key={p.id} product={p} onUpdated={loadProducts} />
              ))}
              <button
                onClick={() => setShowForm(true)}
                aria-label="添加新产品"
                className="border-2 border-dashed border-border-default rounded-xl p-6 flex flex-col items-center
                           justify-center gap-2 text-text-secondary hover:border-brand-orange hover:text-brand-orange transition-colors"
              >
                <span className="text-2xl" aria-hidden="true">+</span>
                <span className="text-sm">加产品</span>
              </button>
            </div>
          </section>
        </>
      )}

      {showForm && (
        <ProductForm
          onSaved={() => { setShowForm(false); loadProducts(); }}
          onCancel={() => setShowForm(false)}
        />
      )}
    </div>
  );
}
