'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="relative min-h-full">
      <div className="grain pointer-events-none absolute inset-0" />

      <div className="relative mx-auto max-w-[1280px] px-12 py-16">
        <header className="mb-16 flex items-end justify-between border-b border-[var(--line)] pb-10">
          <div className="flex-1">
            <p className="font-mono text-[11px] uppercase tracking-[0.24em] text-[var(--ink-muted)]">
              ── 02 / Products
            </p>
            <h1 className="mt-4 font-display text-[64px] font-medium leading-[0.95] tracking-[-0.02em] text-[var(--ink)]">
              产品<span className="italic text-[var(--accent)]">目录</span>
            </h1>
            <p className="mt-4 max-w-md text-[14px] leading-relaxed text-[var(--ink-soft)]">
              组织内所有产品的索引。每个产品聚合需求池、发布版本与归属项目。
            </p>
          </div>

          <div className="flex items-center gap-3">
            <div className="relative">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--ink-muted)]" strokeWidth={1.75} />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="搜索产品"
                className="w-56 rounded-md border border-[var(--line)] bg-[var(--bg-elevated)] py-2 pl-9 pr-3 text-[13px] text-[var(--ink)] placeholder:text-[var(--ink-muted)] focus:border-[var(--ink)] focus:outline-none"
              />
            </div>
            <button
              onClick={() => setShowForm(true)}
              className="flex items-center gap-2 rounded-md bg-[var(--ink)] px-4 py-2 text-[13px] font-medium text-[var(--bg)] transition-all hover:bg-[var(--accent)]"
            >
              <Plus className="h-4 w-4" strokeWidth={2} />
              新建产品
            </button>
          </div>
        </header>

        <div className="mb-8 flex items-baseline gap-4">
          <p className="font-mono text-[11px] uppercase tracking-[0.2em] text-[var(--ink-muted)]">
            Showing
          </p>
          <p className="font-display text-[18px] font-semibold tabular-nums text-[var(--ink)]">
            {String(filtered.length).padStart(2, '0')}
          </p>
          <span className="text-[12px] text-[var(--ink-muted)]">/ {String(products.length).padStart(2, '0')} 个产品</span>
        </div>

        {showForm && (
          <div className="mb-10 animate-fade-up rounded-xl border border-[var(--line)] bg-[var(--bg-elevated)] p-8">
            <p className="mb-4 font-mono text-[10px] uppercase tracking-[0.2em] text-[var(--ink-muted)]">── 新建产品</p>
            <ProductForm onSubmit={handleCreate} onCancel={() => setShowForm(false)} />
          </div>
        )}

        {loading ? (
          <div className="py-32 text-center">
            <p className="font-mono text-xs uppercase tracking-[0.2em] text-[var(--ink-muted)]">Loading...</p>
          </div>
        ) : filtered.length === 0 ? (
          <div className="py-32 text-center">
            <p className="font-display text-2xl text-[var(--ink-muted)]">
              {search ? '没有匹配的产品' : '尚未创建任何产品'}
            </p>
            <p className="mt-2 text-[13px] text-[var(--ink-muted)]">
              {search ? '试试其他关键字' : '点击右上角按钮，创建第一个产品'}
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-5 md:grid-cols-2 lg:grid-cols-3">
            {filtered.map((product, idx) => (
              <ProductCard
                key={product.id}
                product={product as any}
                index={idx}
                onClick={(id) => router.push(`/products/${id}`)}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
