import React, { useState } from "react";
import Cropper from "react-easy-crop";

interface ImagePreviewProps {
  fileUrl: string;
  fileName: string;
  fullscreen?: boolean;
}

const ImagePreview: React.FC<ImagePreviewProps> = ({ fileUrl, fileName, fullscreen }) => {
  const [rotation, setRotation] = useState(0);
  const [zoom, setZoom] = useState(1);
  const [crop, setCrop] = useState({ x: 0, y: 0 });
  const [showCrop, setShowCrop] = useState(false);

  return (
    <div style={{ width: fullscreen ? '100vw' : 500, height: fullscreen ? '100vh' : 400, background: "#222", position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ position: "relative", width: fullscreen ? '80vw' : 400, height: fullscreen ? '80vh' : 300, background: "#222", margin: '0 auto' }}>
        {showCrop ? (
          <Cropper
            image={fileUrl}
            crop={crop}
            zoom={zoom}
            rotation={rotation}
            aspect={4 / 3}
            onCropChange={setCrop}
            onZoomChange={setZoom}
            onRotationChange={setRotation}
          />
        ) : (
          <img
            src={fileUrl}
            alt={fileName}
            style={{
              maxWidth: '100%',
              maxHeight: '100%',
              transform: `rotate(${rotation}deg) scale(${zoom})`,
              display: 'block',
              margin: '0 auto',
              background: '#222',
            }}
            draggable={false}
          />
        )}
      </div>
      <div style={{ marginTop: 16, display: "flex", gap: 10, flexWrap: 'wrap', justifyContent: 'center' }}>
        <button onClick={() => setRotation((r) => r - 90)}>Ruota -90°</button>
        <button onClick={() => setRotation((r) => r + 90)}>Ruota +90°</button>
        <button onClick={() => setZoom((z) => Math.max(0.1, z - 0.1))}>- Zoom</button>
        <button onClick={() => setZoom((z) => Math.min(5, z + 0.1))}>+ Zoom</button>
        <button onClick={() => setShowCrop((v) => !v)}>{showCrop ? 'Disabilita crop' : 'Abilita crop'}</button>
        <a href={fileUrl} download={fileName}>
          <button>Download</button>
        </a>
      </div>
    </div>
  );
};

export default ImagePreview;
