import Image from 'next/image';
import Link from 'next/link';
import type { CSSProperties } from 'react';
import type { CmsSlot } from '@/components/cms/types';

export default function CmsElementImage({ slot }: { slot: CmsSlot }) {
  const rawMedia = slot.data?.media;
  const media = rawMedia?.media ?? rawMedia;
  const linkUrl: string | null = slot.data?.url ?? slot.config?.url?.value ?? null;
  const newTab: boolean = slot.data?.newTab ?? slot.config?.newTab?.value ?? false;
  const displayMode: string = slot.config?.displayMode?.value ?? 'standard';
  const minHeight: string = slot.config?.minHeight?.value ?? '0px';
  const hasMinHeight = minHeight && minHeight !== '0px';

  if (!media?.url) {
    const isMapped = slot.config?.media?.source === 'mapped' || slot.config?.url?.source === 'mapped';
    if (process.env.NODE_ENV === 'development' && !isMapped) {
      return (
        <div className="border border-dashed border-orange-400 bg-orange-50 p-3 rounded text-xs text-orange-700 space-y-1">
          <p><strong>Image slot — no media URL found</strong> (slot name: <code>{slot.slot}</code>)</p>
          <p className="font-semibold">slot.data:</p>
          <pre className="overflow-auto max-h-40 bg-white p-2 rounded">{JSON.stringify(slot.data, null, 2)}</pre>
          <p className="font-semibold">slot.config:</p>
          <pre className="overflow-auto max-h-40 bg-white p-2 rounded">{JSON.stringify(slot.config, null, 2)}</pre>
        </div>
      );
    }
    return null;
  }

  const isCover = displayMode === 'cover';
  const containerStyle: CSSProperties = isCover
    ? { height: hasMinHeight ? minHeight : '300px' }
    : hasMinHeight ? { minHeight } : {};

  const img = (
    <div className="relative w-full overflow-hidden" style={containerStyle}>
      {isCover ? (
        <Image
          src={media.url}
          alt={media.alt ?? media.title ?? ''}
          fill
          className="object-cover"
        />
      ) : (
        <Image
          src={media.url}
          alt={media.alt ?? media.title ?? ''}
          width={media.width ?? 1200}
          height={media.height ?? 600}
          className={`w-full h-auto ${displayMode === 'contain' ? 'object-contain' : 'object-cover'}`}
        />
      )}
    </div>
  );

  if (linkUrl) {
    return (
      <Link href={linkUrl} target={newTab ? '_blank' : undefined} rel={newTab ? 'noopener noreferrer' : undefined}>
        {img}
      </Link>
    );
  }
  return img;
}
