import React, { useState } from 'react';
import Swal from 'sweetalert2';
import { useStore } from '../context/StoreContext';
import { Product, ProductCategory } from '../types';
import { ProductFormModal } from '../components/ProductFormModal';
import { PaginationControl } from '../components/PaginationControl';
import { SearchableSelect } from '../components/SearchableSelect';
import { PackageSearch, Plus, Search, Filter, Edit, Trash2, Barcode, Layers, AlertTriangle, CheckCircle, Tag } from 'lucide-react';

export const ProductsPage: React.FC = () => {
  const { db, deleteProduct } = useStore();
  const [selectedCategory, setSelectedCategory] = useState<string>('Semua');
  const [searchQuery, setSearchQuery] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const categoriesList = ['Semua', ...(db.categories || []).map(c => c.name)];

  // Filter Products
  const filteredProducts = db.products.filter(p => {
    const matchesCategory = selectedCategory === 'Semua' || p.category === selectedCategory;
    const queryLower = searchQuery.toLowerCase().trim();
    if (!queryLower) return matchesCategory;

    const matchesName = p.name.toLowerCase().includes(queryLower);
    const matchesDesc = p.description?.toLowerCase().includes(queryLower);
    const matchesVariant = p.variants.some(v => 
      v.variantName.toLowerCase().includes(queryLower) ||
      v.barcode.includes(queryLower)
    );

    return matchesCategory && (matchesName || matchesDesc || matchesVariant);
  });

  // Calculate pagination
  const totalPages = Math.ceil(filteredProducts.length / pageSize);
  const paginatedProducts = filteredProducts.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  const handleCategoryChange = (cat: string) => {
    setSelectedCategory(cat);
    setCurrentPage(1);
  };

  const handleSearchChange = (q: string) => {
    setSearchQuery(q);
    setCurrentPage(1);
  };

  const handleOpenAddModal = () => {
    setEditingProduct(null);
    setIsModalOpen(true);
  };

  const handleOpenEditModal = (product: Product) => {
    setEditingProduct(product);
    setIsModalOpen(true);
  };

  const handleDeleteProduct = (product: Product) => {
    Swal.fire({
      title: 'Hapus Barang?',
      text: `Apakah Anda yakin ingin menghapus barang "${product.name}" beserta semua variannya?`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#e11d48',
      cancelButtonColor: '#64748b',
      confirmButtonText: 'Ya, Hapus!',
      cancelButtonText: 'Batal'
    }).then((result) => {
      if (result.isConfirmed) {
        deleteProduct(product.id);
        Swal.fire({
          icon: 'success',
          title: 'Berhasil Dihapus!',
          text: `Barang "${product.name}" telah dihapus.`,
          timer: 1500,
          showConfirmButton: false
        });
      }
    });
  };

  return (
    <div className="space-y-6">
      
      {/* Header Bar */}
      <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-2xs flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2">
            <PackageSearch className="w-6 h-6 text-emerald-600" />
            <h2 className="text-xl font-bold text-slate-900">Katalog Barang & Varian Ukuran</h2>
          </div>
          <p className="text-xs text-slate-500 mt-1">
            Kelola daftar sembako, varian ukuran, harga jual & grosir, serta kode barcode unik.
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <button
            onClick={handleOpenAddModal}
            className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl shadow-md flex items-center justify-center gap-2 transition"
          >
            <Plus className="w-4 h-4" /> Tambah Barang Baru
          </button>
        </div>
      </div>

      {/* Search & Category Filter Controls */}
      <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-2xs">
        <div className="flex flex-col sm:flex-row gap-3">
          
          {/* Category Select Filter */}
          <div className="sm:w-64">
            <SearchableSelect
              options={categoriesList.map(cat => ({
                value: cat,
                label: cat === 'Semua' ? 'Semua Kategori' : cat
              }))}
              value={selectedCategory}
              onChange={(val) => handleCategoryChange(val)}
              placeholder="Pilih Kategori..."
              searchPlaceholder="Cari Kategori..."
            />
          </div>

          {/* Search Bar */}
          <div className="relative flex-1">
            <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => handleSearchChange(e.target.value)}
              placeholder="Cari nama barang, varian (cth: 500 ML), atau barcode..."
              className="w-full pl-10 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs font-medium focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white"
            />
          </div>

        </div>
      </div>

      {/* PRODUCTS LIST GRID */}
      {filteredProducts.length === 0 ? (
        <div className="bg-white border border-slate-200 rounded-2xl p-12 text-center space-y-3">
          <div className="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mx-auto text-slate-400">
            <PackageSearch className="w-6 h-6" />
          </div>
          <h3 className="font-bold text-slate-800 text-sm">Barang Tidak Ditemukan</h3>
          <p className="text-xs text-slate-500 max-w-sm mx-auto">
            Tidak ada data barang sembako yang cocok dengan kata kunci pencarian atau kategori ini.
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {paginatedProducts.map((product) => (
            <div key={product.id} className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-2xs hover:border-slate-300 transition">
              
              {/* Product Header Row */}
              <div className="bg-slate-50 border-b border-slate-200 px-6 py-3.5 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <div className="flex items-center gap-3">
                  <span className="px-2.5 py-1 bg-emerald-100 text-emerald-800 text-[10px] font-extrabold rounded-full">
                    {product.category}
                  </span>
                  <div>
                    <h3 className="font-bold text-slate-900 text-base leading-snug">{product.name}</h3>
                    {product.description && (
                      <p className="text-xs text-slate-500">{product.description}</p>
                    )}
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleOpenEditModal(product)}
                    className="px-3 py-1.5 bg-white border border-slate-200 text-slate-700 hover:bg-slate-100 rounded-xl text-xs font-semibold flex items-center gap-1 transition"
                  >
                    <Edit className="w-3.5 h-3.5 text-slate-500" /> Edit Barang
                  </button>
                  <button
                    onClick={() => handleDeleteProduct(product)}
                    className="p-1.5 bg-white border border-slate-200 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-xl transition"
                    title="Hapus Barang"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>

              {/* Product Variants Table */}
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead className="bg-slate-50/50 text-slate-500 font-bold border-b border-slate-100">
                    <tr>
                      <th className="p-3 pl-6">Varian & Ukuran</th>
                      <th className="p-3">Kode Barcode</th>
                      <th className="p-3">Harga Beli (Modal)</th>
                      <th className="p-3">Harga Eceran</th>
                      <th className="p-3">Harga Grosir / Reseller</th>
                      <th className="p-3">Keuntungan (Margin)</th>
                      <th className="p-3 pr-6">Stok & Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {product.variants.map((v) => {
                      const margin = v.sellPrice - v.buyPrice;
                      const isLowStock = v.stock <= v.minStock;
                      const isOutOfStock = v.stock <= 0;

                      return (
                        <tr key={v.id} className="hover:bg-slate-50/80 transition">
                          <td className="p-3 pl-6 font-bold text-slate-900">
                            {v.variantName}
                            <span className="text-slate-400 font-normal ml-1 text-[11px]">
                              ({v.size} {v.unit})
                            </span>
                          </td>

                          <td className="p-3 font-mono text-slate-600">
                            <span className="inline-flex items-center gap-1 bg-slate-100 px-2 py-0.5 rounded font-bold text-[11px]">
                              <Barcode className="w-3 h-3 text-slate-500" /> {v.barcode}
                            </span>
                          </td>

                          <td className="p-3 font-medium text-slate-700">
                            Rp {v.buyPrice.toLocaleString('id-ID')}
                          </td>

                          <td className="p-3 font-bold text-emerald-700">
                            <div>
                              <span>Rp {v.sellPrice.toLocaleString('id-ID')}</span>
                              {v.tierPrices && v.tierPrices.length > 0 && (
                                <div className="mt-1 space-y-0.5">
                                  {v.tierPrices.map((t, tIdx) => (
                                    <span key={tIdx} className="block text-[10px] bg-amber-100 text-amber-900 px-1.5 py-0.5 rounded font-semibold w-fit border border-amber-200">
                                      🏷️ {t.label || (t.priceType === 'unit' 
                                        ? `Beli ≥${t.minQty}: @Rp ${t.price.toLocaleString('id-ID')}` 
                                        : `Beli ${t.minQty}: Rp ${t.price.toLocaleString('id-ID')}`
                                      )}
                                    </span>
                                  ))}
                                </div>
                              )}
                            </div>
                          </td>

                          <td className="p-3 font-bold text-indigo-700">
                            {v.wholesalePrice ? `Rp ${v.wholesalePrice.toLocaleString('id-ID')}` : '-'}
                          </td>

                          <td className="p-3">
                            <span className="font-bold text-teal-600">
                              +Rp {margin.toLocaleString('id-ID')}
                            </span>
                          </td>

                          <td className="p-3 pr-6">
                            <span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold ${
                              isOutOfStock
                                ? 'bg-rose-100 text-rose-800'
                                : isLowStock
                                ? 'bg-amber-100 text-amber-900'
                                : 'bg-emerald-100 text-emerald-800'
                            }`}>
                              {isLowStock && <AlertTriangle className="w-3 h-3" />}
                              {v.stock} {v.unit}
                            </span>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

            </div>
          ))}

          {/* Pagination Control */}
          <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-2xs">
            <PaginationControl
              currentPage={currentPage}
              totalPages={totalPages}
              pageSize={pageSize}
              totalItems={filteredProducts.length}
              onPageChange={setCurrentPage}
              onPageSizeChange={setPageSize}
            />
          </div>
        </div>
      )}

      {/* Product Form Modal */}
      <ProductFormModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        productToEdit={editingProduct}
      />

    </div>
  );
};
