import React, { useState, useRef } from 'react';
import { Upload, X, Image as ImageIcon } from 'lucide-react';
import { Button } from './button';
import { cn } from '@/lib/utils';
import { openWPMediaImage, openWPMediaLogo, openWPMediaFavicon } from '@/lib/wp-media';

interface ImageUploadProps {
  value?: string;
  onChange: (url: string) => void;
  onRemove?: () => void;
  label?: string;
  description?: string;
  accept?: string;
  maxSize?: number; // in MB
  className?: string;
  mediaType?: 'image' | 'logo' | 'favicon'; // Type for WordPress Media Modal
}

export function ImageUpload({
  value,
  onChange,
  onRemove,
  label,
  description,
  accept = 'image/*',
  maxSize = 2,
  className,
  mediaType = 'image',
}: ImageUploadProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = () => {
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    
    const files = Array.from(e.dataTransfer.files);
    if (files.length > 0) {
      handleFile(files[0]);
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      handleFile(files[0]);
    }
  };

  const handleFile = async (file: File) => {
    // Validate file type
    if (!file.type.startsWith('image/')) {
      alert('Please select an image file');
      return;
    }

    // Validate file size
    if (file.size > maxSize * 1024 * 1024) {
      alert(`File size must be less than ${maxSize}MB`);
      return;
    }

    setIsUploading(true);

    try {
      // Create FormData
      const formData = new FormData();
      formData.append('file', file);

      // Get nonce from REST API settings (prioritize WNW_CONFIG for standalone mode)
      const nonce = (window as any).WNW_CONFIG?.nonce ||
                    (window as any).wpApiSettings?.nonce || 
                    (window as any).WooNooW?.nonce ||
                    document.querySelector('meta[name="wp-rest-nonce"]')?.getAttribute('content') || '';

      // Upload to WordPress media library
      const response = await fetch('/wp-json/wp/v2/media', {
        method: 'POST',
        headers: {
          'X-WP-Nonce': nonce,
        },
        credentials: 'include', // Important for standalone mode
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || 'Upload failed');
      }

      const data = await response.json();
      onChange(data.source_url);
    } catch (error) {
      console.error('Upload error:', error);
      alert(error instanceof Error ? error.message : 'Failed to upload image');
    } finally {
      setIsUploading(false);
    }
  };

  const handleRemove = () => {
    if (onRemove) {
      onRemove();
    } else {
      onChange('');
    }
  };

  const handleClick = () => {
    fileInputRef.current?.click();
  };

  const handleWPMedia = () => {
    const openMedia = mediaType === 'logo' ? openWPMediaLogo :
                      mediaType === 'favicon' ? openWPMediaFavicon :
                      openWPMediaImage;
    
    openMedia((file) => {
      onChange(file.url);
    });
  };

  return (
    <div className={cn('space-y-2 rounded-lg p-6 border border-muted-foreground/20', className)}>
      {label && (
        <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
          {label}
        </label>
      )}
      
      {description && (
        <p className="text-sm text-muted-foreground">{description}</p>
      )}

      <div className="space-y-4 relative">
        {value ? (
          // Preview
          <div className="inline-block">
            <img
              src={value}
              alt="Preview"
              className="w-[350px] max-w-full h-auto rounded-lg border"
            />
            <Button
              type="button"
              variant="destructive"
              size="icon"
              className="absolute top-0 right-0 h-fit w-fit shadow-none"
              onClick={handleRemove}
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
        ) : (
          // Upload area
          <div
            className={cn(
              'border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors',
              isDragging
                ? 'border-primary bg-primary/5'
                : 'border-muted-foreground/25 hover:border-primary/50',
              isUploading && 'opacity-50 cursor-not-allowed'
            )}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={handleClick}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept={accept}
              onChange={handleFileSelect}
              className="hidden"
              disabled={isUploading}
            />

            <div className="flex flex-col items-center gap-2">
              {isUploading ? (
                <>
                  <div className="h-12 w-12 rounded-full border-4 border-primary border-t-transparent animate-spin" />
                  <p className="text-sm text-muted-foreground">Uploading...</p>
                </>
              ) : (
                <>
                  <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center">
                    <Upload className="h-6 w-6 text-muted-foreground" />
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm font-medium">
                      Drop image here or click to upload
                    </p>
                    <p className="text-xs text-muted-foreground">
                      Max size: {maxSize}MB
                    </p>
                  </div>
                  <div className="pt-2">
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleWPMedia();
                      }}
                    >
                      <ImageIcon className="h-4 w-4 mr-2" />
                      Choose from Media Library
                    </Button>
                  </div>
                </>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
