'use client';

import { useCallback, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import Image from 'next/image';

interface ImageUploadProps {
  onImageSelect: (file: File | null) => void;
  accept?: string;
  maxSizeMB?: number;
  aspectRatio?: string;
  placeholder?: string;
  currentImageUrl?: string;
}

export default function ImageUpload({
  onImageSelect,
  accept = 'image/*',
  maxSizeMB = 5,
  aspectRatio = '1:1',
  placeholder = 'Drop an image here or click to select',
  currentImageUrl,
}: ImageUploadProps) {
  const [preview, setPreview] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const onDrop = useCallback((acceptedFiles: File[], rejectedFiles: any[]) => {
    setError(null);

    if (rejectedFiles.length > 0) {
      const rejection = rejectedFiles[0];
      if (rejection.errors?.[0]?.code === 'file-too-large') {
        setError(`File is too large. Maximum size is ${maxSizeMB}MB.`);
      } else if (rejection.errors?.[0]?.code === 'file-invalid-type') {
        const allowedTypes = accept.split(',').map(type => type.trim()).join(', ');
        setError(`Invalid file type. Supported formats: ${allowedTypes.replace(/image\//g, '').toUpperCase()}.`);
      } else {
        setError('File rejected. Please try another file.');
      }
      return;
    }

    const file = acceptedFiles[0];
    if (file) {
      // Additional client-side validation for file type
      const allowedTypes = accept.split(',').map(type => type.trim());
      if (!allowedTypes.includes(file.type)) {
        const supportedFormats = allowedTypes.map(type => type.replace('image/', '').toUpperCase()).join(', ');
        setError(`Invalid file type. Your file is ${file.type}. Supported formats: ${supportedFormats}.`);
        return;
      }

      // Create preview
      const previewUrl = URL.createObjectURL(file);
      setPreview(previewUrl);
      onImageSelect(file);
    }
  }, [onImageSelect, maxSizeMB, accept]);

  // Build proper accept object for dropzone based on specific MIME types
  const acceptTypes = accept.split(',').map(type => type.trim());
  const dropzoneAccept = acceptTypes.reduce((acc, type) => {
    acc[type] = []; // Empty array means accept files with this MIME type
    return acc;
  }, {} as Record<string, string[]>);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: dropzoneAccept,
    maxFiles: 1,
    maxSize: maxSizeMB * 1024 * 1024, // Convert MB to bytes
  });

  const clearImage = () => {
    setPreview(null);
    setError(null);
    onImageSelect(null);
  };

  const aspectRatioClass = {
    '1:1': 'aspect-square',
    '3:4': 'aspect-[3/4]',
    '4:3': 'aspect-[4/3]',
    '16:9': 'aspect-video',
  }[aspectRatio] || 'aspect-square';

  const displayImage = preview || currentImageUrl;

  return (
    <div className="space-y-4">
      <div
        {...getRootProps()}
        className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors ${
          isDragActive
            ? 'border-blue-400 bg-blue-50 dark:bg-blue-900/20'
            : error
            ? 'border-red-300 bg-red-50 dark:bg-red-900/20'
            : 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
        } ${displayImage ? 'p-0 border-0' : ''}`}
      >
        <input {...getInputProps()} />
        
        {displayImage ? (
          <div className={`relative ${aspectRatioClass} rounded-lg overflow-hidden group`}>
            <Image
              src={displayImage}
              alt="Preview"
              fill
              className="object-cover"
            />
            <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-50 transition-all duration-200 flex items-center justify-center">
              <div className="opacity-0 group-hover:opacity-100 transition-opacity duration-200 space-x-2">
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    clearImage();
                  }}
                  className="px-3 py-1 bg-red-600 text-white text-sm rounded hover:bg-red-700 transition-colors"
                >
                  Remove
                </button>
                <span className="text-white text-sm">
                  or click to change
                </span>
              </div>
            </div>
          </div>
        ) : (
          <div className="space-y-2">
            <div className="text-4xl theme-text">📸</div>
            <div className="theme-text">
              {isDragActive ? (
                <p>Drop the image here...</p>
              ) : (
                <p>{placeholder}</p>
              )}
            </div>
            <p className="text-sm text-gray-500">
              Supports {acceptTypes.map(type => type.replace('image/', '').toUpperCase()).join(', ')} up to {maxSizeMB}MB
            </p>
          </div>
        )}
      </div>

      {error && (
        <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
      )}
    </div>
  );
}