"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";

interface Product {
  _id: string;
  title?: string;
  sku?: string;
  price?: number;
  cost?: number;
  qty?: number;
  stock?: number;
  scat?: string;
  cat?: string;
  category?: string;
  active?: boolean;
  featured?: boolean;
  photoUrl?: string;
  images?: string[];
  createdAt?: string;
}

function ProductImageCell({ imageUrl, alt }: { imageUrl: string; alt: string }) {
  const [imageError, setImageError] = useState(false);
  const [imageLoaded, setImageLoaded] = useState(false);

  const handleImageError = () => {
    setImageError(true);
  };

  const handleImageLoad = () => {
    setImageLoaded(true);
  };

  return (
    <div className="w-20 h-20 bg-gray-100 rounded-lg border border-gray-200 flex items-center justify-center overflow-hidden shadow-sm relative">
      {imageUrl && !imageError ? (
        <>
          {!imageLoaded && (
            <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
              <div className="w-6 h-6 border-2 border-gray-300 border-t-blue-600 rounded-full animate-spin"></div>
            </div>
          )}
          <img
            src={imageUrl}
            alt={alt}
            className={`w-full h-full object-contain p-1.5 transition-opacity duration-200 ${
              imageLoaded ? "opacity-100" : "opacity-0"
            }`}
            onError={handleImageError}
            onLoad={handleImageLoad}
            loading="lazy"
          />
        </>
      ) : (
        <svg className="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
        </svg>
      )}
    </div>
  );
}

