'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { Package, Search, Eye, EyeOff, MoreVertical, Boxes, AlertTriangle, Loader2, Trash2, X, Star, Settings2, Tags, Pencil, Plus, Save } from 'lucide-react';
import { useAuthStore } from '@/store/authStore';

export default function AdminProductsPage() {
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [categories, setCategories] = useState<any[]>([]);
  const [categoryOpen, setCategoryOpen] = useState(false);
  const [categorySaving, setCategorySaving] = useState(false);
  const [editingCategory, setEditingCategory] = useState<any | null>(null);
  const [categoryForm, setCategoryForm] = useState({ name: '', slug: '', parentId: '' });
  const [purgeOpen, setPurgeOpen] = useState(false);
  const [purgeConfirmation, setPurgeConfirmation] = useState('');
  const [purging, setPurging] = useState(false);
  const [purgeError, setPurgeError] = useState('');
  const token = useAuthStore((s) => s.token);

  const fetchProducts = async () => {
    if (!token) return;
    setLoading(true);
    try {
      const res = await api.get('/admin/products', {
        params: { search }
      });
      const data = res.data?.data || res.data || [];
      setProducts(data.filter((p: any) => (!statusFilter || p.status === statusFilter) && (!categoryFilter || p.categoryId === categoryFilter)));
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      fetchProducts();
    }, search ? 250 : 0);
    return () => clearTimeout(delayDebounceFn);
  }, [search, statusFilter, categoryFilter, token]);

  const fetchCategories = async () => {
    try {
      const response = await api.get('/categories/flat');
      setCategories(response.data || []);
    } catch (error) {
      console.error(error);
    }
  };

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

  const openNewCategory = () => {
    setEditingCategory(null);
    setCategoryForm({ name: '', slug: '', parentId: '' });
  };
  const openEditCategory = (category: any) => {
    setEditingCategory(category);
    setCategoryForm({ name: category.name || '', slug: category.slug || '', parentId: category.parentId || '' });
  };
  const saveCategory = async () => {
    if (!categoryForm.name.trim() || !categoryForm.slug.trim()) return alert('Tên và slug danh mục là bắt buộc.');
    setCategorySaving(true);
    try {
      const payload = { ...categoryForm, parentId: categoryForm.parentId || undefined };
      if (editingCategory) await api.patch(`/categories/${editingCategory.id}`, payload);
      else await api.post('/categories', payload);
      await fetchCategories();
      openNewCategory();
    } catch (error: any) {
      alert(error.response?.data?.message || 'Không thể lưu danh mục.');
    } finally { setCategorySaving(false); }
  };
  const deleteCategory = async (category: any) => {
    if (!confirm(`Xóa danh mục “${category.name}”?`)) return;
    try {
      await api.delete(`/categories/${category.id}`);
      await fetchCategories();
      if (editingCategory?.id === category.id) openNewCategory();
    } catch (error: any) { alert(error.response?.data?.message || 'Không thể xóa danh mục.'); }
  };

  const handleToggleStatus = async (id: string, currentStatus: string) => {
    if (!token) return;
    const newStatus = currentStatus === 'ACTIVE' ? 'HIDDEN' : 'ACTIVE';
    const msg = newStatus === 'HIDDEN' ? 'Bạn có chắc muốn ẨN sản phẩm này?' : 'Bạn có chắc muốn HIỆN sản phẩm này?';

    if (!confirm(msg)) return;

    try {
      await api.patch(`/admin/products/${id}/status`, { status: newStatus });
      fetchProducts();
    } catch {
      alert('Cập nhật trạng thái thất bại');
    }
  };

  const handlePurgeMarketplace = async () => {
    if (purgeConfirmation !== 'XOA TOAN BO MARKETPLACE') return;
    setPurging(true);
    setPurgeError('');
    try {
      await api.delete('/admin/products/purge', { data: { confirmation: purgeConfirmation } });
      setPurgeOpen(false);
      setPurgeConfirmation('');
      await fetchProducts();
      alert('Đã xóa toàn bộ dữ liệu marketplace. Tài khoản và ví vẫn được giữ lại.');
    } catch (error: any) {
      setPurgeError(error.response?.data?.message || 'Không thể xóa dữ liệu marketplace.');
    } finally {
      setPurging(false);
    }
  };
  const handleFeature = async (product: any) => { try { await api.patch(`/admin/products/${product.id}/featured`, { isFeatured: !product.isFeatured }); await fetchProducts(); } catch { alert('Không thể cập nhật sản phẩm nổi bật'); } };
  const handleDeleteProduct = async (product: any) => { if (!confirm(`Xóa sản phẩm "${product.name}"?`)) return; try { await api.delete(`/admin/products/${product.id}`); await fetchProducts(); } catch (error: any) { alert(error.response?.data?.message || 'Không thể xóa sản phẩm'); } };

  const summary = {
    total: products.length,
    active: products.filter((p) => p.status === 'ACTIVE').length,
    hidden: products.filter((p) => p.status === 'HIDDEN').length,
    lowStock: products.filter((p) => Number(p.stock || 0) < 5).length,
  };

  return (
    <div className="space-y-5">
      <div className="flex flex-col gap-4 border-b border-white/10 pb-4 xl:flex-row xl:items-center xl:justify-between">
        <div>
          <h1 className="flex items-center gap-2 text-xl font-black text-white"><Package className="h-5 w-5 text-primary" /> Products</h1>
          <p className="text-gray-500 text-sm mt-1">Giám sát tồn kho, trạng thái hiển thị và seller phát hành sản phẩm.</p>
        </div>
        <div className="flex flex-wrap gap-2"><button onClick={() => { setCategoryOpen(true); openNewCategory(); }} className="inline-flex items-center gap-2 rounded-lg border border-cyan-500/30 bg-cyan-500/10 px-3 py-2.5 text-xs font-bold text-cyan-200 hover:bg-cyan-500/20"><Settings2 className="h-4 w-4" /> Cài đặt danh mục</button><button onClick={() => { setPurgeOpen(true); setPurgeConfirmation(''); setPurgeError(''); }} className="inline-flex items-center gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2.5 text-xs font-bold text-red-300 hover:bg-red-500/20"><Trash2 className="h-4 w-4" /> Xóa marketplace</button></div>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        {[{ label: 'Tổng sản phẩm', value: summary.total, icon: Boxes }, { label: 'Đang hiển thị', value: summary.active, icon: Eye }, { label: 'Đã ẩn', value: summary.hidden, icon: EyeOff }, { label: 'Sắp hết hàng', value: summary.lowStock, icon: AlertTriangle }].map((item, index) => {
          const Icon = item.icon;
          return (
            <div key={index} className="rounded-2xl border border-white/10 bg-[#141414] p-4">
              <div className="flex items-center justify-between">
                <p className="text-sm text-gray-500">{item.label}</p>
                <Icon className="h-4 w-4 text-gray-400" />
              </div>
              <p className="mt-3 text-2xl font-black text-white">{item.value}</p>
            </div>
          );
        })}
      </div>

      <section className="rounded-xl border border-white/10 bg-[#111214] p-3 sm:p-4">
      <div className="mb-3 flex items-center gap-2 border-b border-white/10 pb-3 text-sm font-black uppercase tracking-wide text-white"><Search className="h-4 w-4 text-primary" /> Bộ lọc tìm kiếm</div>
      <div className="flex flex-col gap-3 md:flex-row">
        <div className="relative flex-1">
          <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 sản phẩm theo tên..."
            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-red-500/50"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="bg-[#141414] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-red-500/50"
        >
          <option value="">Tất cả trạng thái</option>
          <option value="ACTIVE">ACTIVE</option>
          <option value="HIDDEN">HIDDEN</option>
        </select>
        <select value={categoryFilter} onChange={(e) => setCategoryFilter(e.target.value)} className="bg-[#141414] border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-primary/50">
          <option value="">Tất cả danh mục</option>
          {categories.map((category) => <option key={category.id} value={category.id}>{category.name}</option>)}
        </select>
      </div>
      </section>

      <div className="bg-[#111214] border border-white/10 rounded-xl overflow-x-auto">
        <div className="min-w-[1180px]">
        <div className="grid grid-cols-12 gap-3 px-4 py-3 border-b border-white/10 text-[10px] text-gray-500 font-bold uppercase tracking-wider bg-black/30">
          <div className="col-span-3">Sản phẩm</div><div className="col-span-2">Danh mục</div><div className="col-span-1 text-center">Trạng thái</div><div className="col-span-2 text-right">Giá bán / Kho</div><div className="col-span-1 text-center">Nổi bật</div><div className="col-span-2">Seller</div><div className="col-span-1 text-right">Thao tác</div>
        </div>

        {loading ? (
          <div className="py-20 text-center text-gray-500">Đang tải dữ liệu...</div>
        ) : products.length === 0 ? (
          <div className="py-20 text-center text-gray-500">Không tìm thấy sản phẩm nào</div>
        ) : (
          products.map((p) => (
            <div key={p.id} className="grid grid-cols-12 gap-3 px-4 py-3 border-b border-white/5 last:border-0 hover:bg-white/[0.035] transition-colors items-center">
              <div className="col-span-3 flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center text-gray-400 shrink-0">
                  <Package className="w-5 h-5" />
                </div>
                <div>
                  <p className="text-white text-sm font-bold line-clamp-1">{p.name}</p>
                  <p className="text-gray-500 text-xs">{p.category?.name || 'Không rõ danh mục'}</p>
                </div>
              </div>
              <div className="col-span-2"><span className="rounded bg-emerald-500/10 px-2 py-1 text-[10px] font-bold text-emerald-300">{p.category?.name || 'Chưa phân loại'}</span><p className="mt-1 text-[10px] text-gray-600">{p.slug}</p></div>
              <div className="col-span-1 flex justify-center"><button onClick={() => handleToggleStatus(p.id, p.status)} className={`relative h-5 w-9 rounded-full transition ${p.status === 'ACTIVE' ? 'bg-emerald-500' : 'bg-gray-600'}`} title={p.status === 'ACTIVE' ? 'Ấn để ẩn sản phẩm' : 'Ấn để hiện sản phẩm'}><span className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition ${p.status === 'ACTIVE' ? 'left-4' : 'left-0.5'}`} /></button></div>
              <div className="col-span-2 text-right">
                <p className="text-red-300 text-sm font-black">{Number(p.price).toLocaleString('vi-VN')}đ</p><p className={`text-xs font-bold ${Number(p.stock || 0) > 0 ? 'text-emerald-400' : 'text-red-400'}`}>Kho: {p.stock ?? 0}</p>
              </div>
              <div className="col-span-1 flex justify-center">{p.isFeatured ? <span className="flex h-7 w-7 items-center justify-center rounded-full bg-amber-400/10 text-amber-300"><Star className="h-4 w-4 fill-current" /></span> : <span className="text-[10px] text-gray-600">—</span>}</div>
              <div className="col-span-2"><p className="text-emerald-400 text-xs font-bold">{p.seller?.name || 'Ẩn danh'}</p><p className="text-gray-500 text-[10px] truncate">{p.seller?.email || '—'}</p></div>
              <div className="col-span-1 flex justify-end gap-1">
                <button onClick={() => void handleFeature(p)} className={`flex h-8 w-8 items-center justify-center rounded-lg transition-colors ${p.isFeatured ? 'bg-amber-400/15 text-amber-300' : 'text-gray-400 hover:bg-white/10'}`} title={p.isFeatured ? 'Gỡ sản phẩm nổi bật' : 'Đưa lên sản phẩm nổi bật'}><Star className={`h-4 w-4 ${p.isFeatured ? 'fill-current' : ''}`} /></button>
                <button
                  onClick={() => handleToggleStatus(p.id, p.status)}
                  className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-white/10 text-gray-400 transition-colors"
                  title={p.status === 'ACTIVE' ? 'Ẩn sản phẩm' : 'Hiện sản phẩm'}
                >
                  <MoreVertical className="w-4 h-4" />
                </button>
                <button onClick={() => void handleDeleteProduct(p)} className="flex h-8 w-8 items-center justify-center rounded-lg text-red-300 hover:bg-red-500/10" title="Xóa sản phẩm"><Trash2 className="h-4 w-4" /></button>
              </div>
            </div>
          ))
        )}
        </div>
      </div>

      {categoryOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-4">
          <div className="max-h-[90vh] w-full max-w-5xl overflow-y-auto rounded-xl border border-white/10 bg-[#111214] p-5 shadow-2xl">
            <div className="flex items-start justify-between gap-4 border-b border-white/10 pb-4"><div><h2 className="flex items-center gap-2 text-lg font-black text-white"><Tags className="h-5 w-5 text-cyan-300" /> Cài đặt danh mục sản phẩm</h2><p className="mt-1 text-sm text-gray-500">Thêm, sửa hoặc xóa danh mục. Danh mục đang có sản phẩm sẽ không thể bị xóa.</p></div><button onClick={() => setCategoryOpen(false)} className="text-gray-500 hover:text-white"><X /></button></div>
            <div className="mt-5 grid gap-5 lg:grid-cols-[1fr_360px]">
              <div className="overflow-hidden rounded-xl border border-white/10"><div className="grid grid-cols-[1fr_150px_90px] gap-3 border-b border-white/10 bg-black/20 px-4 py-3 text-[10px] font-bold uppercase tracking-wide text-gray-500"><span>Danh mục</span><span>Sản phẩm</span><span className="text-right">Thao tác</span></div>{categories.length ? categories.map((category) => <div key={category.id} className="grid grid-cols-[1fr_150px_90px] items-center gap-3 border-b border-white/5 px-4 py-3 last:border-0"><div><p className="font-bold text-white">{category.name}</p><p className="mt-0.5 font-mono text-[10px] text-gray-500">{category.slug}</p></div><span className="text-xs text-gray-400">{category._count?.products || 0} sản phẩm</span><div className="flex justify-end gap-1"><button onClick={() => openEditCategory(category)} className="rounded-lg p-2 text-cyan-300 hover:bg-cyan-500/10" title="Sửa"><Pencil className="h-4 w-4" /></button><button onClick={() => void deleteCategory(category)} className="rounded-lg p-2 text-red-300 hover:bg-red-500/10" title="Xóa"><Trash2 className="h-4 w-4" /></button></div></div>) : <p className="p-8 text-center text-sm text-gray-500">Chưa có danh mục.</p>}</div>
              <div className="rounded-xl border border-cyan-500/20 bg-cyan-500/[0.035] p-4"><div className="flex items-center justify-between"><h3 className="font-black text-white">{editingCategory ? 'Sửa danh mục' : 'Thêm danh mục'}</h3>{editingCategory && <button onClick={openNewCategory} className="text-xs text-cyan-300">Tạo mới</button>}</div><label className="mt-4 block text-xs font-bold text-gray-400">Tên danh mục<input value={categoryForm.name} onChange={(e) => setCategoryForm((value) => ({ ...value, name: e.target.value }))} className="mt-1.5 w-full rounded-lg border border-white/10 bg-black/25 px-3 py-2.5 text-sm text-white outline-none focus:border-cyan-400" placeholder="Ví dụ: Tài khoản mạng xã hội" /></label><label className="mt-3 block text-xs font-bold text-gray-400">Slug<input value={categoryForm.slug} onChange={(e) => setCategoryForm((value) => ({ ...value, slug: e.target.value.toLowerCase().replace(/\s+/g, '-') }))} className="mt-1.5 w-full rounded-lg border border-white/10 bg-black/25 px-3 py-2.5 font-mono text-sm text-white outline-none focus:border-cyan-400" placeholder="tai-khoan-mang-xa-hoi" /></label><label className="mt-3 block text-xs font-bold text-gray-400">Danh mục cha (tùy chọn)<select value={categoryForm.parentId} onChange={(e) => setCategoryForm((value) => ({ ...value, parentId: e.target.value }))} className="mt-1.5 w-full rounded-lg border border-white/10 bg-black/25 px-3 py-2.5 text-sm text-white outline-none focus:border-cyan-400"><option value="">Không có</option>{categories.filter((category) => category.id !== editingCategory?.id).map((category) => <option key={category.id} value={category.id}>{category.name}</option>)}</select></label><button disabled={categorySaving} onClick={() => void saveCategory()} className="mt-5 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-cyan-500 px-4 py-2.5 text-sm font-black text-black hover:bg-cyan-400 disabled:opacity-50">{categorySaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}{editingCategory ? 'Lưu thay đổi' : 'Thêm danh mục'}</button></div>
            </div>
          </div>
        </div>
      )}

      {purgeOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-4">
          <div className="w-full max-w-lg rounded-2xl border border-red-500/30 bg-[#18191d] p-6 shadow-2xl">
            <div className="flex items-start justify-between gap-4"><div className="flex gap-3"><div className="rounded-xl bg-red-500/15 p-3 text-red-300"><AlertTriangle className="h-6 w-6" /></div><div><h2 className="text-lg font-black text-white">Xóa toàn bộ marketplace</h2><p className="mt-1 text-sm text-gray-400">Không thể hoàn tác sau khi xác nhận.</p></div></div><button onClick={() => setPurgeOpen(false)} disabled={purging} className="text-gray-500 hover:text-white"><X /></button></div>
            <div className="mt-5 rounded-xl border border-red-500/20 bg-red-500/5 p-4 text-sm leading-6 text-red-100">Thao tác này xóa tất cả sản phẩm, kho ZIP, đơn hàng, lịch sử đơn hàng, tranh chấp và hồ sơ gian hàng của mọi seller. Tài khoản người dùng và số dư ví không bị xóa.</div>
            <label className="mt-5 block text-sm font-semibold text-white">Gõ <code className="rounded bg-black/30 px-1.5 py-0.5 text-red-300">XOA TOAN BO MARKETPLACE</code> để xác nhận<input autoFocus value={purgeConfirmation} onChange={(event) => setPurgeConfirmation(event.target.value)} className="mt-2 w-full rounded-xl border border-white/10 bg-black/30 px-4 py-3 font-mono text-sm text-white outline-none focus:border-red-400" /></label>
            {purgeError && <p className="mt-3 text-sm text-red-300">{purgeError}</p>}
            <div className="mt-6 flex justify-end gap-3"><button onClick={() => setPurgeOpen(false)} disabled={purging} className="rounded-xl border border-white/10 px-4 py-2.5 text-sm font-bold text-gray-300 hover:bg-white/5">Hủy</button><button onClick={handlePurgeMarketplace} disabled={purging || purgeConfirmation !== 'XOA TOAN BO MARKETPLACE'} className="inline-flex items-center gap-2 rounded-xl bg-red-600 px-4 py-2.5 text-sm font-bold text-white hover:bg-red-500 disabled:cursor-not-allowed disabled:opacity-40">{purging && <Loader2 className="h-4 w-4 animate-spin" />}Xóa vĩnh viễn</button></div>
          </div>
        </div>
      )}
    </div>
  );
}
