"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Plus, Edit, Trash2, Image } from "lucide-react";
import { toast } from "sonner";

interface Category {
  _id: string;
  name: string;
  slug: string;
}

interface Color {
  _id: string;
  name: string;
  hexCode: string;
}

interface Size {
  _id: string;
  name: string;
}

interface Product {
  _id: string;
  name: string;
  slug: string;
  description: string;
  shortDescription?: string;
  category: Category;
  subcategory?: Category;
  brand?: string;
  tags: string[];
  isActive: boolean;
  isFeatured: boolean;
  createdAt: string;
}

interface ProductColor {
  _id: string;
  product: string;
  color: Color;
  size: Size;
  sku: string;
  price: number;
  comparePrice?: number;
  inventory: number;
  isActive: boolean;
}

interface ProductImage {
  _id: string;
  productColor: string;
  product: string;
  imageUrl: string;
  altText?: string;
  sortOrder: number;
  isActive: boolean;
}

type Tab = "products" | "colors" | "images";

export default function ProductsManagement() {
  const [products, setProducts] = useState<Product[]>([]);
  const [productColors, setProductColors] = useState<ProductColor[]>([]);
  const [productImages, setProductImages] = useState<ProductImage[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [colors, setColors] = useState<Color[]>([]);
  const [sizes, setSizes] = useState<Size[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<Tab>("products");
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<any>(null);
  
  // Product form state
  const [productForm, setProductForm] = useState({
    name: "",
    description: "",
    shortDescription: "",
    category: "",
    subcategory: "",
    brand: "",
    tags: [] as string[],
    isActive: true,
    isFeatured: false,
  });

  // Product Color form state
  const [colorForm, setColorForm] = useState({
    product: "",
    color: "",
    size: "",
    sku: "",
    price: 0,
    comparePrice: 0,
    inventory: 0,
    isActive: true,
  });

  // Product Image form state
  const [imageForm, setImageForm] = useState({
    productColor: "",
    product: "",
    imageUrl: "",
    altText: "",
    sortOrder: 0,
    isActive: true,
  });

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const [productsRes, categoriesRes, colorsRes, sizesRes, colorDataRes, imagesRes] = await Promise.all([
        fetch("/api/products"),
        fetch("/api/categories"),
        fetch("/api/colors"),
        fetch("/api/sizes"),
        fetch("/api/product-colors"),
        fetch("/api/product-images")
      ]);

      const [productsResult, categoriesResult, colorsResult, sizesResult, colorDataResult, imagesResult] = await Promise.all([
        productsRes.json(),
        categoriesRes.json(),
        colorsRes.json(),
        sizesRes.json(),
        colorDataRes.json(),
        imagesRes.json()
      ]);

      if (productsResult.success) setProducts(productsResult.data);
      if (categoriesResult.success) setCategories(categoriesResult.data);
      if (colorsResult.success) setColors(colorsResult.data);
      if (sizesResult.success) setSizes(sizesResult.data);
      if (colorDataResult.success) setProductColors(colorDataResult.data);
      if (imagesResult.success) setProductImages(imagesResult.data);
    } catch (error) {
      toast.error("Error fetching data");
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  // Product handlers
  const handleProductSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const url = editingItem?._id && activeTab === "products" ? `/api/products/${editingItem._id}` : "/api/products";
      const method = editingItem?._id && activeTab === "products" ? "PUT" : "POST";

      const response = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(productForm),
      });

      const result = await response.json();

      if (result.success) {
        toast.success(editingItem?.id && activeTab === "products" ? "Product updated" : "Product created");
        setIsDialogOpen(false);
        setEditingItem(null);
        resetProductForm();
        fetchData();
      } else {
        toast.error(result.error || "Failed to save product");
      }
    } catch (error) {
      toast.error("Error saving product");
    }
  };

  // ProductColor handlers
  const handleColorSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const url = editingItem?._id && activeTab === "colors" ? `/api/product-colors/${editingItem._id}` : "/api/product-colors";
      const method = editingItem?._id && activeTab === "colors" ? "PUT" : "POST";

      const response = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(colorForm),
      });

      const result = await response.json();

      if (result.success) {
        toast.success(editingItem?._id && activeTab === "colors" ? "Product color updated" : "Product color created");
        setIsDialogOpen(false);
        setEditingItem(null);
        resetColorForm();
        fetchData();
      } else {
        toast.error(result.error || "Failed to save product color");
      }
    } catch (error) {
      toast.error("Error saving product color");
    }
  };

  // ProductImage handlers
  const handleImageSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const url = editingItem?._id && activeTab === "images" ? `/api/product-images/${editingItem._id}` : "/api/product-images";
      const method = editingItem?._id && activeTab === "images" ? "PUT" : "POST";

      const response = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(imageForm),
      });

      const result = await response.json();

      if (result.success) {
        toast.success(editingItem?._id && activeTab === "images" ? "Product image updated" : "Product image added");
        setIsDialogOpen(false);
        setEditingItem(null);
        resetImageForm();
        fetchData();
      } else {
        toast.error(result.error || "Failed to save product image");
      }
    } catch (error) {
      toast.error("Error saving product image");
    }
  };

  const handleDelete = async (id: string, type: "product" | "color" | "image") => {
    if (!confirm(`Are you sure you want to delete this ${type}?`)) return;

    try {
      const endpoint = type === "product" ? "/api/products" : type === "color" ? "/api/product-colors" : "/api/product-images";
      const response = await fetch(`${endpoint}/${id}`, { method: "DELETE" });
      const result = await response.json();

      if (result.success) {
        toast.success(`${type} deleted successfully`);
        fetchData();
      } else {
        toast.error(result.error || `Failed to delete ${type}`);
      }
    } catch (error) {
      toast.error(`Error deleting ${type}`);
    }
  };

  const handleEditProduct = (product: Product) => {
    setEditingItem(product);
    setProductForm({
      name: product.name,
      description: product.description,
      shortDescription: product.shortDescription || "",
      category: product.category._id,
      subcategory: product.subcategory?._id || "",
      brand: product.brand || "",
      tags: product.tags,
      isActive: product.isActive,
      isFeatured: product.isFeatured,
    });
    setIsDialogOpen(true);
  };

  const handleEditColor = (color: ProductColor) => {
    setEditingItem(color);
    setColorForm({
      product: color.product,
      color: typeof color.color === "string" ? color.color : color.color._id,
      size: typeof color.size === "string" ? color.size : color.size._id,
      sku: color.sku,
      price: color.price,
      comparePrice: color.comparePrice || 0,
      inventory: color.inventory,
      isActive: color.isActive,
    });
    setIsDialogOpen(true);
  };

  const handleEditImage = (image: ProductImage) => {
    setEditingItem(image);
    setImageForm({
      productColor: image.productColor,
      product: image.product,
      imageUrl: image.imageUrl,
      altText: image.altText || "",
      sortOrder: image.sortOrder,
      isActive: image.isActive,
    });
    setIsDialogOpen(true);
  };

  const resetProductForm = () => {
    setProductForm({
      name: "",
      description: "",
      shortDescription: "",
      category: "",
      subcategory: "",
      brand: "",
      tags: [],
      isActive: true,
      isFeatured: false,
    });
  };

  const resetColorForm = () => {
    setColorForm({
      product: "",
      color: "",
      size: "",
      sku: "",
      price: 0,
      comparePrice: 0,
      inventory: 0,
      isActive: true,
    });
  };

  const resetImageForm = () => {
    setImageForm({
      productColor: "",
      product: "",
      imageUrl: "",
      altText: "",
      sortOrder: 0,
      isActive: true,
    });
  };

  if (loading) return <div className="flex justify-center p-8">Loading...</div>;

  return (
    <div className="rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark">
      {/* Tabs */}
      <div className="border-b border-stroke px-6.5 py-4 dark:border-strokedark flex gap-4">
        <button
          onClick={() => setActiveTab("products")}
          className={`pb-2 border-b-2 ${activeTab === "products" ? "border-blue-500 text-blue-500" : "border-transparent text-gray-600"}`}
        >
          Products
        </button>
        <button
          onClick={() => setActiveTab("colors")}
          className={`pb-2 border-b-2 ${activeTab === "colors" ? "border-blue-500 text-blue-500" : "border-transparent text-gray-600"}`}
        >
          Product Colors/Sizes
        </button>
        <button
          onClick={() => setActiveTab("images")}
          className={`pb-2 border-b-2 ${activeTab === "images" ? "border-blue-500 text-blue-500" : "border-transparent text-gray-600"}`}
        >
          Product Images
        </button>
      </div>

      <div className="border-b border-stroke px-6.5 py-4 dark:border-strokedark">
        <div className="flex items-center justify-between">
          <h3 className="font-medium text-black dark:text-white">
            {activeTab === "products" ? "Products Management" : activeTab === "colors" ? "Product Colors/Sizes Management" : "Product Images Management"}
          </h3>
          <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
            <DialogTrigger asChild>
              <Button
                onClick={() => {
                  setEditingItem(null);
                  if (activeTab === "products") resetProductForm();
                  else if (activeTab === "colors") resetColorForm();
                  else resetImageForm();
                }}
                className="flex items-center gap-2"
              >
                <Plus className="h-4 w-4" />
                Add {activeTab === "products" ? "Product" : activeTab === "colors" ? "Color/Size" : "Image"}
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle>
                  {activeTab === "products" && (editingItem ? "Edit Product" : "Add New Product")}
                  {activeTab === "colors" && (editingItem ? "Edit Product Color/Size" : "Add Product Color/Size")}
                  {activeTab === "images" && (editingItem ? "Edit Product Image" : "Add Product Image")}
                </DialogTitle>
              </DialogHeader>

              {/* Products Form */}
              {activeTab === "products" && (
                <form onSubmit={handleProductSubmit} className="space-y-4">
                  <div>
                    <Label htmlFor="name">Name *</Label>
                    <Input
                      id="name"
                      value={productForm.name}
                      onChange={(e) => setProductForm({ ...productForm, name: e.target.value })}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="description">Description *</Label>
                    <Textarea
                      id="description"
                      value={productForm.description}
                      onChange={(e) => setProductForm({ ...productForm, description: e.target.value })}
                      required
                      rows={3}
                    />
                  </div>
                  <div>
                    <Label htmlFor="shortDescription">Short Description</Label>
                    <Textarea
                      id="shortDescription"
                      value={productForm.shortDescription}
                      onChange={(e) => setProductForm({ ...productForm, shortDescription: e.target.value })}
                      rows={2}
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="category">Category *</Label>
                      <Select
                        value={productForm.category}
                        onValueChange={(value) => setProductForm({ ...productForm, category: value })}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select category" />
                        </SelectTrigger>
                        <SelectContent>
                          {categories.map((cat) => (
                            <SelectItem key={cat._id} value={cat._id}>
                              {cat.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label htmlFor="brand">Brand</Label>
                      <Input
                        id="brand"
                        value={productForm.brand}
                        onChange={(e) => setProductForm({ ...productForm, brand: e.target.value })}
                      />
                    </div>
                  </div>
                  <div className="flex items-center space-x-4">
                    <div className="flex items-center space-x-2">
                      <Switch
                        id="isActive"
                        checked={productForm.isActive}
                        onCheckedChange={(checked) => setProductForm({ ...productForm, isActive: checked })}
                      />
                      <Label htmlFor="isActive">Active</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Switch
                        id="isFeatured"
                        checked={productForm.isFeatured}
                        onCheckedChange={(checked) => setProductForm({ ...productForm, isFeatured: checked })}
                      />
                      <Label htmlFor="isFeatured">Featured</Label>
                    </div>
                  </div>
                  <div className="flex justify-end gap-2">
                    <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>
                      Cancel
                    </Button>
                    <Button type="submit">
                      {editingItem ? "Update" : "Create"}
                    </Button>
                  </div>
                </form>
              )}

              {/* Product Color Form */}
              {activeTab === "colors" && (
                <form onSubmit={handleColorSubmit} className="space-y-4">
                  <div>
                    <Label htmlFor="product">Product *</Label>
                    <Select
                      value={colorForm.product}
                      onValueChange={(value) => setColorForm({ ...colorForm, product: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select product" />
                      </SelectTrigger>
                      <SelectContent>
                        {products.map((prod) => (
                          <SelectItem key={prod._id} value={prod._id}>
                            {prod.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="color">Color *</Label>
                      <Select
                        value={colorForm.color}
                        onValueChange={(value) => setColorForm({ ...colorForm, color: value })}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select color" />
                        </SelectTrigger>
                        <SelectContent>
                          {colors.map((col) => (
                            <SelectItem key={col._id} value={col._id}>
                              <div className="flex items-center gap-2">
                                <div className="w-4 h-4 rounded" style={{ backgroundColor: col.hexCode }} />
                                {col.name}
                              </div>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label htmlFor="size">Size *</Label>
                      <Select
                        value={colorForm.size}
                        onValueChange={(value) => setColorForm({ ...colorForm, size: value })}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select size" />
                        </SelectTrigger>
                        <SelectContent>
                          {sizes.map((s) => (
                            <SelectItem key={s._id} value={s._id}>
                              {s.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="sku">SKU *</Label>
                    <Input
                      id="sku"
                      value={colorForm.sku}
                      onChange={(e) => setColorForm({ ...colorForm, sku: e.target.value.toUpperCase() })}
                      required
                    />
                  </div>
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <Label htmlFor="price">Price *</Label>
                      <Input
                        id="price"
                        type="number"
                        value={colorForm.price}
                        onChange={(e) => setColorForm({ ...colorForm, price: parseFloat(e.target.value) })}
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="comparePrice">Compare Price</Label>
                      <Input
                        id="comparePrice"
                        type="number"
                        value={colorForm.comparePrice}
                        onChange={(e) => setColorForm({ ...colorForm, comparePrice: parseFloat(e.target.value) })}
                      />
                    </div>
                    <div>
                      <Label htmlFor="inventory">Inventory *</Label>
                      <Input
                        id="inventory"
                        type="number"
                        value={colorForm.inventory}
                        onChange={(e) => setColorForm({ ...colorForm, inventory: parseInt(e.target.value) })}
                        required
                      />
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Switch
                      id="colorIsActive"
                      checked={colorForm.isActive}
                      onCheckedChange={(checked) => setColorForm({ ...colorForm, isActive: checked })}
                    />
                    <Label htmlFor="colorIsActive">Active</Label>
                  </div>
                  <div className="flex justify-end gap-2">
                    <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>
                      Cancel
                    </Button>
                    <Button type="submit">
                      {editingItem ? "Update" : "Create"}
                    </Button>
                  </div>
                </form>
              )}

              {/* Product Image Form */}
              {activeTab === "images" && (
                <form onSubmit={handleImageSubmit} className="space-y-4">
                  <div>
                    <Label htmlFor="imageProduct">Product *</Label>
                    <Select
                      value={imageForm.product}
                      onValueChange={(value) => setImageForm({ ...imageForm, product: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select product" />
                      </SelectTrigger>
                      <SelectContent>
                        {products.map((prod) => (
                          <SelectItem key={prod._id} value={prod._id}>
                            {prod.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label htmlFor="productColor">Product Color/Size *</Label>
                    <Select
                      value={imageForm.productColor}
                      onValueChange={(value) => setImageForm({ ...imageForm, productColor: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select color/size combination" />
                      </SelectTrigger>
                      <SelectContent>
                        {productColors.map((pc) => (
                          <SelectItem key={pc._id} value={pc._id}>
                            {typeof pc.color === "string" ? pc.color : pc.color.name} - {typeof pc.size === "string" ? pc.size : pc.size.name} (SKU: {pc.sku})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label htmlFor="imageUrl">Image URL *</Label>
                    <Input
                      id="imageUrl"
                      value={imageForm.imageUrl}
                      onChange={(e) => setImageForm({ ...imageForm, imageUrl: e.target.value })}
                      placeholder="https://example.com/image.jpg"
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="altText">Alt Text</Label>
                    <Input
                      id="altText"
                      value={imageForm.altText}
                      onChange={(e) => setImageForm({ ...imageForm, altText: e.target.value })}
                      placeholder="Image description"
                    />
                  </div>
                  <div>
                    <Label htmlFor="sortOrder">Sort Order</Label>
                    <Input
                      id="sortOrder"
                      type="number"
                      value={imageForm.sortOrder}
                      onChange={(e) => setImageForm({ ...imageForm, sortOrder: parseInt(e.target.value) })}
                    />
                  </div>
                  <div className="flex items-center space-x-2">
                    <Switch
                      id="imageIsActive"
                      checked={imageForm.isActive}
                      onCheckedChange={(checked) => setImageForm({ ...imageForm, isActive: checked })}
                    />
                    <Label htmlFor="imageIsActive">Active</Label>
                  </div>
                  <div className="flex justify-end gap-2">
                    <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>
                      Cancel
                    </Button>
                    <Button type="submit">
                      {editingItem ? "Update" : "Add"}
                    </Button>
                  </div>
                </form>
              )}
            </DialogContent>
          </Dialog>
        </div>
      </div>

      <div className="p-6.5">
        {/* Products Table */}
        {activeTab === "products" && (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead>Category</TableHead>
                <TableHead>Brand</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {products.map((product) => (
                <TableRow key={product._id}>
                  <TableCell className="font-medium">{product.name}</TableCell>
                  <TableCell>{product.category.name}</TableCell>
                  <TableCell>{product.brand || "-"}</TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Badge variant={product.isActive ? "default" : "secondary"}>
                        {product.isActive ? "Active" : "Inactive"}
                      </Badge>
                      {product.isFeatured && <Badge variant="outline">Featured</Badge>}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Button variant="outline" size="sm" onClick={() => handleEditProduct(product)}>
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => handleDelete(product._id, "product")}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}

        {/* Product Colors Table */}
        {activeTab === "colors" && (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Product</TableHead>
                <TableHead>Color</TableHead>
                <TableHead>Size</TableHead>
                <TableHead>SKU</TableHead>
                <TableHead>Price</TableHead>
                <TableHead>Inventory</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {productColors.map((pc) => (
                <TableRow key={pc._id}>
                  <TableCell className="font-medium">
                    {products.find(p => p._id === pc.product)?.name || "Unknown"}
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <div
                        className="w-4 h-4 rounded border"
                        style={{ backgroundColor: typeof pc.color === "string" ? "#ccc" : pc.color.hexCode }}
                      />
                      {typeof pc.color === "string" ? pc.color : pc.color.name}
                    </div>
                  </TableCell>
                  <TableCell>{typeof pc.size === "string" ? pc.size : pc.size.name}</TableCell>
                  <TableCell>{pc.sku}</TableCell>
                  <TableCell>${pc.price}</TableCell>
                  <TableCell>{pc.inventory}</TableCell>
                  <TableCell>
                    <Badge variant={pc.isActive ? "default" : "secondary"}>
                      {pc.isActive ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Button variant="outline" size="sm" onClick={() => handleEditColor(pc)}>
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => handleDelete(pc._id, "color")}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}

        {/* Product Images Table */}
        {activeTab === "images" && (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Product</TableHead>
                <TableHead>Color/Size</TableHead>
                <TableHead>Image</TableHead>
                <TableHead>Alt Text</TableHead>
                <TableHead>Sort Order</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {productImages.map((img) => (
                <TableRow key={img._id}>
                  <TableCell className="font-medium">
                    {products.find(p => p._id === img.product)?.name || "Unknown"}
                  </TableCell>
                  <TableCell>
                    {productColors.find(pc => pc._id === img.productColor)?.sku || "Unknown"}
                  </TableCell>
                  <TableCell>
                    <a href={img.imageUrl} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline">
                      <Image className="h-4 w-4" />
                    </a>
                  </TableCell>
                  <TableCell>{img.altText || "-"}</TableCell>
                  <TableCell>{img.sortOrder}</TableCell>
                  <TableCell>
                    <Badge variant={img.isActive ? "default" : "secondary"}>
                      {img.isActive ? "Active" : "Inactive"}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Button variant="outline" size="sm" onClick={() => handleEditImage(img)}>
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => handleDelete(img._id, "image")}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </div>
    </div>
  );
}