'use client';

import React, { useState, useRef, useEffect } from 'react';
import Image from 'next/image';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
import styles from './ImageCropEditor.module.css';

interface ImageCropEditorProps {
  file: File;
  onCropApply: (croppedDataUrl: string) => void;
  onCancel: () => void;
  /** Aspect ratio for the crop area (width/height). Defaults to 16/9. */
  aspectRatio?: number;
}

const DEFAULT_ASPECT_RATIO = 16 / 9;

export default function ImageCropEditor({
  file,
  onCropApply,
  onCancel,
  aspectRatio = DEFAULT_ASPECT_RATIO,
}: ImageCropEditorProps) {
  const [imageUrl, setImageUrl] = useState<string>('');
  const [cropper, setCropper] = useState<Cropper | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const imageRef = useRef<HTMLImageElement>(null);

  // Load image from file
  useEffect(() => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const url = e.target?.result as string;
      setImageUrl(url);
    };
    reader.readAsDataURL(file);
  }, [file]);

  // Initialize Cropper when image loads
  useEffect(() => {
    if (!imageUrl || !imageRef.current) return;

    // Cleanup old cropper instance
    return () => {
      if (cropper) {
        cropper.destroy();
      }
    };
  }, [imageUrl, cropper]);

  // Create new cropper instance when image URL changes
  useEffect(() => {
    if (!imageUrl || !imageRef.current) return;

    const img = imageRef.current;
    const newCropper = new Cropper(img, {
      aspectRatio,
      viewMode: 1,
      autoCropArea: 0.8,
      responsive: true,
      restore: true,
      guides: true,
      center: true,
      highlight: true,
      cropBoxMovable: true,
      cropBoxResizable: true,
      toggleDragModeOnDblclick: true,
      background: true,
    });

    setCropper(newCropper);
  }, [imageUrl, aspectRatio]);

  // Handle apply crop
  const handleApplyCrop = async () => {
    if (!cropper) return;

    setIsProcessing(true);
    try {
      const canvas = cropper.getCroppedCanvas({
        maxWidth: 4096,
        maxHeight: 4096,
        fillColor: '#fff',
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high',
      });

      canvas.toBlob(
        (blob) => {
          if (blob) {
            const reader = new FileReader();
            reader.onload = (e) => {
              const dataUrl = e.target?.result as string;
              onCropApply(dataUrl);
            };
            reader.readAsDataURL(blob);
          }
        },
        'image/jpeg',
        0.9
      );
    } catch (error) {
      console.error('Crop failed:', error);
      alert('Failed to crop image. Using original.');
      // Fall back to original image
      const reader = new FileReader();
      reader.onload = (e) => {
        onCropApply(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    } finally {
      setIsProcessing(false);
    }
  };

  if (!imageUrl) {
    return <div className={styles.loading}>Loading image...</div>;
  }

  return (
    <div className={styles.cropEditor}>
      <div className={styles.mainContainer}>
        <div className={styles.previewContainer}>
          <Image
            ref={imageRef}
            src={imageUrl}
            alt="Crop image"
            width={800}
            height={600}
            style={{ maxWidth: '100%', height: 'auto' }}
            unoptimized
          />
        </div>
      </div>

      {/* Controls */}
      <div className={styles.controls}>
        <div className={styles.zoomControl}>
          <label>Zoom: </label>
          <input
            type="range"
            min="0.1"
            max="3"
            step="0.1"
            defaultValue="1"
            onChange={(e) => {
              if (cropper) {
                const ratio = parseFloat(e.target.value);
                cropper.setCanvasData({ left: 0, top: 0 });
                cropper.zoomTo(ratio);
              }
            }}
          />
        </div>
      </div>

      {/* Buttons */}
      <div className={styles.actions}>
        <button className={styles.cancelButton} onClick={onCancel} disabled={isProcessing}>
          Cancel
        </button>
        <button className={styles.applyButton} onClick={handleApplyCrop} disabled={isProcessing}>
          {isProcessing ? 'Processing...' : 'Apply Crop'}
        </button>
      </div>
    </div>
  );
}
