'use client';

import React, { useState } from 'react';
import MediaLibraryModal from '@/app/components/MediaLibraryModal';
import type { ImageSelection } from '@/types/media';

interface ImagePickerFieldProps {
  value: string;
  onChange: (value: string) => void;
}

/**
 * Custom Puck field component for selecting images from the Media Library.
 * Displays current image preview and opens MediaLibraryModal on click.
 */
export function ImagePickerField({ value, onChange }: ImagePickerFieldProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleSelect = (image: ImageSelection) => {
    onChange(image.url);
    setIsModalOpen(false);
  };

  const handleClear = (e: React.MouseEvent) => {
    e.stopPropagation();
    onChange('');
  };

  return (
    <>
      <div style={styles.container}>
        {value ? (
          <div style={styles.preview} onClick={() => setIsModalOpen(true)}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={value} alt="Selected" style={styles.previewImage} />
            <div style={styles.previewOverlay}>
              <span style={styles.changeText}>Click to change</span>
            </div>
            <button
              style={styles.clearButton}
              onClick={handleClear}
              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>
        ) : (
          <button style={styles.selectButton} onClick={() => setIsModalOpen(true)} type="button">
            <svg
              style={styles.icon}
              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 style={styles.selectText}>Select from Media Library</span>
          </button>
        )}
      </div>

      <MediaLibraryModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onSelect={handleSelect}
        context="page"
      />
    </>
  );
}

const styles: Record<string, React.CSSProperties> = {
  container: {
    width: '100%',
  },
  preview: {
    position: 'relative',
    width: '100%',
    aspectRatio: '16 / 9',
    borderRadius: '6px',
    overflow: 'hidden',
    cursor: 'pointer',
    border: '1px solid #e0e0e0',
  },
  previewImage: {
    width: '100%',
    height: '100%',
    objectFit: 'cover',
  },
  previewOverlay: {
    position: 'absolute',
    inset: 0,
    background: 'rgba(0, 0, 0, 0.4)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    opacity: 0,
    transition: 'opacity 0.2s',
  },
  changeText: {
    color: 'white',
    fontSize: '13px',
    fontWeight: 500,
  },
  clearButton: {
    position: 'absolute',
    top: '8px',
    right: '8px',
    width: '24px',
    height: '24px',
    borderRadius: '4px',
    border: 'none',
    background: 'rgba(220, 38, 38, 0.9)',
    color: 'white',
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    opacity: 0,
    transition: 'opacity 0.2s',
  },
  selectButton: {
    width: '100%',
    padding: '24px 16px',
    border: '2px dashed #d0d0d0',
    borderRadius: '6px',
    background: 'white',
    cursor: 'pointer',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: '8px',
    transition: 'border-color 0.2s, background 0.2s',
  },
  icon: {
    width: '32px',
    height: '32px',
    color: '#666',
  },
  selectText: {
    fontSize: '13px',
    color: '#666',
    fontWeight: 500,
  },
};

// Add hover styles via CSS-in-JS workaround
if (typeof window !== 'undefined') {
  const styleSheet = document.createElement('style');
  styleSheet.textContent = `
    .puck-image-picker-preview:hover .puck-image-picker-overlay,
    .puck-image-picker-preview:hover .puck-image-picker-clear {
      opacity: 1 !important;
    }
    .puck-image-picker-button:hover {
      border-color: var(--color-primary-accent, #38bdf8) !important;
      background: #f8fafc !important;
    }
  `;
  document.head.appendChild(styleSheet);
}

export default ImagePickerField;
