import { Button } from "@/components/ui/button";
import { apiFetch } from '@/utils/api';
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Loader2, Link as LinkIcon, Image as ImageIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { ImageDropzone } from "./ImageDropzone";
import { SortableImage } from "./SortableImage";
import { CopyButton } from "./CopyButton";
import { ProductImageSortable, Product } from "../../types";
import { DroppableContainer } from "../DroppableContainer";
import { SortableContext, horizontalListSortingStrategy } from '@dnd-kit/sortable';
import { useQuery } from "@tanstack/react-query";
import config from "@/config";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { AuthedImage } from "@/components/ui/authed-image";
import { useState, useMemo } from "react";

interface ReusableImage {
  id: number;
  name: string;
  image_url: string;
  is_global: boolean;
  company: string | null;
}

interface ProductCardProps {
  product: Product;
  index: number;
  urlInput: string;
  processingUrl: boolean;
  activeDroppableId: string | null;
  activeId: string | null;
  productImages: ProductImageSortable[];
  fileInputRef: React.RefObject<HTMLInputElement>;
  onUrlInputChange: (value: string) => void;
  onUrlSubmit: (e: React.FormEvent) => void;
  onImageUpload: (files: FileList | File[]) => void;
  onDragOver: (e: React.DragEvent) => void;
  onRemoveImage: (id: string) => void;
  getProductContainerClasses: () => string;
  findContainer: (id: string) => string | null;
  handleAddImageFromUrl: (productIndex: number, url: string) => void;
}

