import { useState, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { Upload, X, Loader2 } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { cn } from "@/lib/utils";
import { useToast } from "@/components/ui/use-toast";

interface ImageUploadFieldProps {
  images?: string[];
  onChange: (images: string[]) => void;
  disabled?: boolean;
  bucket?: string;
}

export function ImageUploadField({
  images = [],
  onChange,
  disabled = false,
  bucket = "status-update-images",
}: ImageUploadFieldProps) {
  const [uploading, setUploading] = useState(false);
  const { toast } = useToast();
  const safeImages = Array.isArray(images) ? images : [];

  const onDrop = useCallback(
    async (acceptedFiles: File[]) => {
      if (disabled) return;
      setUploading(true);
      const newImages: string[] = [];
      const errors: string[] = [];

      for (const file of acceptedFiles) {
        try {
          const fileExt = file.name.split(".").pop();
          const fileName = `${Math.random().toString(36).substring(2)}_${Date.now()}.${fileExt}`;

          const { error: uploadError } = await supabase.storage
            .from(bucket)
            .upload(fileName, file);

          if (uploadError) throw uploadError;

          const {
            data: { publicUrl },
          } = supabase.storage.from(bucket).getPublicUrl(fileName);

          newImages.push(publicUrl);
        } catch (error) {
          console.error("Error uploading image:", error);
          errors.push(file.name);
        }
      }

      if (errors.length > 0) {
        toast({
          variant: "destructive",
          title: "Upload Failed",
          description: `Failed to upload: ${errors.join(", ")}`,
        });
      }

      if (newImages.length > 0) {
        onChange([...safeImages, ...newImages]);
      }

      setUploading(false);
    },
    [safeImages, onChange, disabled, toast, bucket]
  );

  const removeImage = (indexToRemove: number) => {
    if (disabled) return;
    onChange(safeImages.filter((_, index) => index !== indexToRemove));
  };

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: { "image/*": [".png", ".jpg", ".jpeg", ".gif", ".webp"] },
    disabled: disabled || uploading,
    maxSize: 5242880,
  });

  return (
    <div className="space-y-4">
      <div
        {...getRootProps()}
        className={cn(
          "border-2 border-dashed rounded-lg p-6 transition-colors text-center cursor-pointer",
          isDragActive
            ? "border-primary bg-primary/5"
            : "border-border hover:bg-muted/50",
          disabled && "opacity-50 cursor-not-allowed hover:bg-transparent"
        )}
      >
        <input {...getInputProps()} />
        <div className="flex flex-col items-center justify-center space-y-2 text-muted-foreground">
          {uploading ? (
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
          ) : (
            <Upload className="w-8 h-8" />
          )}
          <div className="text-sm">
            {uploading ? (
              <p>Uploading images...</p>
            ) : isDragActive ? (
              <p className="text-primary font-medium">Drop images here</p>
            ) : (
              <p>
                <span className="font-semibold text-primary">Click to upload</span>{" "}
                or drag and drop
              </p>
            )}
          </div>
          <p className="text-xs text-muted-foreground/70">PNG, JPG, GIF up to 5MB</p>
        </div>
      </div>

      {safeImages.length > 0 && (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
          {safeImages.map((url, index) => (
            <div
              key={url}
              className="group relative aspect-square rounded-md overflow-hidden border bg-muted"
            >
              <img
                src={url}
                alt={`Uploaded ${index + 1}`}
                className="w-full h-full object-cover"
              />
              {!disabled && (
                <button
                  type="button"
                  onClick={() => removeImage(index)}
                  className="absolute top-1 right-1 p-1 bg-background/90 rounded-full shadow-sm opacity-0 group-hover:opacity-100 transition-opacity hover:bg-destructive/10 text-muted-foreground hover:text-destructive"
                >
                  <X className="w-4 h-4" />
                </button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
