'use client';

import { useState, useRef, useCallback } from 'react';
import Image from 'next/image';
import toast from 'react-hot-toast';

interface ImageUploadProps {
  // ✅ Support both single and multiple
  value: string | string[] | null;
  onUpload: (publicId: string, url: string) => void;
  onRemove: (publicId?: string) => void; // ✅ Optional publicId for multiple
  label?: string;
  folder?: string;
  maxSize?: number; // in MB
  accept?: string;
  aspectRatio?: number;
  multiple?: boolean; // ✅ New: Enable multiple uploads
  className?: string;
  disabled?: boolean; // read-only: no picking a file, no removing
}

export default function ImageUpload({
  value,
  onUpload,
  onRemove,
  label = 'Image',
  folder = 'general',
  maxSize = 2,
  accept = 'image/*',
  aspectRatio,
  multiple = false,
  className = '',
  disabled = false,
}: ImageUploadProps) {
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<number | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Convert value to array for consistent handling
  const images = Array.isArray(value) ? value : value ? [value] : [];

  const handleFileSelect = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      const files = e.target.files;
      if (!files || files.length === 0) return;

      const fileList = Array.from(files);
      
      // If not multiple, only take first file
      const filesToUpload = multiple ? fileList : fileList.slice(0, 1);

      // Validate each file
      const validFiles = filesToUpload.filter((file) => {
        // Validate file type
        if (!file.type.startsWith('image/')) {
          toast.error(`"${file.name}" is not an image`);
          return false;
        }

        // Validate file size
        const maxBytes = maxSize * 1024 * 1024;
        if (file.size > maxBytes) {
          toast.error(`"${file.name}" exceeds ${maxSize}MB limit`);
          return false;
        }

        return true;
      });

      if (validFiles.length === 0) return;

      setUploading(true);
      setUploadProgress(0);

      try {
        let uploadedCount = 0;
        const totalFiles = validFiles.length;

        for (const file of validFiles) {
          const formData = new FormData();
          formData.append('file', file);
          formData.append('folder', folder);

          const res = await fetch('/api/cloudinary-upload', {
            method: 'POST',
            body: formData,
          });

          if (!res.ok) {
            const error = await res.json();
            throw new Error(error.message || 'Upload failed');
          }

          const data = await res.json();
          const publicId = data.data.public_id;
          const url = data.data.url;

          // ✅ Call onUpload for each successful upload
          onUpload(publicId, url);

          uploadedCount++;
          setUploadProgress(Math.round((uploadedCount / totalFiles) * 100));
        }

        toast.success(
          multiple 
            ? `${uploadedCount} image(s) uploaded successfully`
            : 'Image uploaded successfully'
        );
      } catch (error) {
        console.error('Upload error:', error);
        toast.error(error instanceof Error ? error.message : 'Failed to upload image');
      } finally {
        setUploading(false);
        setUploadProgress(null);
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
      }
    },
    [maxSize, folder, multiple, onUpload]
  );

  const handleRemove = useCallback(
    (publicId?: string) => {
      if (disabled) return;
      if (multiple && publicId) {
        // ✅ Multiple mode: remove specific image
        onRemove(publicId);
      } else {
        // ✅ Single mode: remove the only image
        onRemove();
      }
    },
    [multiple, onRemove, disabled]
  );

  return (
    <div className={className}>
      {label && (
        <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
          {label}
          {multiple && images.length > 0 && (
            <span className="ml-2 text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
              ({images.length} uploaded)
            </span>
          )}
        </label>
      )}

      <div className="space-y-3">
        {/* Drop Zone / Upload Area */}
        <div
          className={`relative border-2 border-dashed rounded-lg p-6 transition-all ${
            uploading || disabled ? 'opacity-50 pointer-events-none' : 'cursor-pointer hover:opacity-80'
          }`}
          style={{
            borderColor: 'var(--color-border)',
            background: 'var(--color-surface-alt)',
          }}
          onClick={() => !disabled && fileInputRef.current?.click()}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept={accept}
            multiple={multiple}
            onChange={handleFileSelect}
            disabled={disabled}
            className="hidden"
          />

          <div className="flex flex-col items-center justify-center gap-2">
            {uploading ? (
              <>
                <svg
                  className="animate-spin h-8 w-8"
                  style={{ color: 'var(--color-cta)' }}
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                    fill="none"
                  />
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  />
                </svg>
                {uploadProgress !== null ? (
                  <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
                    Uploading... {uploadProgress}%
                  </span>
                ) : (
                  <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
                    Uploading...
                  </span>
                )}
              </>
            ) : (
              <>
                <svg
                  className="h-10 w-10"
                  style={{ color: 'var(--color-text-tertiary)' }}
                  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"
                  />
                </svg>
                <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
                  {multiple ? 'Drop images here or click to browse' : 'Drop image here or click to browse'}
                </span>
                <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                  {multiple 
                    ? `Supports multiple images, max ${maxSize}MB each`
                    : `Max ${maxSize}MB (JPG, PNG, WEBP)`
                  }
                </span>
              </>
            )}
          </div>
        </div>

        {/* Image Preview - Single Mode */}
        {!multiple && images.length === 1 && (
          <div className="relative rounded-lg overflow-hidden border-2" style={{ 
            borderColor: 'var(--color-border)',
            width: aspectRatio ? '100%' : '120px',
            height: aspectRatio ? 'auto' : '120px',
            maxWidth: aspectRatio ? '200px' : '120px',
            aspectRatio: aspectRatio ? aspectRatio : '1/1',
          }}>
            <Image
              src={`https://res.cloudinary.com/${process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME}/image/upload/${images[0]}.webp`}
              alt="Uploaded image"
              fill
              className="object-cover"
              sizes="200px"
            />
            <button
              type="button"
              onClick={() => handleRemove()}
              className="absolute top-2 right-2 p-1 rounded-full bg-red-500/80 text-white hover:bg-red-500 transition-all"
              title="Remove image"
            >
              <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        )}

        {/* Image Preview - Multiple Mode (Grid) */}
        {multiple && images.length > 0 && (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
            {images.map((imageUrl, index) => {

              return (
                <div
                  key={index}
                  className="relative group rounded-lg overflow-hidden border-2"
                  style={{
                    borderColor: 'var(--color-border)',
                    aspectRatio: aspectRatio || '1/1',
                  }}
                >
                  <Image
                    src={`https://res.cloudinary.com/${process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME}/image/upload/${imageUrl}.webp`}
                    alt={`Image ${index + 1}`}
                    fill
                    className="object-cover"
                    sizes="(max-width: 768px) 50vw, 25vw"
                  />

                  {/* Overlay */}
                  <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                    <button
                      type="button"
                      onClick={() => handleRemove(imageUrl)}
                      className="p-1.5 rounded-full bg-red-500/80 text-white hover:bg-red-500 transition-all"
                      title="Remove image"
                    >
                      <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </button>
                  </div>

                  {/* Position Badge */}
                  <div className="absolute bottom-2 left-2 px-2 py-0.5 rounded text-xs font-medium bg-black/50 text-white">
                    {index + 1}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}