/* eslint-disable @next/next/no-img-element -- Local preview data URLs; next/image migration is out of scope. */
import { useState } from 'react';
import { Modal, Input, Button } from './ui';

export default function UploadImageModal({ isOpen, onClose, onUpload, currentImage }) {
  const [uploadMethod, setUploadMethod] = useState('url');
  const [imageUrl, setImageUrl] = useState(currentImage || '');
  const [dragActive, setDragActive] = useState(false);
  const [uploading, setUploading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!imageUrl.trim()) return;

    setUploading(true);
    try {
      await onUpload(imageUrl);
      onClose();
    } catch (error) {
      console.error('Upload failed:', error);
    } finally {
      setUploading(false);
    }
  };

  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileUpload(e.dataTransfer.files[0]);
    }
  };

  const handleFileUpload = (file) => {
    if (file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = (event) => {
        setImageUrl(event.target.result);
        setUploadMethod('file');
      };
      reader.readAsDataURL(file);
    }
  };

  const handleFileInput = (e) => {
    if (e.target.files && e.target.files[0]) {
      handleFileUpload(e.target.files[0]);
    }
  };

  return (
    <Modal open={isOpen} onClose={onClose} title="Upload Hero Image" size="md">
      <form onSubmit={handleSubmit}>
        <div
          className="flex space-x-1 mb-6 rounded-lg p-1"
          style={{
            backgroundColor: 'var(--bg-tertiary)',
            border: '1px solid var(--border)',
          }}
        >
          <button
            type="button"
            onClick={() => setUploadMethod('url')}
            className="flex-1 py-2 px-3 rounded-md text-sm font-medium transition-colors"
            style={{
              backgroundColor:
                uploadMethod === 'url' ? 'var(--bg-primary)' : 'transparent',
              color:
                uploadMethod === 'url'
                  ? 'var(--text-primary)'
                  : 'var(--text-secondary)',
              boxShadow: uploadMethod === 'url' ? 'var(--elevation-ambient)' : 'none',
            }}
          >
            Image URL
          </button>
          <button
            type="button"
            onClick={() => setUploadMethod('file')}
            className="flex-1 py-2 px-3 rounded-md text-sm font-medium transition-colors"
            style={{
              backgroundColor:
                uploadMethod === 'file' ? 'var(--bg-primary)' : 'transparent',
              color:
                uploadMethod === 'file'
                  ? 'var(--text-primary)'
                  : 'var(--text-secondary)',
              boxShadow: uploadMethod === 'file' ? 'var(--elevation-ambient)' : 'none',
            }}
          >
            Upload File
          </button>
        </div>

        {uploadMethod === 'url' ? (
          <div className="mb-6">
            <Input
              label="Image URL"
              type="url"
              value={imageUrl}
              onChange={(e) => setImageUrl(e.target.value)}
              placeholder="https://example.com/image.jpg"
            />
          </div>
        ) : (
          <div className="mb-6">
            <label
              className="block text-sm font-medium mb-2"
              style={{ color: 'var(--text-primary)' }}
            >
              Upload Image
            </label>
            <div
              className="border-2 border-dashed rounded-lg p-6 text-center transition-colors"
              style={{
                borderColor: dragActive ? 'var(--accent-ember)' : 'var(--border)',
                backgroundColor: dragActive ? 'rgba(var(--ember-rim-subtle), 0.08)' : 'transparent',
              }}
              onDragEnter={handleDrag}
              onDragLeave={handleDrag}
              onDragOver={handleDrag}
              onDrop={handleDrop}
            >
              <svg
                className="w-12 h-12 mx-auto mb-4"
                style={{ color: 'var(--text-tertiary)' }}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                />
              </svg>
              <p className="mb-2" style={{ color: 'var(--text-secondary)' }}>
                Drag and drop an image here, or
              </p>
              <label
                className="inline-block px-4 py-2 rounded-lg cursor-pointer transition-colors"
                style={{
                  backgroundColor: 'var(--accent-ember)',
                  color: 'white',
                }}
              >
                Choose File
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleFileInput}
                  className="hidden"
                />
              </label>
              <p className="text-xs mt-2" style={{ color: 'var(--text-tertiary)' }}>
                PNG, JPG, GIF up to 10MB
              </p>
            </div>
          </div>
        )}

        {imageUrl && (
          <div className="mb-6">
            <label
              className="block text-sm font-medium mb-2"
              style={{ color: 'var(--text-primary)' }}
            >
              Preview
            </label>
            <div
              className="relative rounded-lg overflow-hidden"
              style={{ backgroundColor: 'var(--bg-tertiary)' }}
            >
              <img
                src={imageUrl}
                alt="Preview"
                className="w-full h-32 object-cover"
                onError={(e) => {
                  e.target.src =
                    'https://via.placeholder.com/400x128/f3f4f6/6b7280?text=Invalid+Image';
                }}
              />
            </div>
          </div>
        )}

        <div className="flex space-x-3">
          <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
            Cancel
          </Button>
          <Button
            type="submit"
            variant="primary"
            disabled={!imageUrl.trim() || uploading}
            loading={uploading}
            className="flex-1"
          >
            {uploading ? 'Uploading...' : 'Upload Image'}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
