'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Plus, Pencil, Trash2, Package, Eye, Search, Archive } from 'lucide-react';
import { useAuthStore } from '@/store/authStore';

interface Product {
  id: string;
  name: string;
  slug: string;
  price: number;
  stock: number;
  category?: { name: string };
  createdAt: string;
}

export default function SellerProductsPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [deleting, setDeleting] = useState<string | null>(null);
  const { locale } = useParams();

  const fetchProducts = async () => {
    setLoading(true);
    try {
      const res = await api.get('/products/my');
      setProducts(res.data?.data || res.data || []);
    } catch {
      setProducts([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const timer = window.setTimeout(() => { void fetchProducts(); }, 0);
    return () => window.clearTimeout(timer);
  }, []);

  const handleDelete = async (id: string) => {
    if (!confirm('Bạn có chắc muốn xóa sản phẩm này?')) return;
    setDeleting(id);
    try {
      await api.delete(`/products/${id}`);
      setProducts(products.filter(p => p.id !== id));
    } catch {
      alert('Xóa sản phẩm thất bại!');
    } finally {
      setDeleting(null);
    }
  };

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

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-white">Sản phẩm của tôi</h2>
          <p className="text-gray-500 text-sm mt-1">{products.length} sản phẩm đang đăng bán</p>
        </div>
        <Link
          href={`/${locale}/seller/products/create`}
          className="flex items-center gap-2 bg-teal-500 hover:bg-teal-600 text-black font-bold text-sm px-5 py-2.5 rounded-xl transition-colors"
        >
          <Plus className="w-4 h-4" />
          Đăng mới
        </Link>
        <Link href={`/${locale}/seller/inventory`} className="flex items-center gap-2 bg-white/5 hover:bg-white/10 text-white font-bold text-sm px-5 py-2.5 rounded-xl transition-colors">
          <Archive className="w-4 h-4" /> Quản lý kho
        </Link>
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
        <input
          type="text"
          placeholder="Tìm kiếm sản phẩm..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full bg-[#141414] border border-white/10 rounded-xl pl-10 pr-4 py-3 text-white placeholder-gray-500 text-sm focus:outline-none focus:border-teal-500/50"
        />
      </div>

      {/* Products Table */}
      <div className="bg-[#141414] border border-white/5 rounded-2xl overflow-hidden">
        <div className="grid grid-cols-12 gap-4 px-5 py-3 border-b border-white/5 text-xs text-gray-500 font-bold uppercase tracking-wider">
          <div className="col-span-5">Tên sản phẩm</div>
          <div className="col-span-2">Danh mục</div>
          <div className="col-span-2 text-right">Giá</div>
          <div className="col-span-1 text-center">Kho</div>
          <div className="col-span-2 text-right">Thao tác</div>
        </div>

        {loading ? (
          <div className="space-y-0">
            {[1,2,3,4,5].map(i => (
              <div key={i} className="grid grid-cols-12 gap-4 px-5 py-4 border-b border-white/5">
                <div className="col-span-5 h-5 bg-white/5 rounded animate-pulse" />
                <div className="col-span-2 h-5 bg-white/5 rounded animate-pulse" />
                <div className="col-span-2 h-5 bg-white/5 rounded animate-pulse" />
                <div className="col-span-1 h-5 bg-white/5 rounded animate-pulse" />
                <div className="col-span-2 h-5 bg-white/5 rounded animate-pulse" />
              </div>
            ))}
          </div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-gray-500">
            <Package className="w-12 h-12 mb-4 opacity-20" />
            <p className="text-sm font-medium">
              {search ? 'Không tìm thấy sản phẩm phù hợp' : 'Bạn chưa có sản phẩm nào'}
            </p>
            {!search && (
              <Link href={`/${locale}/seller/products/create`} className="mt-3 text-teal-400 text-xs hover:underline">
                + Đăng sản phẩm đầu tiên
              </Link>
            )}
          </div>
        ) : (
          filtered.map((product) => (
            <div
              key={product.id}
              className="grid grid-cols-12 gap-4 px-5 py-4 border-b border-white/5 last:border-0 hover:bg-white/2 transition-colors items-center"
            >
              <div className="col-span-5 flex items-center gap-3">
                <div className="w-9 h-9 rounded-lg bg-white/5 border border-white/5 flex items-center justify-center text-gray-500 shrink-0">
                  <Package className="w-4 h-4" />
                </div>
                <div>
                  <p className="text-white text-sm font-medium line-clamp-1">{product.name}</p>
                  <p className="text-gray-500 text-xs">{product.slug}</p>
                </div>
              </div>
              <div className="col-span-2">
                <span className="text-gray-400 text-xs px-2 py-1 bg-white/5 rounded-lg">
                  {product.category?.name || '—'}
                </span>
              </div>
              <div className="col-span-2 text-right">
                <p className="text-white text-sm font-bold">
                  {Number(product.price).toLocaleString('vi-VN')}đ
                </p>
              </div>
              <div className="col-span-1 text-center">
                <span className={`text-xs font-bold ${(product.stock || 0) > 0 ? 'text-teal-400' : 'text-red-400'}`}>
                  {product.stock ?? '∞'}
                </span>
              </div>
              <div className="col-span-2 flex items-center justify-end gap-2">
                <Link
                  href={`/${locale}/product/${product.slug}`}
                  className="w-7 h-7 rounded-lg bg-white/5 hover:bg-white/10 flex items-center justify-center text-gray-400 hover:text-white transition-colors"
                  title="Xem"
                >
                  <Eye className="w-3.5 h-3.5" />
                </Link>
                <Link
                  href={`/${locale}/seller/products/${product.id}/edit`}
                  className="w-7 h-7 rounded-lg bg-blue-500/10 hover:bg-blue-500/20 flex items-center justify-center text-blue-400 hover:text-blue-300 transition-colors"
                  title="Chỉnh sửa"
                >
                  <Pencil className="w-3.5 h-3.5" />
                </Link>
                <button
                  onClick={() => handleDelete(product.id)}
                  disabled={deleting === product.id}
                  className="w-7 h-7 rounded-lg bg-red-500/10 hover:bg-red-500/20 flex items-center justify-center text-red-400 hover:text-red-300 transition-colors disabled:opacity-50"
                  title="Xóa"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
