import React, { useState } from 'react';
import { Button } from '../../ui/button';
import { ImageCropper } from '../../ui/ImageCropper';
import { X, Upload, AlertTriangle, Image as ImageIcon } from 'lucide-react';
import { useToast } from '../../../context/ToastContext';

interface CoverArtUploadModalProps {
  onClose: () => void;
  onSave: (imageDataUrl: string) => void;
  currentImage?: string;
}

// Helper to crop image
const createImage = (url: string): Promise<HTMLImageElement> =>
  new Promise((resolve, reject) => {
    const image = new Image();
    image.addEventListener('load', () => resolve(image));
    image.addEventListener('error', (error) => reject(error));
    image.setAttribute('crossOrigin', 'anonymous');
    image.src = url;
  });

async function getCroppedImg(
  imageSrc: string,
  pixelCrop: any,
): Promise<string> {
  const image = await createImage(imageSrc);
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  if (!ctx) return '';

  canvas.width = pixelCrop.width;
  canvas.height = pixelCrop.height;

  ctx.drawImage(
    image,
    pixelCrop.x,
    pixelCrop.y,
    pixelCrop.width,
    pixelCrop.height,
    0,
    0,
    pixelCrop.width,
    pixelCrop.height,
  );

  return new Promise((resolve) => {
    canvas.toBlob((blob) => {
      if (!blob) return;
      resolve(URL.createObjectURL(blob));
    }, 'image/jpeg');
  });
}

export const CoverArtUploadModal: React.FC<CoverArtUploadModalProps> = ({
  onClose,
  onSave,
  currentImage,
}) => {
  const { addToast } = useToast();
  const [imageSrc, setImageSrc] = useState<string | null>(null);
  const [showCropper, setShowCropper] = useState(false);

  const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      const url = URL.createObjectURL(file);

      // Basic resolution check
      const img = new Image();
      img.onload = () => {
        if (img.width < 1000 || img.height < 1000) {
          addToast('Warning: Image is smaller than 1000x1000px', 'info');
        }
        setImageSrc(url);
        setShowCropper(true);
      };
      img.src = url;
    }
  };

  const onCropComplete = async (croppedAreaPixels: any) => {
    if (imageSrc) {
      try {
        const croppedImage = await getCroppedImg(imageSrc, croppedAreaPixels);
        onSave(croppedImage);
        onClose();
      } catch (e) {
        addToast('Failed to crop image', 'error');
      }
    }
  };

  if (showCropper && imageSrc) {
    return (
      <ImageCropper
        imageSrc={imageSrc}
        aspectRatio={1}
        onCancel={() => setShowCropper(false)}
        onCropComplete={onCropComplete}
      />
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div
        className="absolute inset-0 bg-kodo-void/90 backdrop-blur-sm"
        onClick={onClose}
      ></div>
      <div className="relative w-full max-w-lg bg-kodo-graphite border border-kodo-steel rounded-xl shadow-2xl animate-scaleIn overflow-hidden">
        <div className="p-4 border-b border-kodo-steel bg-kodo-ink flex justify-between items-center">
          <h3 className="font-bold text-white flex items-center gap-2">
            <ImageIcon className="w-4 h-4 text-kodo-cyan" /> Upload Artwork
          </h3>
          <button onClick={onClose}>
            <X className="w-5 h-5 text-gray-400 hover:text-white" />
          </button>
        </div>

        <div className="p-8 text-center">
          <div className="w-32 h-32 bg-kodo-ink border-2 border-dashed border-kodo-steel rounded-xl mx-auto mb-6 flex items-center justify-center relative overflow-hidden group">
            {currentImage ? (
              <img src={currentImage} className="w-full h-full object-cover" />
            ) : (
              <Upload className="w-8 h-8 text-gray-500" />
            )}
            <div className="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
              <span className="text-xs font-bold text-white">Change</span>
            </div>
          </div>

          <div className="space-y-2 mb-8">
            <h4 className="text-white font-bold">Drag & Drop or Browse</h4>
            <p className="text-gray-400 text-sm">
              Recommended: 3000x3000px, JPG or PNG.
              <br />
              Minimum: 1000x1000px.
            </p>
            <div className="flex items-center justify-center gap-2 text-kodo-gold text-xs bg-kodo-gold/10 p-2 rounded max-w-xs mx-auto mt-4">
              <AlertTriangle className="w-3 h-3" />
              High quality artwork increases plays by 40%
            </div>
          </div>

          <div className="relative">
            <Button variant="primary" className="w-full">
              Select File
            </Button>
            <input
              type="file"
              accept="image/*"
              className="absolute inset-0 opacity-0 cursor-pointer"
              onChange={onFileChange}
            />
          </div>
        </div>
      </div>
    </div>
  );
};
