'use client';

import React, { useRef, useState } from 'react';
import { useSliderEditor } from './SliderEditorContext';
import ImageCropModal from './ImageCropModal';
import { useImageUpload } from '@/hooks/useImageUpload';
import styles from './ImageUploadTab.module.css';

export default function ImageUploadTab() {
  const { formState, updateSlide } = useSliderEditor();
  const { uploadImage, isUploading: _isUploading } = useImageUpload();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [showCropModal, setShowCropModal] = useState(false);

  const handleFileSelect = (file: File) => {
    if (file.type.startsWith('image/')) {
      setSelectedFile(file);
      setShowCropModal(true);
    } else {
      alert('Please select a valid image file (JPG, PNG)');
    }
  };

  const handleCropComplete = async (dataUrl: string) => {
    try {
      // Convert data URL to Blob
      const response = await fetch(dataUrl);
      const blob = await response.blob();

      // Upload to server
      const url = await uploadImage(blob, 'slider');

      // Update slide with permanent URL
      updateSlide(formState.currentSlideIndex, {
        image: {
          url,
          source: 'upload',
        },
      });

      setShowCropModal(false);
      setSelectedFile(null);
    } catch (error) {
      console.error('Failed to upload image:', error);
      alert('Failed to upload image. Please try again.');
    }
  };

  const handleCropCancel = () => {
    setShowCropModal(false);
    setSelectedFile(null);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.currentTarget.classList.add(styles.dragOver);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.currentTarget.classList.remove(styles.dragOver);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.currentTarget.classList.remove(styles.dragOver);
    const file = e.dataTransfer.files[0];
    if (file) handleFileSelect(file);
  };

  return (
    <>
      <div className={styles.uploadContainer}>
        <div
          className={styles.dropZone}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          onClick={() => fileInputRef.current?.click()}
        >
          <div className={styles.uploadIcon}>Upload</div>
          <p className={styles.uploadText}>Drag image here or click to upload</p>
          <p className={styles.uploadHint}>Supported: JPG, PNG (max 5MB)</p>
        </div>

        <input
          ref={fileInputRef}
          type="file"
          accept="image/jpeg,image/png"
          onChange={(e) => {
            const file = e.target.files?.[0];
            if (file) handleFileSelect(file);
          }}
          style={{ display: 'none' }}
        />
      </div>

      {selectedFile && showCropModal && (
        <ImageCropModal
          file={selectedFile}
          onCropComplete={handleCropComplete}
          onCancel={handleCropCancel}
        />
      )}
    </>
  );
}
