'use client';

import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { ShopifyProduct } from '@/lib/shopify/product-service';
import { apiUrl } from '@/lib/utils/asset';

interface ProductPickerModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (selectedProducts: ShopifyProduct[]) => void;
  initiallySelectedIds?: string[];
  shop?: string;
}

export function ProductPickerModal({
  isOpen,
  onClose,
  onSelect,
  initiallySelectedIds = [],
  shop,
}: ProductPickerModalProps) {
  const searchParams = useSearchParams();
  const currentShop = shop || searchParams?.get('shop') || searchParams?.get('shopify_domain') || '';

  const getEndpoint = (path: string) => {
    const qs = currentShop ? `shop=${encodeURIComponent(currentShop)}` : '';
    const sep = path.includes('?') ? '&' : '?';
    return apiUrl(qs ? `${path}${sep}${qs}` : path);
  };

  const [searchQuery, setSearchQuery] = useState('');
  const [products, setProducts] = useState<ShopifyProduct[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedMap, setSelectedMap] = useState<Record<string, ShopifyProduct>>({});
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [isSyncingShopify, setIsSyncingShopify] = useState(false);
  const [syncError, setSyncError] = useState<string | null>(null);

  useEffect(() => {
    if (isOpen) {
      fetchProducts(1, searchQuery);
    }
  }, [isOpen]);

  const handleSyncShopify = async () => {
    setIsSyncingShopify(true);
    setSyncError(null);
    try {
      const res = await fetch(getEndpoint('/api/shopify/products/sync'), { method: 'POST' });
      const data = await res.json();
      if (data.success) {
        await fetchProducts(1, searchQuery);
      } else {
        setSyncError(data.error || 'Failed to sync from Shopify');
      }
    } catch (err: any) {
      setSyncError(err.message || 'Network error syncing from Shopify');
    } finally {
      setIsSyncingShopify(false);
    }
  };

  const fetchProducts = async (targetPage: number, query: string) => {
    setLoading(true);
    try {
      const res = await fetch(getEndpoint(`/api/shopify/products?page=${targetPage}&limit=20&q=${encodeURIComponent(query)}`));
      const data = await res.json();
      if (data.success) {
        setProducts(data.products || []);
        if (data.pagination) {
          setPage(data.pagination.page);
          setTotalPages(data.pagination.totalPages);
          setTotalCount(data.pagination.total);
        }
      }
    } catch (err) {
      console.error('Failed to fetch products for modal', err);
    } finally {
      setLoading(false);
    }
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setPage(1);
    fetchProducts(1, searchQuery);
  };

  const toggleSelectProduct = (prod: ShopifyProduct) => {
    const id = String(prod.id);
    setSelectedMap(prev => {
      const next = { ...prev };
      if (next[id]) {
        delete next[id];
      } else {
        next[id] = prod;
      }
      return next;
    });
  };

  const toggleSelectAllCurrent = () => {
    const allSelected = products.every(p => !!selectedMap[String(p.id)]);
    setSelectedMap(prev => {
      const next = { ...prev };
      if (allSelected) {
        products.forEach(p => delete next[String(p.id)]);
      } else {
        products.forEach(p => {
          next[String(p.id)] = p;
        });
      }
      return next;
    });
  };

  const handleConfirm = () => {
    onSelect(Object.values(selectedMap));
    onClose();
  };

  if (!isOpen) return null;

  const selectedCount = Object.keys(selectedMap).length;
  const isAllCurrentSelected = products.length > 0 && products.every(p => !!selectedMap[String(p.id)]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs p-3 sm:p-4 animate-in fade-in-50 duration-200">
      <div className="bg-white border border-slate-200 rounded-2xl w-full max-w-3xl shadow-xl overflow-hidden flex flex-col max-h-[85vh]">
        {/* Header */}
        <div className="px-4 sm:px-6 py-3.5 sm:py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/70">
          <div>
            <h3 className="text-base font-bold text-slate-900 tracking-tight">Select specific products</h3>
            <p className="text-xs text-slate-500 mt-0.5">
              Choose the products you want to include in this Facebook catalog
            </p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="text-slate-400 hover:text-slate-700 rounded-lg p-1.5 hover:bg-slate-200/60 transition"
          >
            <i className="fa-solid fa-xmark text-base" />
          </button>
        </div>

        {/* Search Bar & Actions */}
        <div className="p-3.5 sm:p-4 bg-white border-b border-slate-100 space-y-2">
          <div className="flex flex-col sm:flex-row sm:items-center gap-2">
            <form onSubmit={handleSearchSubmit} className="relative flex-1 flex items-center gap-2">
              <div className="relative flex-1">
                <span className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-slate-400">
                  <i className="fa-solid fa-magnifying-glass text-xs" />
                </span>
                <input
                  type="text"
                  value={searchQuery}
                  onChange={e => setSearchQuery(e.target.value)}
                  placeholder="Search products by title or SKU..."
                  className="w-full pl-9 pr-4 py-2 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme transition"
                />
              </div>
              <button
                type="submit"
                className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold rounded-xl transition shadow-2xs shrink-0"
              >
                Search
              </button>
            </form>
            <button
              type="button"
              onClick={handleSyncShopify}
              disabled={isSyncingShopify || loading}
              className="px-3.5 py-2 bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold rounded-xl transition shadow-2xs flex items-center justify-center gap-1.5 disabled:opacity-50 shrink-0"
              title="Sync latest live products from your Shopify store"
            >
              {isSyncingShopify ? (
                <>
                  <i className="fa-solid fa-spinner fa-spin text-theme text-xs" />
                  <span>Syncing...</span>
                </>
              ) : (
                <>
                  <i className="fa-brands fa-shopify text-emerald-600 text-xs" />
                  <span>Sync from Shopify</span>
                </>
              )}
            </button>
          </div>
          {syncError && (
            <p className="text-[11px] text-rose-600 font-medium">
              ⚠️ {syncError}
            </p>
          )}
        </div>

        {/* Product List Table */}
        <div className="flex-1 overflow-y-auto min-h-[300px] p-2">
          {loading ? (
            <div className="flex flex-col items-center justify-center h-64 text-slate-400">
              <i className="fa-solid fa-spinner fa-spin text-theme text-2xl mb-2" />
              <p className="text-xs font-medium">Loading store products...</p>
            </div>
          ) : products.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-64 text-slate-400">
              <i className="fa-solid fa-box-open text-3xl text-slate-300 mb-2" />
              <p className="text-xs font-medium">No products found</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse min-w-[480px]">
                <thead>
                  <tr className="border-b border-slate-100 text-[10px] font-bold text-slate-400 uppercase tracking-wider bg-slate-50/50">
                    <th className="py-2.5 px-3 w-10 text-center">
                      <input
                        type="checkbox"
                        checked={isAllCurrentSelected}
                        onChange={toggleSelectAllCurrent}
                        className="w-4 h-4 rounded border-slate-300 text-theme focus:ring-theme cursor-pointer"
                      />
                    </th>
                    <th className="py-2.5 px-3 w-14">Image</th>
                    <th className="py-2.5 px-3">Product</th>
                    <th className="py-2.5 px-3 text-right">Variants</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {products.map(prod => {
                    const isSelected = !!selectedMap[String(prod.id)];
                    const imgSrc = prod.image?.src || (prod.images && prod.images[0] ? (typeof prod.images[0] === 'string' ? prod.images[0] : prod.images[0].src) : null);
                    const variantCount = prod.variants?.length || 1;

                    return (
                      <tr
                        key={prod.id}
                        onClick={() => toggleSelectProduct(prod)}
                        className={`hover:bg-slate-50/70 cursor-pointer transition ${
                          isSelected ? 'bg-theme/5' : ''
                        }`}
                      >
                        <td className="py-2.5 px-3 text-center" onClick={e => e.stopPropagation()}>
                          <input
                            type="checkbox"
                            checked={isSelected}
                            onChange={() => toggleSelectProduct(prod)}
                            className="w-4 h-4 rounded border-slate-300 text-theme focus:ring-theme cursor-pointer"
                          />
                        </td>
                        <td className="py-2.5 px-3">
                          <div className="w-10 h-10 rounded-lg bg-slate-100 border border-slate-200 overflow-hidden flex items-center justify-center">
                            {imgSrc ? (
                              <img src={imgSrc} alt={prod.title} width={40} height={40} loading="lazy" className="w-full h-full object-cover" />
                            ) : (
                              <i className="fa-solid fa-box text-slate-400 text-sm" />
                            )}
                          </div>
                        </td>
                        <td className="py-2.5 px-3">
                          <p className="text-xs font-bold text-slate-900 line-clamp-1">{prod.title}</p>
                          <p className="text-[11px] text-slate-400">
                            {prod.vendor ? `${prod.vendor} • ` : ''}ID: {prod.id}
                          </p>
                        </td>
                        <td className="py-2.5 px-3 text-right text-xs font-semibold text-slate-600">
                          {variantCount} {variantCount === 1 ? 'variant' : 'variants'}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Pagination & Footer */}
        <div className="px-4 sm:px-6 py-3 sm:py-4 border-t border-slate-100 bg-slate-50/70 flex flex-col-reverse sm:flex-row sm:items-center justify-between gap-3">
          <div className="text-xs text-slate-500">
            {totalCount > 0 && (
              <span>
                Page {page} of {totalPages} ({totalCount} total products)
              </span>
            )}
            {selectedCount > 0 && (
              <span className="ml-2 sm:ml-3 font-semibold text-theme">
                {selectedCount} selected
              </span>
            )}
          </div>

          <div className="flex flex-wrap items-center justify-end gap-2 sm:gap-3">
            {totalPages > 1 && (
              <div className="flex items-center gap-1 mr-2 sm:mr-4">
                <button
                  type="button"
                  disabled={page <= 1 || loading}
                  onClick={() => fetchProducts(page - 1, searchQuery)}
                  className="px-2.5 py-1 text-xs bg-white border border-slate-200 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed rounded-lg text-slate-700 shadow-2xs font-medium"
                >
                  Prev
                </button>
                <button
                  type="button"
                  disabled={page >= totalPages || loading}
                  onClick={() => fetchProducts(page + 1, searchQuery)}
                  className="px-2.5 py-1 text-xs bg-white border border-slate-200 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed rounded-lg text-slate-700 shadow-2xs font-medium"
                >
                  Next
                </button>
              </div>
            )}

            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-100 rounded-xl transition"
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={handleConfirm}
              className="px-5 py-2 text-xs font-bold bg-theme hover:bg-theme-hover text-white rounded-xl shadow-sm hover:shadow-md transition active:scale-95"
            >
              Add {selectedCount > 0 ? `(${selectedCount})` : ''} products
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
