import { useEffect, useRef, useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useAppStore } from '../../store/appStore';
import type { TileInfo } from '../../types/assets';
import styles from './ItemPreview.module.css';

interface ArtImageResult {
  width: number;
  height: number;
  pixels: number[];
}

interface Props {
  tile: TileInfo;
}

export default function ItemPreview({ tile }: Props) {
  const { uoRoot } = useAppStore();
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [loading, setLoading] = useState(false);
  // null = ok, 'none' = no art (show placeholder), string = real error
  const [artState, setArtState] = useState<null | 'none' | string>(null);

  useEffect(() => {
    if (!uoRoot) return;

    async function loadArt() {
      setLoading(true);
      setArtState(null);
      try {
        const result = await invoke<ArtImageResult>('get_tile_art', {
          itemId: tile.id,
          uoRoot,
        });

        const canvas = canvasRef.current;
        if (!canvas) return;

        canvas.width = result.width;
        canvas.height = result.height;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        const imageData = ctx.createImageData(result.width, result.height);
        imageData.data.set(result.pixels);
        ctx.putImageData(imageData, 0, 0);
      } catch {
        // Any failure (no art data, unsupported format, buffer error, etc.)
        // → show placeholder silently. The art source may just not have this item.
        setArtState('none');
      } finally {
        setLoading(false);
      }
    }

    loadArt();
  }, [tile.id, uoRoot]);

  return (
    <div className={styles.preview}>
      <div className={styles.header}>
        <span className={`${styles.name} font-cinzel`}>{tile.name || '(unnamed)'}</span>
        <span className={styles.id}>#{tile.id}</span>
      </div>

      <div className={styles.canvas}>
        {loading && <div className={styles.loading}>Loading art…</div>}
        {artState === 'none' && (
          <div className={styles.noArt}>
            <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
              <rect x="4" y="4" width="40" height="40" rx="4"
                stroke="var(--border-accent)" strokeWidth="1.5" strokeDasharray="4 3" />
              <path d="M16 32 L24 16 L32 32 Z"
                stroke="var(--text-muted)" strokeWidth="1.5" fill="none" />
            </svg>
            <span>No art data</span>
          </div>
        )}
        {artState && artState !== 'none' && (
          <div className={styles.error}>{artState}</div>
        )}
        <canvas
          ref={canvasRef}
          className={styles.artCanvas}
          style={{ display: loading || artState ? 'none' : 'block' }}
        />
      </div>
    </div>
  );
}