export default function AdminProductsPage() {
  const router = useRouter();
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [categories, setCategories] = useState<string[]>([]);

  useEffect(() => {
    fetchProducts();
  }, [currentPage, search, categoryFilter, statusFilter]);

  const fetchProducts = async () => {
    setLoading(true);
    try {
      // Fetch all products first (no search param to get all)
      const params = new URLSearchParams({
        page: "1",
        limit: "10000", // Get all for client-side filtering
      });

      // Fetch from both collections
      const [productsRes, ecommersRes] = await Promise.all([
        fetch(`/api/products?${params}`),
        fetch(`/api/ecommers?${params}`),
      ]);

      let allProducts: Product[] = [];

      if (productsRes.ok) {
        const productsData = await productsRes.json();
        if (Array.isArray(productsData?.products)) {
          allProducts.push(...productsData.products);
        }
      }

      if (ecommersRes.ok) {
        const ecommersData = await ecommersRes.json();
        if (Array.isArray(ecommersData?.products)) {
          allProducts.push(...ecommersData.products);
        }
      }

      // Apply search filter first (client-side)
      let filtered = allProducts;
      
      if (search.trim()) {
        const searchLower = search.toLowerCase().trim();
        filtered = filtered.filter((p) => {
          // Try to parse productDetails for search
          let productDetailsText = "";
          try {
            if ((p as any).productDetails) {
              const details = typeof (p as any).productDetails === "string" 
                ? JSON.parse((p as any).productDetails) 
                : (p as any).productDetails;
              if (typeof details === "object" && details !== null) {
                productDetailsText = Object.values(details).join(" ");
              } else {
                productDetailsText = String((p as any).productDetails);
              }
            }
          } catch (e) {
            productDetailsText = String((p as any).productDetails || "");
          }

          const searchableText = [
            p.title || "",
            p.sku || "",
            (p as any).description || "",
            (p as any).shortDescription || "",
            (p as any).fullDescription || "",
            productDetailsText,
            p.scat || "",
            p.cat || "",
            (p as any).category || "",
            (p as any).itc1 || "",
            (p as any).itn || "",
            (p as any).supplier || "",
            (p as any).mfg || "",
          ]
            .join(" ")
            .toLowerCase();
          return searchableText.includes(searchLower);
        });
      }

      // Apply category filter
      if (categoryFilter !== "all") {
        filtered = filtered.filter((p) => {
          const cat = p.scat || p.cat || p.category || "";
          return cat.toLowerCase().includes(categoryFilter.toLowerCase());
        });
      }

      // Apply status filter
      if (statusFilter === "active") {
        filtered = filtered.filter((p) => p.active !== false);
      } else if (statusFilter === "inactive") {
        filtered = filtered.filter((p) => p.active === false);
      } else if (statusFilter === "featured") {
        filtered = filtered.filter((p) => p.featured === true);
      }

      // Extract unique categories from all products (not filtered)
      const uniqueCategories = new Set<string>();
      allProducts.forEach((p) => {
        const cat = p.scat || p.cat || p.category;
        if (cat) uniqueCategories.add(cat);
      });
      setCategories(Array.from(uniqueCategories).sort());

      setProducts(filtered);
      setTotalPages(Math.ceil(filtered.length / 50));
    } catch (error) {
      console.error("Error fetching products:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (productId: string, collection: string) => {
    if (!confirm("Are you sure you want to delete this product?")) {
      return;
    }

    try {
      const response = await fetch(`/api/${collection}/${productId}`, {
        method: "DELETE",
      });

      if (response.ok) {
        alert("Product deleted successfully");
        fetchProducts();
      } else {
        alert("Failed to delete product");
      }
    } catch (error) {
      console.error("Error deleting product:", error);
      alert("Error deleting product");
    }
  };

  const handleToggleStatus = async (product: Product, collection: string) => {
    try {
      const newActiveStatus = product.active === false ? true : false;
      const response = await fetch(`/api/${collection}/${product._id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ active: newActiveStatus }),
      });

      if (response.ok) {
        fetchProducts();
      } else {
        const errorData = await response.json();
        alert(`Failed to update product status: ${errorData.error || "Unknown error"}`);
      }
    } catch (error) {
      console.error("Error updating product:", error);
      alert("Error updating product");
    }
  };

  const handleToggleFeatured = async (product: Product) => {
    try {
      const response = await fetch(`/api/ecommers/${product._id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ featured: !product.featured }),
      });

      if (response.ok) {
        fetchProducts();
      } else {
        alert("Failed to update featured status");
      }
    } catch (error) {
      console.error("Error updating featured status:", error);
      alert("Error updating featured status");
    }
  };

  const determineCollection = (product: Product): string => {
    // Check if product has ecommers-specific fields
    if (product.featured !== undefined || product.images?.length) {
      return "ecommers";
    }
    return "products";
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <h1 className="text-3xl font-bold text-gray-900">Products</h1>
        <p>Loading products...</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Products Management</h1>
          <p className="text-gray-600 mt-2">Manage all products in your store</p>
        </div>
        <Link
          href="/admin/add-product"
          className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition"
        >
          + Add New Product
        </Link>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-lg shadow p-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">
              Search
            </label>
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search products..."
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">
              Category
            </label>
            <select
              value={categoryFilter}
              onChange={(e) => setCategoryFilter(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
            >
              <option value="all">All Categories</option>
              {categories.map((cat) => (
                <option key={cat} value={cat}>
                  {cat}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">
              Status
            </label>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
              <option value="featured">Featured</option>
            </select>
          </div>
          <div className="flex items-end">
            <button
              onClick={() => {
                setSearch("");
                setCategoryFilter("all");
                setStatusFilter("all");
              }}
              className="w-full px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold rounded-lg transition"
            >
              Clear Filters
            </button>
          </div>
        </div>
      </div>

      {/* Products Table */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Image
                </th>
                <th className="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Product
                </th>
                <th className="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  SKU
                </th>
                <th className="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Category
                </th>
                <th className="px-6 py-3 text-right text-xs font-semibold text-gray-700 uppercase">
                  Price
                </th>
                <th className="px-6 py-3 text-right text-xs font-semibold text-gray-700 uppercase">
                  Stock
                </th>
                <th className="px-6 py-3 text-center text-xs font-semibold text-gray-700 uppercase">
                  Status
                </th>
                <th className="px-6 py-3 text-center text-xs font-semibold text-gray-700 uppercase">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {products.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-6 py-12 text-center text-gray-500">
                    No products found
                  </td>
                </tr>
              ) : (
                products.map((product) => {
                  const collection = determineCollection(product);
                  // Prefer thumbnail, then first image, then photoUrl, then placeholder
                  const imageUrl = (product as any).photoThumb || 
                                   (product as any).thumbnails?.[0] || 
                                   product.images?.[0] || 
                                   product.photoUrl || 
                                   "";
                  
                  return (
                    <tr key={product._id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <ProductImageCell 
                          imageUrl={imageUrl} 
                          alt={product.title || "Product"} 
                        />
                      </td>
                      <td className="px-6 py-4">
                        <div className="font-semibold text-gray-900">
                          {product.title || "Untitled Product"}
                        </div>
                        {product.featured && (
                          <span className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded">
                            Featured
                          </span>
                        )}
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-600">
                        {product.sku || "N/A"}
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-600">
                        {product.scat || product.cat || product.category || "N/A"}
                      </td>
                      <td className="px-6 py-4 text-right font-semibold text-gray-900">
                        ${product.price?.toFixed(2) || "0.00"}
                      </td>
                      <td className="px-6 py-4 text-right text-sm text-gray-600">
                        {product.qty || product.stock || 0}
                      </td>
                      <td className="px-6 py-4 text-center">
                        <button
                          onClick={() => handleToggleStatus(product, collection)}
                          className={`px-3 py-1 rounded-full text-xs font-semibold ${
                            product.active !== false
                              ? "bg-green-100 text-green-800"
                              : "bg-red-100 text-red-800"
                          }`}
                        >
                          {product.active !== false ? "Active" : "Inactive"}
                        </button>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center justify-center gap-2">
                          <Link
                            href={`/admin/products/${product._id}/edit`}
                            className="px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold rounded transition"
                          >
                            Edit
                          </Link>
                          {collection === "ecommers" && (
                            <button
                              onClick={() => handleToggleFeatured(product)}
                              className={`px-3 py-1 text-xs font-semibold rounded transition ${
                                product.featured
                                  ? "bg-yellow-100 text-yellow-800 hover:bg-yellow-200"
                                  : "bg-gray-100 text-gray-800 hover:bg-gray-200"
                              }`}
                            >
                              {product.featured ? "★ Featured" : "☆ Feature"}
                            </button>
                          )}
                          <button
                            onClick={() => handleDelete(product._id, collection)}
                            className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-xs font-semibold rounded transition"
                          >
                            Delete
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="px-6 py-4 border-t border-gray-200 flex justify-between items-center">
            <div className="text-sm text-gray-600">
              Page {currentPage} of {totalPages}
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Previous
              </button>
              <button
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
                className="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-lg shadow p-6">
          <div className="text-sm font-semibold text-gray-600">Total Products</div>
          <div className="text-2xl font-bold text-gray-900 mt-2">{products.length}</div>
        </div>
        <div className="bg-white rounded-lg shadow p-6">
          <div className="text-sm font-semibold text-gray-600">Active Products</div>
          <div className="text-2xl font-bold text-green-600 mt-2">
            {products.filter((p) => p.active !== false).length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow p-6">
          <div className="text-sm font-semibold text-gray-600">Featured Products</div>
          <div className="text-2xl font-bold text-yellow-600 mt-2">
            {products.filter((p) => p.featured).length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow p-6">
          <div className="text-sm font-semibold text-gray-600">Low Stock</div>
          <div className="text-2xl font-bold text-red-600 mt-2">
            {products.filter((p) => (p.qty || p.stock || 0) < 10).length}
          </div>
        </div>
      </div>
    </div>
  );
}

