'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useProductStore } from '@/stores/useProductStore';
import { ProductCard } from '@/components/product/ProductCard';
import { ProductForm } from '@/components/product/ProductForm';

export default function ProductsPage() {
  const router = useRouter();
  const { products, loading, fetchProducts, createProduct } = useProductStore();
  const [showForm, setShowForm] = useState(false);

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

  const handleCreate = async (data: { name: string; description: string }) => {
    await createProduct(data);
    setShowForm(false);
  };

  return (
    <div className="mx-auto max-w-6xl px-6 py-8">
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">产品列表</h1>
        <button
          onClick={() => setShowForm(true)}
          className="rounded-md bg-blue-600 px-4 py-2 text-sm text-white hover:bg-blue-700"
        >
          新建产品
        </button>
      </div>

      {showForm && (
        <div className="mb-6 rounded-lg border border-gray-200 p-6">
          <h2 className="mb-4 text-lg font-medium">新建产品</h2>
          <ProductForm onSubmit={handleCreate} onCancel={() => setShowForm(false)} />
        </div>
      )}

      {loading ? (
        <div className="py-12 text-center text-gray-400">加载中...</div>
      ) : products.length === 0 ? (
        <div className="py-12 text-center text-gray-400">暂无产品，点击上方按钮创建</div>
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {products.map((product) => (
            <ProductCard
              key={product.id}
              product={product}
              onClick={(id) => router.push(`/products/${id}`)}
            />
          ))}
        </div>
      )}
    </div>
  );
}
