'use client';

import React, { useEffect, useRef, useState } from 'react';
import { Image01Icon } from '@zen/core/shared/icons';
import { newBlockId } from '../utils/ids.js';

// Bloc image. Phase 2 : URL uniquement (pas d'upload). État vide = formulaire
// d'insertion d'URL. État rempli = image rendue + caption optionnelle.

function ImageBlock({ block, onChange, disabled }) {
  const [url, setUrl] = useState(block.src ?? '');
  const inputRef = useRef(null);

  useEffect(() => {
    if (!block.src && !disabled) {
      // Au montage initial du bloc vide, on focus l'input automatiquement.
      inputRef.current?.focus();
    }
  }, [block.src, disabled]);

  function submit(e) {
    e.preventDefault();
    if (!url.trim()) return;
    onChange?.({ src: url.trim() });
  }

  function handleAltChange(e) {
    onChange?.({ alt: e.target.value });
  }

  function handleCaptionChange(e) {
    onChange?.({ caption: e.target.value });
  }

  function reset() {
    setUrl('');
    onChange?.({ src: '', alt: '', caption: '' });
  }

  if (!block.src) {
    return (
      <form
        onSubmit={submit}
        className="flex items-center gap-2 rounded-lg border border-dashed border-neutral-300 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800/40 px-3 py-3"
      >
        <Image01Icon width={18} height={18} className="text-neutral-500" />
        <input
          ref={inputRef}
          type="url"
          placeholder="URL de l'image (https://…)"
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          disabled={disabled}
          className="flex-1 px-2 py-1 text-sm rounded border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 text-neutral-900 dark:text-white outline-none focus:border-blue-500"
        />
        <button
          type="submit"
          disabled={disabled || !url.trim()}
          className="px-3 py-1 text-sm rounded bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:hover:bg-blue-600 text-white"
        >
          Insérer
        </button>
      </form>
    );
  }

  return (
    <div className="group/image relative">
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        src={block.src}
        alt={block.alt ?? ''}
        className="rounded-lg max-w-full block"
        draggable={false}
      />
      {!disabled && (
        <button
          type="button"
          onClick={reset}
          title="Retirer l'image"
          className="absolute top-2 right-2 opacity-0 group-hover/image:opacity-100 transition-opacity w-7 h-7 flex items-center justify-center rounded-full bg-black/60 hover:bg-black/80 text-white text-sm"
        >
          ✕
        </button>
      )}
      <div className="mt-1 flex flex-col gap-1">
        <input
          type="text"
          placeholder="Légende (optionnelle)"
          value={block.caption ?? ''}
          onChange={handleCaptionChange}
          disabled={disabled}
          className="w-full px-1 py-0.5 text-sm italic text-neutral-600 dark:text-neutral-400 bg-transparent outline-none focus:border-b focus:border-neutral-300 dark:focus:border-neutral-700"
        />
        {!disabled && (
          <input
            type="text"
            placeholder="Texte alternatif (accessibilité)"
            value={block.alt ?? ''}
            onChange={handleAltChange}
            className="w-full px-1 py-0.5 text-xs text-neutral-500 dark:text-neutral-500 bg-transparent outline-none focus:border-b focus:border-neutral-300 dark:focus:border-neutral-700"
          />
        )}
      </div>
    </div>
  );
}

const Image = {
  type: 'image',
  label: 'Image',
  icon: <Image01Icon width={18} height={18} />,
  keywords: ['image', 'photo', 'picture', 'img'],
  isText: false,
  create(init = {}) {
    return { id: newBlockId(), type: 'image', src: '', alt: '', caption: '', ...init };
  },
  Component: ImageBlock,
};

export default Image;
