import { useRef, useState } from 'react';

export function UploadTab({ onAddImage }) {
  const fileInputRef = useRef(null);
  const [isDragging, setIsDragging] = useState(false);
  const [isUploading, setIsUploading] = useState(false);

  const handleFiles = async (files) => {
    const file = files[0];
    if (!file) return;

    // Validate file type
    const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
    if (!validTypes.includes(file.type)) {
      alert('Please upload a JPEG, PNG, or WebP image');
      return;
    }

    // Validate file size (20MB)
    if (file.size > 20 * 1024 * 1024) {
      alert('File size must be under 20MB');
      return;
    }

    setIsUploading(true);

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

      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error('Upload failed');
      }

      const data = await response.json();

      // Add the uploaded image to canvas (use preview for canvas)
      onAddImage({
        type: 'image',
        x: 75,
        y: 75,
        width: 150,
        height: 150,
        rotation: 0,
        src: data.preview.url,
        originalUrl: data.original.url,
      });
    } catch (error) {
      console.error('Upload error:', error);
      alert('Failed to upload image. Please try again.');
    } finally {
      setIsUploading(false);
    }
  };

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

  const handleDragLeave = (e) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setIsDragging(false);
    handleFiles(e.dataTransfer.files);
  };

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

  const handleFileChange = (e) => {
    handleFiles(e.target.files);
  };

  return (
    <div>
      <h3 style={{ margin: '0 0 1rem 0', fontSize: '14px', color: 'var(--text-primary)' }}>
        Upload Image
      </h3>

      <div
        onClick={handleClick}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        style={{
          border: `2px dashed ${isDragging ? 'var(--accent)' : 'var(--border)'}`,
          borderRadius: 'var(--radius-md)',
          padding: '2rem 1rem',
          textAlign: 'center',
          cursor: 'pointer',
          background: isDragging ? 'var(--accent-bg)' : 'var(--bg-primary)',
          transition: 'all 0.15s ease',
          marginBottom: '1rem',
        }}
      >
        <div style={{ fontSize: '32px', marginBottom: '0.5rem' }}>📁</div>
        <div style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '0.25rem' }}>
          Click to upload or drag and drop
        </div>
        <div style={{ fontSize: '11px', color: 'var(--text-muted)' }}>
          JPEG, PNG, WebP (max 20MB)
        </div>
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        onChange={handleFileChange}
        style={{ display: 'none' }}
      />

      {isUploading && (
        <div style={{
          padding: '0.75rem',
          background: 'var(--accent-bg)',
          borderRadius: 'var(--radius-sm)',
          fontSize: '12px',
          color: 'var(--accent)',
          textAlign: 'center',
        }}>
          Uploading...
        </div>
      )}

      <div style={{
        marginTop: '1rem',
        padding: '0.75rem',
        background: 'var(--bg-primary)',
        borderRadius: 'var(--radius-sm)',
        fontSize: '11px',
        color: 'var(--text-muted)',
        lineHeight: '1.4',
      }}>
        <strong>Tip:</strong> After uploading, you can remove the background from your image using the background removal tool.
      </div>
    </div>
  );
}