export const ProductCard = ({
  product,
  index,
  urlInput,
  processingUrl,
  activeDroppableId,
  activeId,
  productImages,
  fileInputRef,
  onUrlInputChange,
  onUrlSubmit,
  onImageUpload,
  onDragOver,
  onRemoveImage,
  getProductContainerClasses,
  findContainer,
  handleAddImageFromUrl
}: ProductCardProps) => {
  const [isReusableDialogOpen, setIsReusableDialogOpen] = useState(false);

  // Function to get images for this product
  const getProductImages = () => {
    return productImages.filter(img => img.productIndex === index);
  };

  // Convert string container to number for internal comparison
  const getContainerAsNumber = (id: string): number | null => {
    const result = findContainer(id);
    return result !== null ? parseInt(result) : null;
  };

  // Fetch reusable images
  const { data: reusableImages, isLoading: isLoadingReusable } = useQuery<ReusableImage[]>({
    queryKey: ["reusable-images"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/reusable-images`);
      if (!response.ok) {
        throw new Error("Failed to fetch reusable images");
      }
      return response.json();
    },
  });

  // Filter reusable images based on product's company
  const availableReusableImages = useMemo(() => {
    if (!reusableImages) return [];
    return reusableImages.filter(img => 
      img.is_global || img.company === product.company
    );
  }, [reusableImages, product.company]);

  // Handle adding a reusable image
  const handleAddReusableImage = (imageUrl: string) => {
    handleAddImageFromUrl(index, imageUrl);
    setIsReusableDialogOpen(false);
  };

  return (
    <Card 
      className={cn(
        "p-3 transition-colors",
        activeDroppableId === `product-${index}` && activeId && 
        getContainerAsNumber(activeId) !== index &&
        "ring-2 ring-primary bg-primary/5"
      )}
    >
      <CardContent className="p-0">
        <div className="flex flex-col gap-2">
          <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-2">
            <div className="flex flex-col lg:flex-row lg:items-baseline gap-0.5 lg:gap-4">
              <h3 className="text-base font-medium">{product.name || `Product #${index + 1}`}</h3>
              <div className="text-xs lg:text-sm text-muted-foreground">
                <span className="font-medium">UPC:</span> {product.upc || 'N/A'}
                <CopyButton text={product.upc || ''} itemKey={`upc-${index}`} />
                {' | '}
                <span className="font-medium">Supplier #:</span> {product.supplier_no || 'N/A'}
                <CopyButton text={product.supplier_no || ''} itemKey={`supplier-${index}`} />
              </div>
            </div>
            <div className="flex-shrink-0">
              <form 
                className="flex items-center gap-2"
                onSubmit={onUrlSubmit}
              >
                {getProductImages().length === 0 && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="h-8 whitespace-nowrap flex gap-1 items-center text-xs"
                    onClick={() => setIsReusableDialogOpen(true)}
                  >
                    <ImageIcon className="h-3.5 w-3.5" />
                    Select from Library
                  </Button>
                )}
                <Input
                  placeholder="Add image from URL"
                  value={urlInput}
                  onChange={(e) => onUrlInputChange(e.target.value)}
                  className="!text-xs h-8 w-[180px]"
                />
                <Button 
                  type="submit"
                  size="sm"
                  className="h-8 whitespace-nowrap flex gap-1 items-center text-xs"
                  disabled={processingUrl || !urlInput}
                >
                  {processingUrl ? 
                    <Loader2 className="h-3.5 w-3.5 animate-spin" /> : 
                    <LinkIcon className="h-3.5 w-3.5" />}
                  Add
                </Button>
              </form>
            </div>
          </div>
        
          <div className="flex flex-col sm:flex-row gap-2">
            <div className="flex flex-row gap-2 items-center gap-4">
              <ImageDropzone 
                productIndex={index} 
                onDrop={onImageUpload}
              />
            </div>
            
            <div 
              className={getProductContainerClasses()}
              style={{ 
                pointerEvents: 'auto',
                touchAction: 'none',
                minHeight: '100px',
              }}
              onDragOver={onDragOver}
            >
              <DroppableContainer 
                id={`product-${index}`} 
                isEmpty={getProductImages().length === 0}
              >
                {getProductImages().length > 0 ? (
                  <SortableContext 
                    items={getProductImages().map(img => img.id)}
                    strategy={horizontalListSortingStrategy}
                  >
                    {getProductImages().map((image, imgIndex) => (
                      <SortableImage 
                        key={image.id} 
                        image={image} 
                        productIndex={index}
                        imgIndex={imgIndex}
                        productName={product.name}
                        removeImage={onRemoveImage}
                      />
                    ))}
                  </SortableContext>
                ) : (
                  <div className="w-full h-full" data-empty-placeholder="true"></div>
                )}
              </DroppableContainer>
            </div>
          </div>
          
          <Input
            ref={fileInputRef}
            type="file"
            className="hidden"
            accept="image/*"
            multiple
            onChange={(e) => e.target.files && onImageUpload(e.target.files)}
          />
        </div>
      </CardContent>

      {/* Reusable Images Dialog */}
      <Dialog open={isReusableDialogOpen} onOpenChange={setIsReusableDialogOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>Select from Image Library</DialogTitle>
            <DialogDescription>
              Choose a global or company-specific image to add to this product.
            </DialogDescription>
          </DialogHeader>
          <ScrollArea className="h-[400px] pr-4">
            {isLoadingReusable ? (
              <div className="flex items-center justify-center h-full">
                <Loader2 className="h-8 w-8 animate-spin" />
              </div>
            ) : availableReusableImages.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full text-muted-foreground">
                <ImageIcon className="h-8 w-8 mb-2" />
                <p>No reusable images available</p>
              </div>
            ) : (
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                {availableReusableImages.map((image) => (
                  <div
                    key={image.id}
                    className="group relative aspect-square border rounded-lg overflow-hidden cursor-pointer hover:ring-2 hover:ring-primary"
                    onClick={() => handleAddReusableImage(image.image_url)}
                  >
                    <AuthedImage
                      src={image.image_url}
                      alt={image.name}
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors" />
                    <div className="absolute bottom-0 left-0 right-0 p-2 bg-gradient-to-t from-black/60 to-transparent">
                      <p className="text-xs text-white truncate">{image.name}</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </ScrollArea>
        </DialogContent>
      </Dialog>
    </Card>
  );
};
