'use client';

import React, { useState, useRef } from 'react';
import { useSliderEditor } from './SliderEditorContext';
import MediaLibraryModal from './MediaLibraryModal';
import ImageCropModal from './ImageCropModal';
import { useImageUpload } from '@/hooks/useImageUpload';
import type { ImageSelection } from '@/types/media';
import styles from './SliderImagePicker.module.css';

/** Slider aspect ratio: 2.57:1 (matches frontend slider design) */
const SLIDER_ASPECT_RATIO = 2.57;
const SLIDER_ASPECT_RATIO_LABEL = '2.57:1';

/**
 * Unified image picker for the slider editor.
 * Matches the page builder's ImagePickerField style with inline preview
 * and supports both media library selection and direct upload with cropping.
 * All images are cropped to 2.57:1 aspect ratio to fit the slider.
 */
export default function SliderImagePicker() {
  const { sliderContent, formState, updateSlide } = useSliderEditor();
  const { uploadImage } = useImageUpload();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [isLibraryOpen, setIsLibraryOpen] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [showCropModal, setShowCropModal] = useState(false);
  const [isLoadingLibraryImage, setIsLoadingLibraryImage] = useState(false);

  const currentSlide = sliderContent.slides[formState.currentSlideIndex];
  const currentImageUrl = currentSlide?.image?.url;

  const handleLibrarySelect = async (image: ImageSelection) => {
    setIsLibraryOpen(false);
    setIsLoadingLibraryImage(true);

    try {
      // Fetch the image and convert to File for cropping
      const response = await fetch(image.url);
      const blob = await response.blob();
      const file = new File([blob], image.filename || 'library-image.jpg', {
        type: blob.type || 'image/jpeg',
      });

      setSelectedFile(file);
      setShowCropModal(true);
    } catch (error) {
      console.error('Failed to load library image for cropping:', error);
      // Fallback: use image directly without cropping
      updateSlide(formState.currentSlideIndex, {
        image: {
          url: image.url,
          source: 'library',
        },
      });
    } finally {
      setIsLoadingLibraryImage(false);
    }
  };

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

  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 handleClearImage = (e: React.MouseEvent) => {
    e.stopPropagation();
    updateSlide(formState.currentSlideIndex, {
      image: {
        url: '',
        source: 'library',
      },
    });
  };

  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.container}>
        {currentImageUrl ? (
          // Show image preview when an image is selected
          <div className={styles.preview}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={currentImageUrl} alt="Slide image" className={styles.previewImage} />
            <div className={styles.previewOverlay}>
              <div className={styles.previewActions}>
                <button
                  className={styles.actionButton}
                  onClick={() => setIsLibraryOpen(true)}
                  type="button"
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                  >
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
                    <circle cx="8.5" cy="8.5" r="1.5" />
                    <polyline points="21 15 16 10 5 21" />
                  </svg>
                  Media Library
                </button>
                <button
                  className={styles.actionButton}
                  onClick={() => fileInputRef.current?.click()}
                  type="button"
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                  >
                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                    <polyline points="17 8 12 3 7 8" />
                    <line x1="12" y1="3" x2="12" y2="15" />
                  </svg>
                  Upload New
                </button>
              </div>
            </div>
            <button
              className={styles.clearButton}
              onClick={handleClearImage}
              title="Remove image"
              type="button"
            >
              <svg
                width="14"
                height="14"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <line x1="18" y1="6" x2="6" y2="18" />
                <line x1="6" y1="6" x2="18" y2="18" />
              </svg>
            </button>
          </div>
        ) : (
          // Show selection options when no image is selected
          <div
            className={styles.selectContainer}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
          >
            <div className={styles.selectButtons}>
              <button
                className={styles.selectButton}
                onClick={() => setIsLibraryOpen(true)}
                type="button"
              >
                <svg
                  className={styles.selectIcon}
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                >
                  <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
                  <circle cx="8.5" cy="8.5" r="1.5" />
                  <polyline points="21 15 16 10 5 21" />
                </svg>
                <span className={styles.selectText}>Media Library</span>
                <span className={styles.selectHint}>Browse your images</span>
              </button>
              <button
                className={styles.selectButton}
                onClick={() => fileInputRef.current?.click()}
                type="button"
              >
                <svg
                  className={styles.selectIcon}
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                >
                  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                  <polyline points="17 8 12 3 7 8" />
                  <line x1="12" y1="3" x2="12" y2="15" />
                </svg>
                <span className={styles.selectText}>Upload Image</span>
                <span className={styles.selectHint}>JPG, PNG, WebP</span>
              </button>
            </div>
            <p className={styles.dropHint}>or drag and drop an image here</p>
          </div>
        )}
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        onChange={(e) => {
          const file = e.target.files?.[0];
          if (file) handleFileSelect(file);
          // Reset input so same file can be selected again
          e.target.value = '';
        }}
        style={{ display: 'none' }}
      />

      <MediaLibraryModal
        isOpen={isLibraryOpen}
        onClose={() => setIsLibraryOpen(false)}
        onSelect={handleLibrarySelect}
        context="slider"
      />

      {selectedFile && showCropModal && (
        <ImageCropModal
          file={selectedFile}
          onCropComplete={handleCropComplete}
          onCancel={handleCropCancel}
          aspectRatio={SLIDER_ASPECT_RATIO}
          aspectRatioLabel={SLIDER_ASPECT_RATIO_LABEL}
        />
      )}

      {isLoadingLibraryImage && (
        <div className={styles.loadingOverlay}>
          <div className={styles.loadingSpinner}>Loading image...</div>
        </div>
      )}
    </>
  );
}
