import React from 'react';
import type { ComponentConfig } from '@measured/puck';
import type { ImageProps } from '../../types';
import { imagePickerField } from '../../fields/ImagePickerField';

const ASPECT_RATIO_CLASSES = {
  '16:9': 'aspect-video',
  '4:3': 'aspect-[4/3]',
  '1:1': 'aspect-square',
  'auto': '',
};

const RADIUS_CLASSES = {
  none: 'rounded-none',
  small: 'rounded-md',
  medium: 'rounded-lg',
  large: 'rounded-xl',
};

export const Image: ComponentConfig<ImageProps> = {
  label: 'Image',
  fields: {
    src: {
      ...imagePickerField,
      label: 'Image',
    },
    alt: {
      type: 'text',
      label: 'Alt Text',
    },
    caption: {
      type: 'text',
      label: 'Caption (optional)',
    },
    aspectRatio: {
      type: 'select',
      options: [
        { label: 'Auto', value: 'auto' },
        { label: '16:9', value: '16:9' },
        { label: '4:3', value: '4:3' },
        { label: '1:1', value: '1:1' },
      ],
    },
    borderRadius: {
      type: 'select',
      options: [
        { label: 'None', value: 'none' },
        { label: 'Small', value: 'small' },
        { label: 'Medium', value: 'medium' },
        { label: 'Large', value: 'large' },
      ],
    },
  },
  defaultProps: {
    src: '',
    alt: '',
    aspectRatio: 'auto',
    borderRadius: 'medium',
  },
  render: ({ src, alt, caption, aspectRatio = 'auto', borderRadius = 'medium' }) => {
    const aspectClass = ASPECT_RATIO_CLASSES[aspectRatio] || '';
    const radiusClass = RADIUS_CLASSES[borderRadius] || RADIUS_CLASSES.medium;

    if (!src) {
      return (
        <div className={`${aspectClass || 'aspect-video'} ${radiusClass} bg-gray-200 dark:bg-gray-700 flex items-center justify-center`}>
          <span className="text-gray-500 dark:text-gray-400">No image selected</span>
        </div>
      );
    }

    return (
      <figure>
        <div className={`${aspectClass} ${radiusClass} overflow-hidden`}>
          <img
            src={src}
            alt={alt}
            className={`w-full h-full ${aspectClass ? 'object-cover' : ''}`}
          />
        </div>
        {caption && (
          <figcaption className="mt-2 text-sm text-gray-600 dark:text-gray-400 text-center">
            {caption}
          </figcaption>
        )}
      </figure>
    );
  },
};

export default Image;
