'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Search } from 'lucide-react';
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);
  const [search, setSearch] = useState('');

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

  const filtered = products.filter((p) =>
    p.name.toLowerCase().includes(search.toLowerCase()),
  );

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

  return (
    <div className="flex h-full flex-col">
      <header className="flex h-14 shrink-0 items-center justify-between border-b border-[var(--line)] bg-[var(--bg-card)] px-6">
        <div className="flex items-center gap-2.5">
          <h1 className="text-[15px] font-semibold tracking-tight text-[var(--ink)]">产品</h1>
          <span className="rounded-md bg-[var(--bg-subtle)] px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-[var(--ink-soft)]">
            {products.length}
          </span>
        </div>
        <button
          onClick={() => setShowForm(true)}
          className="flex h-8 items-center gap-1.5 rounded-lg bg-[var(--accent)] px-3 text-[13px] font-medium text-white shadow-[var(--shadow-sm)] transition-colors hover:bg-[var(--accent-hover)]"
        >
          <Plus className="h-3.5 w-3.5" strokeWidth={2.5} />
          新建产品
        </button>
      </header>

      <div className="flex-1 overflow-y-auto">
        <div className="mx-auto max-w-[1400px] p-6">
          <div className="mb-5 flex items-center gap-2">
            <div className="relative max-w-xs flex-1">
              <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--ink-muted)]" strokeWidth={2} />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="搜索产品名称"
                className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] pl-8 pr-3 text-[13px] text-[var(--ink)] placeholder:text-[var(--ink-muted)] focus:border-[var(--accent)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-ring)]"
              />
            </div>
          </div>

          {showForm && (
            <div className="mb-5 rounded-2xl border border-[var(--line)] bg-[var(--bg-card)] p-6 shadow-[var(--shadow-sm)]">
              <h2 className="mb-4 text-[14px] font-semibold text-[var(--ink)]">新建产品</h2>
              <ProductForm onSubmit={handleCreate} onCancel={() => setShowForm(false)} />
            </div>
          )}

          {loading ? (
            <div className="py-20 text-center text-[13px] text-[var(--ink-muted)]">加载中…</div>
          ) : filtered.length === 0 ? (
            <div className="rounded-2xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] py-20 text-center">
              <p className="text-[14px] font-medium text-[var(--ink-soft)]">
                {search ? '没有找到匹配的产品' : '尚未创建任何产品'}
              </p>
              <p className="mt-1.5 text-[12.5px] text-[var(--ink-muted)]">
                {search ? '尝试其他关键字' : '点击右上角"新建产品"开始'}
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
              {filtered.map((product) => (
                <ProductCard
                  key={product.id}
                  product={product as any}
                  onClick={(id) => router.push(`/products/${id}`)}
                />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
