import React, { useState } from 'react';
import { ShoppingBag, Edit3, Trash2, Plus, Search, Package, Tag, Star, Truck, Grid, List, BarChart2, Filter, X } from 'lucide-react';
import { Product } from '../../types';

interface ProductManagerProps {
  products: Product[];
  setEditingItem: (item: any) => void;
  canAccess: (section: string, action?: 'view' | 'edit' | 'delete') => boolean;
  showToast: (msg: string, type: 'success' | 'error') => void;
  deleteItem: (table: string, id: string) => void;
  getBanglaName: (bn: string | undefined, en: string) => string;
}

const ProductQRButton: React.FC<{ product: any; getBanglaName: any }> = ({ product, getBanglaName }) => {
  const [open, setOpen] = React.useState(false);
  const [downloading, setDownloading] = React.useState(false);
  const qrValue = String(product.id);
  const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=${encodeURIComponent(qrValue)}&bgcolor=ffffff&color=000000&margin=10&format=png`;
  const displayName = getBanglaName(product.nameBangla, product.name);

  const handlePrint = () => {
    const win = window.open('', '_blank', 'width=420,height=560');
    if (win) {
      win.document.write(`<html><head><title>QR - ${product.name}</title>
        <style>body{font-family:Arial,sans-serif;text-align:center;padding:24px}img{width:220px;height:220px;display:block;margin:0 auto 14px;border:1px solid #eee;border-radius:8px}h2{font-size:15px;margin:0 0 4px;color:#111}p{font-size:11px;color:#555;margin:3px 0}.id{font-size:9px;color:#999;margin-top:6px;font-family:monospace}</style>
        </head><body>
        <img src="${qrUrl}" />
        <h2>${displayName}</h2>
        <p>${product.name}</p><p>৳${product.price}</p>
        <p class="id">ID: ${qrValue}</p>
        </body></html>`);
      win.document.close();
      win.focus();
      setTimeout(() => { win.print(); win.close(); }, 400);
    }
  };

  const handleDownload = async () => {
    try {
      setDownloading(true);
      const res = await fetch(qrUrl);
      const blob = await res.blob();
      const blobUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = blobUrl;
      a.download = `QR-${product.id}.png`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(blobUrl);
    } catch (e) { console.error(e); }
    finally { setDownloading(false); }
  };

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        title="QR Code"
        className="w-8 h-8 bg-white/90 backdrop-blur-sm rounded-xl flex items-center justify-center shadow-md hover:bg-indigo-600 hover:text-white text-indigo-600 transition-all text-[10px] font-black"
      >
        QR
      </button>

      {/* Full-screen modal popup */}
      {open && (
        <div
          className="fixed inset-0 z-[9999] flex items-center justify-center p-4"
          style={{ background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)' }}
          onClick={() => setOpen(false)}
        >
          <div
            className="bg-white rounded-3xl shadow-2xl w-full max-w-sm overflow-hidden"
            onClick={e => e.stopPropagation()}
          >
            {/* Modal Header */}
            <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
              <div>
                <h3 className="font-black text-base text-black">QR Code</h3>
                <p className="text-[11px] text-slate-500 mt-0.5 line-clamp-1 font-bold">{displayName}</p>
              </div>
              <button
                onClick={() => setOpen(false)}
                className="w-8 h-8 flex items-center justify-center rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-500 transition-all"
              >
                <X size={16} />
              </button>
            </div>

            {/* QR Image */}
            <div className="p-6 flex flex-col items-center gap-4">
              <div className="w-56 h-56 rounded-2xl overflow-hidden border-2 border-slate-100 shadow-inner bg-slate-50 flex items-center justify-center">
                <img src={qrUrl} alt="QR Code" className="w-full h-full object-contain" />
              </div>

              {/* Product info */}
              <div className="text-center">
                <p className="text-xs font-black text-black">{displayName}</p>
                <p className="text-[10px] text-slate-400 font-bold mt-0.5">ID: {qrValue}</p>
                <p className="text-sm font-black text-indigo-600 mt-1">৳{product.price}</p>
              </div>

              {/* Action Buttons */}
              <div className="flex gap-3 w-full">
                <button
                  onClick={handlePrint}
                  className="flex-1 flex items-center justify-center gap-2 py-3 bg-slate-900 hover:bg-slate-700 text-white rounded-2xl text-sm font-black transition-all"
                >
                  🖨️ Print
                </button>
                <button
                  onClick={handleDownload}
                  disabled={downloading}
                  className="flex-1 flex items-center justify-center gap-2 py-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-2xl text-sm font-black transition-all disabled:opacity-60"
                >
                  {downloading ? '⏳ ...' : '⬇️ Download'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};


export default function ProductManager({
  products, setEditingItem, canAccess, showToast, deleteItem, getBanglaName
}: ProductManagerProps) {
  const [search, setSearch] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');

  // Collect unique categories
  const categories = ['all', ...Array.from(new Set(products.map(p => p.category).filter(Boolean) as string[]))];

  const filtered = products.filter(p => {
    const matchCat = categoryFilter === 'all' || p.category === categoryFilter;
    const q = search.toLowerCase();
    const matchSearch = !q ||
      p.name?.toLowerCase().includes(q) ||
      (p.nameBangla || '').includes(q) ||
      (p.category || '').toLowerCase().includes(q);
    return matchCat && matchSearch;
  });

  const getPriceConfigs = (p: Product) => {
    try {
      return typeof p.priceConfigs === 'string' ? JSON.parse(p.priceConfigs as any) : (p.priceConfigs || {});
    } catch { return {}; }
  };

  const getLowestPrice = (p: Product) => {
    const pc = getPriceConfigs(p);
    const prices = Object.values(pc).map((c: any) => c.salePrice).filter(Boolean) as number[];
    return prices.length > 0 ? Math.min(...prices) : p.price;
  };

  const getFreeDelivery = (p: Product) => {
    const pc = getPriceConfigs(p);
    return Object.values(pc).some((c: any) => c.freeDelivery);
  };

  const totalRevenue = products.reduce((sum, p) => sum + (p.price || 0), 0);
  const featuredCount = products.filter(p => p.isFeatured).length;
  const freeDeliveryCount = products.filter(p => getFreeDelivery(p)).length;

  return (
    <div className="space-y-6 pb-10">

      {/* ── PAGE HEADER ── */}
      <div
        className="relative overflow-hidden rounded-3xl p-7 flex flex-col sm:flex-row sm:items-center justify-between gap-5"
        style={{
          background: 'linear-gradient(135deg, #0f0c1d 0%, #1a1245 50%, #0f0c1d 100%)',
          border: '1px solid rgba(124,58,237,0.25)',
        }}
      >
        {/* Background glow */}
        <div className="absolute top-0 left-1/3 w-64 h-32 rounded-full opacity-20 blur-3xl" style={{ background: 'radial-gradient(circle, #7c3aed, transparent)' }} />
        <div className="flex items-center gap-4 relative z-10">
          <div
            className="w-14 h-14 rounded-2xl flex items-center justify-center shrink-0 shadow-2xl"
            style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 0 28px rgba(124,58,237,0.5)' }}
          >
            <ShoppingBag size={26} className="text-white" />
          </div>
          <div>
            <h2 className="text-2xl font-black text-white tracking-tight">Inventory</h2>
            <p className="text-sm text-violet-300 mt-0.5">Manage products, categories, and stock.</p>
          </div>
        </div>

        {/* Stats pills */}
        <div className="flex flex-wrap items-center gap-2 relative z-10">
          <div className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-black" style={{ background: 'rgba(124,58,237,0.2)', color: '#c4b5fd', border: '1px solid rgba(124,58,237,0.25)' }}>
            <Package size={12} />{products.length} Products
          </div>
          <div className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-black" style={{ background: 'rgba(234,179,8,0.15)', color: '#fde047', border: '1px solid rgba(234,179,8,0.2)' }}>
            <Star size={12} />{featuredCount} Featured
          </div>
          <div className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-black" style={{ background: 'rgba(34,197,94,0.15)', color: '#86efac', border: '1px solid rgba(34,197,94,0.2)' }}>
            <Truck size={12} />{freeDeliveryCount} Free Delivery
          </div>
          {canAccess('products', 'edit') && (
            <button
              onClick={() => setEditingItem({
                id: `P-${Date.now()}`,
                name: '', nameBangla: '', price: 0, image: '',
                category: 'Basic', highlight: '', description: '',
                isFeatured: false, sizes: [], priceConfigs: {}
              })}
              className="flex items-center gap-2 px-5 py-2 rounded-2xl text-sm font-black text-white shadow-xl transition-all hover:scale-105 active:scale-95"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 4px 20px rgba(124,58,237,0.4)' }}
            >
              <Plus size={16} /> Add Product
            </button>
          )}
        </div>
      </div>

      {/* ── SEARCH + FILTER BAR ── */}
      <div className="bg-white rounded-2xl border border-slate-100 shadow-sm p-4 flex flex-col sm:flex-row gap-3 items-center">
        {/* Search */}
        <div className="relative flex-1 w-full">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
          <input
            type="text"
            placeholder="Search by name or category..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="w-full pl-10 pr-10 py-2.5 bg-slate-50 rounded-xl text-sm font-bold outline-none focus:ring-2 focus:ring-violet-400 text-black placeholder-slate-400 transition-all"
          />
          {search && (
            <button onClick={() => setSearch('')} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-700">
              <X size={15} />
            </button>
          )}
        </div>

        {/* Category filter */}
        <div className="flex gap-1.5 flex-wrap">
          {categories.map(cat => (
            <button
              key={cat}
              onClick={() => setCategoryFilter(cat)}
              className={`px-3 py-1.5 rounded-xl text-xs font-black transition-all ${categoryFilter === cat
                ? 'bg-violet-600 text-white shadow-lg shadow-violet-600/20'
                : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}
            >
              {cat === 'all' ? '🗂 All' : cat}
            </button>
          ))}
        </div>

        {/* View mode toggle */}
        <div className="flex items-center gap-1 bg-slate-100 rounded-xl p-1">
          <button
            onClick={() => setViewMode('grid')}
            className={`p-2 rounded-lg transition-all ${viewMode === 'grid' ? 'bg-white shadow-sm text-violet-600' : 'text-slate-400 hover:text-slate-700'}`}
          >
            <Grid size={16} />
          </button>
          <button
            onClick={() => setViewMode('list')}
            className={`p-2 rounded-lg transition-all ${viewMode === 'list' ? 'bg-white shadow-sm text-violet-600' : 'text-slate-400 hover:text-slate-700'}`}
          >
            <List size={16} />
          </button>
        </div>
      </div>

      {/* Results count */}
      {search || categoryFilter !== 'all' ? (
        <p className="text-xs font-black text-slate-500 px-1">
          {filtered.length} result{filtered.length !== 1 ? 's' : ''} {search ? `for "${search}"` : ''} {categoryFilter !== 'all' ? `in "${categoryFilter}"` : ''}
        </p>
      ) : null}

      {/* ── PRODUCTS GRID / LIST ── */}
      {filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-24 bg-white rounded-3xl border border-dashed border-slate-200">
          <div className="w-16 h-16 bg-violet-50 rounded-2xl flex items-center justify-center mb-4">
            <Package size={28} className="text-violet-400" />
          </div>
          <p className="text-base font-black text-slate-600">No products found</p>
          <p className="text-sm text-slate-400 mt-1">Try changing your search or filter</p>
          {canAccess('products', 'edit') && (
            <button
              onClick={() => setEditingItem({ id: `P-${Date.now()}`, name: '', nameBangla: '', price: 0, image: '', category: 'Basic', highlight: '', description: '', isFeatured: false, sizes: [], priceConfigs: {} })}
              className="mt-5 flex items-center gap-2 px-5 py-2.5 rounded-2xl text-sm font-black text-white"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)' }}
            >
              <Plus size={16} /> Add First Product
            </button>
          )}
        </div>
      ) : viewMode === 'grid' ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
          {filtered.map(p => {
            const pc = getPriceConfigs(p);
            const sizes = Object.keys(pc);
            const hasFreeDelivery = getFreeDelivery(p);
            const lowestPrice = getLowestPrice(p);

            return (
              <div
                key={p.id}
                className="group bg-white rounded-3xl overflow-hidden border border-slate-100 shadow-sm hover:shadow-xl hover:-translate-y-1 transition-all duration-300"
              >
                {/* Image */}
                <div className="relative aspect-square overflow-hidden bg-gradient-to-br from-slate-50 to-slate-100">
                  {p.image
                    ? <img src={p.image} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" alt={p.name} />
                    : (
                      <div className="absolute inset-0 flex items-center justify-center">
                        <Package size={40} className="text-slate-300" />
                      </div>
                    )
                  }

                  {/* Badges */}
                  <div className="absolute top-3 left-3 flex flex-col gap-1.5">
                    {p.isFeatured && (
                      <span className="flex items-center gap-1 text-[9px] font-black px-2 py-1 rounded-full text-yellow-700 bg-yellow-100 border border-yellow-200">
                        <Star size={8} fill="currentColor" /> Featured
                      </span>
                    )}
                    {hasFreeDelivery && (
                      <span className="flex items-center gap-1 text-[9px] font-black px-2 py-1 rounded-full text-green-700 bg-green-100 border border-green-200">
                        <Truck size={8} /> Free Delivery
                      </span>
                    )}
                  </div>

                  {/* Action buttons on hover */}
                  <div className="absolute top-3 right-3 flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-all duration-200 translate-x-2 group-hover:translate-x-0">
                    <button
                      onClick={() => canAccess('products', 'edit') ? setEditingItem(p) : showToast('Access denied', 'error')}
                      title="Edit Product"
                      className="w-8 h-8 bg-white/90 backdrop-blur-sm rounded-xl flex items-center justify-center shadow-md hover:bg-violet-600 hover:text-white text-violet-600 transition-all"
                    >
                      <Edit3 size={14} />
                    </button>
                    <ProductQRButton product={p} getBanglaName={getBanglaName} />
                    {canAccess('products', 'delete') && (
                      <button
                        onClick={() => deleteItem('products', p.id)}
                        title="Delete Product"
                        className="w-8 h-8 bg-white/90 backdrop-blur-sm rounded-xl flex items-center justify-center shadow-md hover:bg-red-600 hover:text-white text-red-500 transition-all"
                      >
                        <Trash2 size={14} />
                      </button>
                    )}
                  </div>
                </div>

                {/* Info */}
                <div className="p-4">
                  <h3 className="text-sm font-black text-slate-900 line-clamp-1 font-bangla">{getBanglaName(p.nameBangla, p.name)}</h3>
                  <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider mt-0.5 line-clamp-1">{p.name}</p>

                  <div className="flex items-center justify-between mt-3">
                    <div>
                      <p className="text-lg font-black text-slate-900">৳{lowestPrice.toLocaleString()}</p>
                      {p.category && (
                        <span className="text-[9px] font-black text-violet-600 bg-violet-50 px-2 py-0.5 rounded-full border border-violet-100">
                          {p.category}
                        </span>
                      )}
                    </div>
                    {sizes.length > 0 && (
                      <div className="flex flex-wrap gap-1 justify-end max-w-[100px]">
                        {sizes.slice(0, 3).map(s => (
                          <span key={s} className="text-[8px] font-black bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded-md">
                            {s}
                          </span>
                        ))}
                        {sizes.length > 3 && (
                          <span className="text-[8px] font-black bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded-md">+{sizes.length - 3}</span>
                        )}
                      </div>
                    )}
                  </div>

                  {/* Quick edit footer */}
                  <button
                    onClick={() => canAccess('products', 'edit') ? setEditingItem(p) : showToast('Access denied', 'error')}
                    className="mt-3 w-full py-2 rounded-xl text-xs font-black text-violet-600 bg-violet-50 hover:bg-violet-100 border border-violet-100 transition-all flex items-center justify-center gap-1.5"
                  >
                    <Edit3 size={12} /> Edit Product
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        /* LIST VIEW */
        <div className="bg-white rounded-3xl border border-slate-100 shadow-sm overflow-hidden">
          <table className="w-full">
            <thead className="bg-slate-50 border-b border-slate-100">
              <tr className="text-[10px] font-black uppercase text-slate-500 tracking-wider">
                <th className="px-5 py-4 text-left">Product</th>
                <th className="px-4 py-4 text-left">Category</th>
                <th className="px-4 py-4 text-left">Price</th>
                <th className="px-4 py-4 text-left">Variations</th>
                <th className="px-4 py-4 text-left">Badges</th>
                <th className="px-4 py-4 text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((p, idx) => {
                const pc = getPriceConfigs(p);
                const sizes = Object.keys(pc);
                const hasFreeDelivery = getFreeDelivery(p);
                return (
                  <tr key={p.id} className={`border-t border-slate-50 hover:bg-violet-50/30 transition-colors ${idx % 2 === 0 ? '' : 'bg-slate-50/40'}`}>
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-3">
                        <div className="w-11 h-11 rounded-xl overflow-hidden bg-slate-100 shrink-0">
                          {p.image
                            ? <img src={p.image} className="w-full h-full object-cover" alt={p.name} />
                            : <div className="w-full h-full flex items-center justify-center"><Package size={16} className="text-slate-300" /></div>
                          }
                        </div>
                        <div>
                          <p className="text-sm font-black text-black line-clamp-1 font-bangla">{getBanglaName(p.nameBangla, p.name)}</p>
                          <p className="text-[10px] text-slate-400 font-bold">{p.name}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-[10px] font-black text-violet-600 bg-violet-50 px-2 py-1 rounded-lg border border-violet-100">
                        {p.category || '—'}
                      </span>
                    </td>
                    <td className="px-4 py-3 font-black text-slate-900">৳{getLowestPrice(p).toLocaleString()}</td>
                    <td className="px-4 py-3">
                      {sizes.length > 0 ? (
                        <div className="flex flex-wrap gap-1">
                          {sizes.slice(0, 4).map(s => (
                            <span key={s} className="text-[9px] font-black bg-slate-100 text-slate-600 px-2 py-0.5 rounded-md">{s}</span>
                          ))}
                          {sizes.length > 4 && <span className="text-[9px] font-bold text-slate-400">+{sizes.length - 4}</span>}
                        </div>
                      ) : <span className="text-[10px] text-slate-400">—</span>}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex gap-1 flex-wrap">
                        {p.isFeatured && <span className="text-[9px] font-black px-2 py-0.5 rounded-full text-yellow-700 bg-yellow-100">⭐ Featured</span>}
                        {hasFreeDelivery && <span className="text-[9px] font-black px-2 py-0.5 rounded-full text-green-700 bg-green-100">🚚 Free</span>}
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1.5">
                        <button
                          onClick={() => canAccess('products', 'edit') ? setEditingItem(p) : showToast('Access denied', 'error')}
                          className="px-3 py-1.5 rounded-xl text-[10px] font-black text-violet-600 bg-violet-50 hover:bg-violet-600 hover:text-white transition-all border border-violet-100 flex items-center gap-1"
                        >
                          <Edit3 size={11} /> Edit
                        </button>
                        <ProductQRButton product={p} getBanglaName={getBanglaName} />
                        {canAccess('products', 'delete') && (
                          <button
                            onClick={() => deleteItem('products', p.id)}
                            className="p-1.5 rounded-xl text-red-500 hover:bg-red-600 hover:text-white transition-all border border-red-100 bg-red-50"
                          >
                            <Trash2 size={14} />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
