'use client';

import React, { useEffect, useState } from 'react';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import {
  RefreshCw,
  ShoppingBag,
  Database,
  Search,
  Plus,
  Edit2,
  Trash2,
  Upload,
  X,
} from 'lucide-react';
import CategoriesIcon from '@/components/icons/CategoriesIcon';

interface Variant {
  id: string;
  name: string;
  price: number;
  stockQuantity: number | null;
  stockStatus: string;
}

interface Product {
  id: string;
  name: string;
  description: string | null;
  sku: string | null;
  price: number;
  currency: string;
  stockQuantity: number | null;
  stockStatus: string;
  imageUrl: string | null;
  sourceSystem: string;
  variants: Variant[];
}

interface Category {
  id: string;
  name: string;
  sourceSystem: string;
  externalCategoryId: string;
  parentId: string | null;
}

interface SyncLog {
  id: string;
  syncType: string;
  status: string;
  recordsProcessed: number;
  recordsFailed: number;
  errorMessage: string | null;
  startedAt: string;
  completedAt: string | null;
}

export default function ProductsPage() {
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState<'products' | 'categories'>('products');
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [syncLogs, setSyncLogs] = useState<SyncLog[]>([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);

  // Modals state
  const [isProductModalOpen, setIsProductModalOpen] = useState(false);
  const [isCategoryModalOpen, setIsCategoryModalOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [isUploading, setIsUploading] = useState(false);

  // Forms state
  const [productForm, setProductForm] = useState({
    name: '',
    sku: '',
    price: '',
    description: '',
    stockQuantity: '',
    stockStatus: 'instock',
    imageUrl: '',
    category: '',
    syncTarget: 'all',
  });

  const [categoryForm, setCategoryForm] = useState({
    name: '',
    parentId: '',
  });

  useEffect(() => {
    loadData();
  }, [user?.id, user?.subscriptionStatus]);

  async function loadData() {
    if (!user || user.subscriptionStatus === 'UNSUBSCRIBED' || user.subscriptionStatus === 'EXPIRED') {
      setLoading(false);
      return;
    }
    try {
      const [prodsData, logsData, catsData] = await Promise.all([
        apiRequest('api/products'),
        apiRequest('api/products/sync-logs'),
        apiRequest('api/categories'),
      ]);
      setProducts(prodsData);
      setSyncLogs(logsData);
      setCategories(catsData);

      // Check if last log is still running
      if (logsData.length > 0 && logsData[0].status === 'RUNNING') {
        setSyncing(true);
        // Start polling
        setTimeout(pollSyncStatus, 3000);
      }
    } catch (err) {
      console.error('Failed to load catalog data:', err);
    } finally {
      setLoading(false);
    }
  }

  const pollSyncStatus = async () => {
    try {
      const logsData = await apiRequest('api/products/sync-logs');
      setSyncLogs(logsData);
      
      if (logsData.length > 0 && logsData[0].status === 'RUNNING') {
        setTimeout(pollSyncStatus, 3000);
      } else {
        setSyncing(false);
        // Reload products and categories lists once finished
        const [prodsData, catsData] = await Promise.all([
          apiRequest('api/products'),
          apiRequest('api/categories'),
        ]);
        setProducts(prodsData);
        setCategories(catsData);
      }
    } catch (err) {
      console.error('Failed polling sync status:', err);
      setSyncing(false);
    }
  };

  const handleSyncTrigger = async () => {
    setSyncing(true);
    try {
      await apiRequest('api/products/sync', 'POST');
      loadData();
    } catch (err: any) {
      alert(`Sync failed to start: ${err.message}`);
      setSyncing(false);
    }
  };

  // Product Form handlers
  const openAddProductModal = () => {
    setEditingProduct(null);
    setProductForm({
      name: '',
      sku: '',
      price: '',
      description: '',
      stockQuantity: '',
      stockStatus: 'instock',
      imageUrl: '',
      category: '',
      syncTarget: 'all',
    });
    setIsProductModalOpen(true);
  };

  const openEditProductModal = (product: Product) => {
    setEditingProduct(product);
    const desc = product.description || '';
    const match = desc.match(/\n\nCategory:\s*(.+)$/);
    const category = match ? match[1] : '';
    const cleanDesc = desc.replace(/\n\nCategory:\s*(.+)$/, '').trim();

    setProductForm({
      name: product.name,
      sku: product.sku || '',
      price: String(product.price),
      description: cleanDesc,
      stockQuantity: product.stockQuantity !== null ? String(product.stockQuantity) : '',
      stockStatus: product.stockStatus,
      imageUrl: product.imageUrl || '',
      category: category,
      syncTarget: product.sourceSystem === 'woocommerce' ? 'woocommerce' : product.sourceSystem === 'meta_catalog' ? 'meta_catalog' : 'all',
    });
    setIsProductModalOpen(true);
  };

  const handleSaveProduct = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!productForm.name || !productForm.price) {
      alert('Product Name and Price are required.');
      return;
    }
    
    try {
      let finalDescription = productForm.description.trim();
      if (productForm.category) {
        finalDescription += `\n\nCategory: ${productForm.category}`;
      }

      const payload = {
        name: productForm.name,
        sku: productForm.sku,
        price: parseFloat(productForm.price) || 0,
        description: finalDescription,
        stockQuantity: productForm.stockQuantity !== '' ? parseInt(productForm.stockQuantity) : null,
        stockStatus: productForm.stockStatus,
        imageUrl: productForm.imageUrl,
        syncTarget: productForm.syncTarget,
      };

      if (editingProduct) {
        await apiRequest(`api/products/${editingProduct.id}`, 'PATCH', payload);
      } else {
        await apiRequest('api/products', 'POST', payload);
      }

      setIsProductModalOpen(false);
      loadData();
    } catch (err: any) {
      alert(`Failed to save product: ${err.message}`);
    }
  };

  const handleDeleteProduct = async (id: string) => {
    if (!confirm('Are you sure you want to delete this product?')) return;
    try {
      await apiRequest(`api/products/${id}`, 'DELETE');
      loadData();
    } catch (err: any) {
      alert(`Failed to delete product: ${err.message}`);
    }
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setIsUploading(true);
    const formData = new FormData();
    formData.append('file', file);

    try {
      const res = await apiRequest('api/products/upload', 'POST', formData);
      const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
      const fullUrl = res.imageUrl.startsWith('http') ? res.imageUrl : `${API_URL}${res.imageUrl}`;
      setProductForm((prev) => ({ ...prev, imageUrl: fullUrl }));
    } catch (err: any) {
      alert(`File upload failed: ${err.message}`);
    } finally {
      setIsUploading(false);
    }
  };

  // Category Form handlers
  const openAddCategoryModal = () => {
    setEditingCategory(null);
    setCategoryForm({
      name: '',
      parentId: '',
    });
    setIsCategoryModalOpen(true);
  };

  const openEditCategoryModal = (category: Category) => {
    setEditingCategory(category);
    setCategoryForm({
      name: category.name,
      parentId: category.parentId || '',
    });
    setIsCategoryModalOpen(true);
  };

  const handleSaveCategory = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!categoryForm.name) {
      alert('Category Name is required.');
      return;
    }

    try {
      const payload = {
        name: categoryForm.name,
        parentId: categoryForm.parentId || null,
      };

      if (editingCategory) {
        await apiRequest(`api/categories/${editingCategory.id}`, 'PATCH', payload);
      } else {
        await apiRequest('api/categories', 'POST', payload);
      }

      setIsCategoryModalOpen(false);
      loadData();
    } catch (err: any) {
      alert(`Failed to save category: ${err.message}`);
    }
  };

  const handleDeleteCategory = async (id: string) => {
    if (!confirm('Are you sure you want to delete this category? Any child subcategories will be unlinked.')) return;
    try {
      await apiRequest(`api/categories/${id}`, 'DELETE');
      loadData();
    } catch (err: any) {
      alert(`Failed to delete category: ${err.message}`);
    }
  };

  const filteredProducts = products.filter((p) =>
    p.name.toLowerCase().includes(search.toLowerCase()) ||
    (p.sku && p.sku.toLowerCase().includes(search.toLowerCase())),
  );

  const filteredCategories = categories.filter((c) =>
    c.name.toLowerCase().includes(search.toLowerCase())
  );

  const recentSyncLogs = syncLogs.filter((log) => {
    if (log.status === 'RUNNING') return true;
    const completedTime = log.completedAt ? new Date(log.completedAt).getTime() : new Date(log.startedAt).getTime();
    const oneHourAgo = Date.now() - 60 * 60 * 1000;
    return completedTime >= oneHourAgo;
  });

  return (
    <div className="space-y-8 font-sans pb-16">
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold tracking-tight text-white Outfit">
            Catalog Management
          </h1>
          <p className="text-sm text-gray-400 mt-1">
            Manage your store catalog manually or sync dynamically from integration connectors
          </p>
        </div>
        <div className="flex gap-3">
          {activeTab === 'products' ? (
            <button
              onClick={openAddProductModal}
              className="flex items-center gap-2 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold px-4 py-2.5 rounded-xl text-sm transition-all shadow-lg shadow-emerald-500/10 cursor-pointer"
            >
              <Plus className="h-4 w-4" />
              Add Product
            </button>
          ) : (
            <button
              onClick={openAddCategoryModal}
              className="flex items-center gap-2 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold px-4 py-2.5 rounded-xl text-sm transition-all shadow-lg shadow-emerald-500/10 cursor-pointer"
            >
              <Plus className="h-4 w-4" />
              Add Category
            </button>
          )}
          <button
            onClick={handleSyncTrigger}
            disabled={syncing}
            className={`flex items-center gap-2 bg-white/5 border border-white/10 hover:bg-white/10 text-white font-semibold px-4 py-2.5 rounded-xl text-sm transition-all cursor-pointer disabled:opacity-60 disabled:pointer-events-none`}
          >
            <RefreshCw className={`h-4 w-4 ${syncing ? 'animate-spin' : ''}`} />
            {syncing ? 'Syncing...' : 'Sync Catalog'}
          </button>
        </div>
      </div>

      {/* Tabs Menu */}
      <div className="flex border-b border-white/5 gap-6">
        <button
          onClick={() => {
            setActiveTab('products');
            setSearch('');
          }}
          className={`pb-3 font-semibold text-sm transition-all relative cursor-pointer ${
            activeTab === 'products' ? 'text-emerald-400' : 'text-gray-400 hover:text-gray-200'
          }`}
        >
          <span className="flex items-center gap-2">
            <ShoppingBag className="h-4 w-4" /> Products ({products.length})
          </span>
          {activeTab === 'products' && (
            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-emerald-400 rounded-full" />
          )}
        </button>
        <button
          onClick={() => {
            setActiveTab('categories');
            setSearch('');
          }}
          className={`pb-3 font-semibold text-sm transition-all relative cursor-pointer ${
            activeTab === 'categories' ? 'text-emerald-400' : 'text-gray-400 hover:text-gray-200'
          }`}
        >
          <span className="flex items-center gap-2">
            <CategoriesIcon className="h-4 w-4" /> Categories ({categories.length})
          </span>
          {activeTab === 'categories' && (
            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-emerald-400 rounded-full" />
          )}
        </button>
      </div>

      {/* Sync Status Alert Banner if running */}
      {syncing && (
        <div className="bg-emerald-500/10 border border-emerald-500/20 rounded-xl p-4 flex gap-3 items-center text-sm text-emerald-400 pulse-glow-element">
          <RefreshCw className="h-5 w-5 animate-spin" />
          <span>
            Integration catalog items are currently syncing in the background from your active stores...
          </span>
        </div>
      )}

      <div className="grid grid-cols-1 xl:grid-cols-4 gap-8">
        {/* Main Area */}
        <div className="xl:col-span-3 space-y-6">
          <div className="flex items-center gap-3 bg-white/3 border border-white/5 rounded-xl px-4 py-3 max-w-md">
            <Search className="h-5 w-5 text-gray-500" />
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={
                activeTab === 'products'
                  ? 'Search products by name or SKU...'
                  : 'Search categories by name...'
              }
              className="bg-transparent border-0 outline-none text-sm text-white w-full placeholder-gray-500"
            />
          </div>

          {loading ? (
            <div className="flex h-64 items-center justify-center">
              <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-emerald-500 border-t-transparent"></div>
            </div>
          ) : activeTab === 'products' ? (
            // PRODUCTS TAB
            filteredProducts.length === 0 ? (
              <div className="glass-panel rounded-2xl p-12 text-center text-gray-500 space-y-3">
                <Database className="h-12 w-12 text-gray-600 mx-auto" />
                <h3 className="font-bold text-white text-base">No Products Found</h3>
                <p className="text-sm max-w-sm mx-auto leading-relaxed">
                  We couldn&apos;t find any products matching your query. Create one manually using &quot;Add Product&quot;, or sync from your integration.
                </p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredProducts.map((p) => {
                  const rawDesc = p.description || '';
                  const categoryMatch = rawDesc.match(/\n\nCategory:\s*(.+)$/);
                  const category = categoryMatch ? categoryMatch[1] : '';
                  const cleanDesc = rawDesc.replace(/\n\nCategory:\s*(.+)$/, '').trim();

                  return (
                    <div key={p.id} className="glass-panel glass-panel-hover rounded-2xl overflow-hidden flex flex-col group relative">
                      {/* Image container */}
                      <div className="h-48 w-full bg-black/40 relative overflow-hidden flex items-center justify-center border-b border-white/5">
                        {p.imageUrl ? (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img
                            src={p.imageUrl}
                            alt={p.name}
                            className="h-full w-full object-cover transition-transform group-hover:scale-105 duration-500"
                          />
                        ) : (
                          <ShoppingBag className="h-12 w-12 text-gray-700" />
                        )}
                        
                        {/* Price Tag Overlay */}
                        <div className="absolute bottom-3 right-3 glass-panel bg-black/60 px-3 py-1 rounded-lg border border-white/10 z-10">
                          <span className="font-mono text-xs text-primary font-bold">
                            ${p.price.toFixed(2)}
                          </span>
                        </div>
                      </div>

                      {/* Card Body */}
                      <div className="p-5 flex-1 flex flex-col justify-between space-y-4">
                        <div className="space-y-3">
                            {/* Stock Badge */}
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-medium tracking-wide ${
                              p.stockStatus === 'instock'
                                ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                                : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'
                            }`}>
                              {p.stockStatus === 'instock' ? 'In Stock' : 'Out of Stock'}
                            </span>

                          <div className="flex items-center justify-between gap-2">
                            <h4 className="font-bold text-slate-800 dark:text-white text-sm truncate font-sans tracking-tight">{p.name}</h4>
                            {category && (
                              <span className="bg-slate-100 dark:bg-white/5 border border-slate-200 dark:border-white/10 text-slate-500 dark:text-gray-400 text-[9px] font-bold px-2 py-0.5 rounded font-sans tracking-wide shrink-0">
                                {category}
                              </span>
                            )}
                          </div>
                          <p className="text-xs text-gray-400 line-clamp-2 leading-relaxed min-h-[2.5rem]">
                            {cleanDesc || 'No description provided.'}
                          </p>
                        </div>

                        <div className="space-y-3 pt-3 border-t border-white/5">
                          <div className="flex justify-between items-center">
                            <span className="text-[10px] text-gray-500 font-mono">
                              SKU: {p.sku || 'N/A'}
                            </span>
                            
                            <div className="flex gap-2">
                              {/* Edit & Delete Actions */}
                              <button
                                onClick={() => openEditProductModal(p)}
                                className="text-gray-400 hover:text-emerald-500 dark:hover:text-primary transition-colors cursor-pointer border-0 bg-transparent"
                                title="Edit product"
                                type="button"
                              >
                                <Edit2 className="h-4 w-4" />
                              </button>
                              <button
                                onClick={() => handleDeleteProduct(p.id)}
                                className="text-gray-400 hover:text-rose-500 dark:hover:text-red-400 transition-colors cursor-pointer border-0 bg-transparent"
                                title="Delete product"
                                type="button"
                              >
                                <Trash2 className="h-4 w-4" />
                              </button>
                            </div>
                          </div>

                          {p.variants && p.variants.length > 0 && (
                            <div className="bg-black/25 p-2 rounded-lg border border-white/5 space-y-1">
                              <p className="text-[9px] font-bold uppercase tracking-wider text-gray-500">Variants ({p.variants.length})</p>
                              <div className="flex flex-wrap gap-1">
                                {p.variants.map((v) => (
                                  <span key={v.id} className="text-[9px] bg-white/5 text-gray-300 px-1.5 py-0.5 rounded border border-white/5 font-mono">
                                    {v.name} (${v.price})
                                  </span>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )
          ) : (
            // CATEGORIES TAB
            filteredCategories.length === 0 ? (
              <div className="glass-panel rounded-2xl p-12 text-center text-gray-500 space-y-3">
                <CategoriesIcon className="h-12 w-12 mx-auto" />
                <h3 className="font-bold text-white text-base">No Categories Found</h3>
                <p className="text-sm max-w-sm mx-auto leading-relaxed">
                  We couldn&apos;t find any categories matching your query. Create one manually using &quot;Add Category&quot;, or sync from your integration.
                </p>
              </div>
            ) : (
              <div className="glass-panel rounded-2xl overflow-hidden border border-white/5">
                <div className="overflow-x-auto scrollbar-thin">
                  <table className="w-full min-w-[650px] text-left border-collapse text-sm">
                    <thead>
                      <tr className="border-b border-white/10 bg-white/2 text-gray-400 font-semibold">
                        <th className="px-6 py-4 text-left">Name</th>
                        <th className="px-6 py-4 text-left">Source System</th>
                        <th className="px-6 py-4 text-left">Parent Category</th>
                        <th className="px-6 py-4 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-white/5 text-gray-200">
                      {filteredCategories.map((c) => {
                        const parentCat = categories.find((cat) => cat.id === c.parentId || cat.externalCategoryId === c.parentId);
                        return (
                          <tr key={c.id} className="hover:bg-white/1 transition-all">
                            <td className="px-6 py-4 font-bold text-white">{c.name}</td>
                            <td className="px-6 py-4">
                              <span className="px-2 py-0.5 rounded-full text-[9px] font-bold uppercase bg-[#efeae2] text-[#008069] border border-[#008069]/20">
                                {c.sourceSystem}
                              </span>
                            </td>
                            <td className="px-6 py-4 text-gray-400">{parentCat?.name || '-'}</td>
                            <td className="px-6 py-4 text-right">
                              <div className="flex gap-2 justify-end">
                                <button
                                  onClick={() => openEditCategoryModal(c)}
                                  className="p-1.5 bg-white/5 hover:bg-white/10 rounded-lg text-gray-300 hover:text-white transition-all cursor-pointer"
                                  title="Edit category"
                                >
                                  <Edit2 className="h-3.5 w-3.5" />
                                </button>
                                <button
                                  onClick={() => handleDeleteCategory(c.id)}
                                  className="p-1.5 bg-red-500/10 hover:bg-red-500/20 rounded-lg text-red-400 hover:text-red-300 transition-all cursor-pointer"
                                  title="Delete category"
                                >
                                  <Trash2 className="h-3.5 w-3.5" />
                                </button>
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )
          )}
        </div>

        {/* Sync logs sidebar */}
        <div className="space-y-6">
          <div className="glass-panel rounded-2xl p-6 space-y-4">
            <h3 className="font-bold text-base text-white">Synchronization Logs</h3>
            <p className="text-xs text-gray-500">Track history of API data sync requests</p>
            
            {recentSyncLogs.length === 0 ? (
              <div className="text-center py-6 text-gray-500 text-xs">
                No sync logs recorded in the last hour.
              </div>
            ) : (
              <div className="space-y-4 max-h-[400px] overflow-y-auto pr-1">
                {recentSyncLogs.map((log) => (
                  <div key={log.id} className="text-xs border-b border-white/5 pb-3 last:border-b-0 last:pb-0 space-y-1">
                    <div className="flex items-center justify-between">
                      <span className="font-semibold text-white capitalize">{log.syncType} Sync</span>
                      <span className={`px-1.5 py-0.5 rounded text-[8px] font-bold uppercase ${
                        log.status === 'COMPLETED'
                          ? 'bg-emerald-500/10 text-emerald-400'
                          : log.status === 'FAILED'
                          ? 'bg-red-500/10 text-red-400'
                          : 'bg-amber-500/10 text-amber-400'
                      }`}>
                        {log.status}
                      </span>
                    </div>
                    <p className="text-[10px] text-gray-500">
                      Processed: <strong className="text-gray-300">{log.recordsProcessed}</strong> | Failed: <strong className="text-gray-300">{log.recordsFailed}</strong>
                    </p>
                    {log.errorMessage && (
                      <p className="text-[9px] text-red-400 bg-red-500/5 p-1 rounded border border-red-500/10 select-text leading-snug">
                        Error: {log.errorMessage}
                      </p>
                    )}
                    <span className="text-[9px] text-gray-600 block">
                      Started: {new Date(log.startedAt).toLocaleTimeString()}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* PRODUCT DIALOG MODAL */}
      {isProductModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
          <div className="glass-panel w-full max-w-xl rounded-2xl overflow-hidden shadow-2xl animate-fade-in border border-white/10">
            <div className="flex items-center justify-between px-6 py-4 border-b border-white/5 bg-white/2">
              <h3 className="font-bold text-lg text-white">
                {editingProduct ? 'Edit Product' : 'Add New Manual Product'}
              </h3>
              <button
                onClick={() => setIsProductModalOpen(false)}
                className="p-1.5 hover:bg-white/5 rounded-lg text-gray-400 hover:text-white transition-all cursor-pointer"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <form onSubmit={handleSaveProduct} className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1">
                  <label className="text-xs text-gray-400 font-semibold">Product Name *</label>
                  <input
                    type="text"
                    required
                    value={productForm.name}
                    onChange={(e) => setProductForm((prev) => ({ ...prev, name: e.target.value }))}
                    placeholder="e.g. Wireless Headphones"
                    className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all"
                  />
                </div>
                <div className="space-y-1">
                  <label className="text-xs text-gray-400 font-semibold">Price ($ USD) *</label>
                  <input
                    type="number"
                    step="0.01"
                    required
                    value={productForm.price}
                    onChange={(e) => setProductForm((prev) => ({ ...prev, price: e.target.value }))}
                    placeholder="e.g. 59.99"
                    className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1">
                  <label className="text-xs text-gray-400 font-semibold">SKU (Stock Keeping Unit)</label>
                  <input
                    type="text"
                    value={productForm.sku}
                    onChange={(e) => setProductForm((prev) => ({ ...prev, sku: e.target.value }))}
                    placeholder="e.g. WH-1000XM4"
                    className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all"
                  />
                </div>
                <div className="space-y-1">
                  <label className="text-xs text-gray-400 font-semibold">Stock Status</label>
                  <select
                    value={productForm.stockStatus}
                    onChange={(e) => setProductForm((prev) => ({ ...prev, stockStatus: e.target.value }))}
                    className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all"
                  >
                    <option value="instock" className="bg-neutral-900 text-white">In Stock</option>
                    <option value="outofstock" className="bg-neutral-900 text-white">Out of Stock</option>
                  </select>
                </div>
              </div>

              <div className="space-y-1">
                <label className="text-xs text-gray-400 font-semibold">Stock Quantity (Optional)</label>
                <input
                  type="number"
                  value={productForm.stockQuantity}
                  onChange={(e) => setProductForm((prev) => ({ ...prev, stockQuantity: e.target.value }))}
                  placeholder="e.g. 50"
                  className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all"
                />
              </div>

              <div className="space-y-1">
                <label className="text-xs text-gray-400 font-semibold">Product Description</label>
                <textarea
                  rows={3}
                  value={productForm.description}
                  onChange={(e) => setProductForm((prev) => ({ ...prev, description: e.target.value }))}
                  placeholder="Tell clients about this product..."
                  className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all resize-none"
                />
              </div>

              <div className="space-y-1">
                <label className="text-xs text-gray-400 font-semibold">Category (Optional)</label>
                <select
                  value={productForm.category}
                  onChange={(e) => setProductForm((prev) => ({ ...prev, category: e.target.value }))}
                  className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all"
                  style={{ colorScheme: 'dark' }}
                >
                  <option value="" style={{ backgroundColor: '#171717', color: '#9ca3af' }}>-- Select Category --</option>
                  {categories.map((cat) => (
                    <option key={cat.id} value={cat.name} style={{ backgroundColor: '#171717', color: '#ffffff' }}>
                      {cat.name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="space-y-3 border border-white/10 bg-black/40 p-4 rounded-xl">
                <label className="text-xs text-gray-300 font-semibold block">Sync Target Routing</label>
                <div className="grid grid-cols-3 gap-3">
                  <button
                    type="button"
                    onClick={() => setProductForm((prev) => ({ ...prev, syncTarget: 'all' }))}
                    className={`flex flex-col items-center justify-center py-3 px-2 rounded-lg border text-xs font-semibold transition-all cursor-pointer ${
                      productForm.syncTarget === 'all'
                        ? 'bg-emerald-500 border-emerald-400 text-white shadow-md shadow-emerald-500/20'
                        : 'bg-black/40 border-white/10 text-gray-400 hover:border-white/20 hover:text-gray-200'
                    }`}
                  >
                    <span>Multi-Channel (All)</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setProductForm((prev) => ({ ...prev, syncTarget: 'woocommerce' }))}
                    className={`flex flex-col items-center justify-center py-3 px-2 rounded-lg border text-xs font-semibold transition-all cursor-pointer ${
                      productForm.syncTarget === 'woocommerce'
                        ? 'bg-emerald-500 border-emerald-400 text-white shadow-md shadow-emerald-500/20'
                        : 'bg-black/40 border-white/10 text-gray-400 hover:border-white/20 hover:text-gray-200'
                    }`}
                  >
                    <span>WooCommerce Only</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setProductForm((prev) => ({ ...prev, syncTarget: 'meta_catalog' }))}
                    className={`flex flex-col items-center justify-center py-3 px-2 rounded-lg border text-xs font-semibold transition-all cursor-pointer ${
                      productForm.syncTarget === 'meta_catalog'
                        ? 'bg-emerald-500 border-emerald-400 text-white shadow-md shadow-emerald-500/20'
                        : 'bg-black/40 border-white/10 text-gray-400 hover:border-white/20 hover:text-gray-200'
                    }`}
                  >
                    <span>WhatsApp Only</span>
                  </button>
                </div>
              </div>

              <div className="space-y-2 border border-white/5 bg-black/20 p-4 rounded-xl">
                <label className="text-xs text-gray-300 font-bold block">Product Image</label>
                
                {productForm.imageUrl ? (
                  <div className="flex items-center gap-4 bg-white/2 p-2.5 rounded-lg border border-white/10 relative">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={productForm.imageUrl}
                      alt="Product Preview"
                      className="h-16 w-16 object-cover rounded-lg border border-white/10"
                    />
                    <div className="flex-1 overflow-hidden">
                      <p className="text-xs text-gray-400 truncate">{productForm.imageUrl}</p>
                    </div>
                    <button
                      type="button"
                      onClick={() => setProductForm((prev) => ({ ...prev, imageUrl: '' }))}
                      className="p-1 hover:bg-white/10 rounded-full text-gray-400 hover:text-white cursor-pointer"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  </div>
                ) : (
                  <div className="border border-dashed border-white/10 rounded-lg p-6 text-center space-y-2 relative">
                    {isUploading ? (
                      <div className="flex flex-col items-center justify-center gap-2 py-2">
                        <RefreshCw className="h-6 w-6 text-emerald-400 animate-spin" />
                        <span className="text-xs text-emerald-400 font-medium">Uploading image...</span>
                      </div>
                    ) : (
                      <>
                        <Upload className="h-8 w-8 text-gray-600 mx-auto" />
                        <div className="text-xs text-gray-400">
                          <span className="text-emerald-400 hover:underline cursor-pointer relative font-semibold">
                            Upload a file
                            <input
                              type="file"
                              accept="image/*"
                              onChange={handleFileUpload}
                              className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"
                            />
                          </span>
                          &nbsp;or enter image URL directly below
                        </div>
                      </>
                    )}
                  </div>
                )}

                {!productForm.imageUrl && !isUploading && (
                  <input
                    type="text"
                    value={productForm.imageUrl}
                    onChange={(e) => setProductForm((prev) => ({ ...prev, imageUrl: e.target.value }))}
                    placeholder="Alternatively, paste image URL (e.g. https://example.com/image.png)"
                    className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-xs focus:border-emerald-500 outline-none transition-all mt-2"
                  />
                )}
              </div>

              <div className="flex justify-end gap-3 pt-4 border-t border-white/5">
                <button
                  type="button"
                  onClick={() => setIsProductModalOpen(false)}
                  className="px-4 py-2 rounded-xl text-sm font-semibold border border-white/10 text-gray-300 hover:bg-white/5 transition-all cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-6 py-2 rounded-xl text-sm font-semibold bg-emerald-500 hover:bg-emerald-600 text-white shadow-lg shadow-emerald-500/10 transition-all cursor-pointer"
                >
                  Save Product
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* CATEGORY DIALOG MODAL */}
      {isCategoryModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
          <div className="glass-panel w-full max-w-md rounded-2xl overflow-hidden shadow-2xl animate-fade-in border border-white/10">
            <div className="flex items-center justify-between px-6 py-4 border-b border-white/5 bg-white/2">
              <h3 className="font-bold text-lg text-white">
                {editingCategory ? 'Edit Category' : 'Add New Category'}
              </h3>
              <button
                onClick={() => setIsCategoryModalOpen(false)}
                className="p-1.5 hover:bg-white/5 rounded-lg text-gray-400 hover:text-white transition-all cursor-pointer"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <form onSubmit={handleSaveCategory} className="p-6 space-y-4">
              <div className="space-y-1">
                <label className="text-xs text-gray-400 font-semibold">Category Name *</label>
                <input
                  type="text"
                  required
                  value={categoryForm.name}
                  onChange={(e) => setCategoryForm((prev) => ({ ...prev, name: e.target.value }))}
                  placeholder="e.g. Electronics"
                  className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all"
                />
              </div>

              <div className="space-y-1">
                <label className="text-xs text-gray-400 font-semibold">Parent Category (Optional)</label>
                <select
                  value={categoryForm.parentId}
                  onChange={(e) => setCategoryForm((prev) => ({ ...prev, parentId: e.target.value }))}
                  className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm focus:border-emerald-500 outline-none transition-all"
                  style={{ colorScheme: 'dark' }}
                >
                  <option value="" style={{ backgroundColor: '#171717', color: '#ffffff' }}>None (Root Category)</option>
                  {categories
                    .filter((c) => !editingCategory || (c.id !== editingCategory.id && c.externalCategoryId !== editingCategory.id))
                    .map((c) => (
                      <option key={c.id} value={c.id} style={{ backgroundColor: '#171717', color: '#ffffff' }}>
                        {c.name} ({c.sourceSystem})
                      </option>
                    ))}
                </select>
              </div>

              <div className="flex justify-end gap-3 pt-4 border-t border-white/5">
                <button
                  type="button"
                  onClick={() => setIsCategoryModalOpen(false)}
                  className="px-4 py-2 rounded-xl text-sm font-semibold border border-white/10 text-gray-300 hover:bg-white/5 transition-all cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-6 py-2 rounded-xl text-sm font-semibold bg-emerald-500 hover:bg-emerald-600 text-white shadow-lg shadow-emerald-500/10 transition-all cursor-pointer"
                >
                  Save Category
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
