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

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

interface Props {
  gump: GumpEntry;
}

export default function GumpPreview({ gump }: Props) {
  const { uoRoot } = useAppStore();
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [loading, setLoading] = useState(false);
  const [artState, setArtState] = useState<null | 'none' | string>(null);
  const [dims, setDims] = useState<{ w: number; h: number } | null>(null);

  useEffect(() => {
    setArtState(null);
    setDims(null);
    if (!uoRoot) return;

    async function loadArt() {
      setLoading(true);
      try {
        const result = await invoke<ArtImageResult>('get_gump_art', {
          gumpId: gump.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);
        setDims({ w: result.width, h: result.height });
      } catch {
        setArtState('none');
      } finally {
        setLoading(false);
      }
    }

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

  const hexId = `0x${gump.id.toString(16).toUpperCase().padStart(4, '0')}`;

  return (
    <div className={styles.preview}>
      <div className={styles.header}>
        <span className={`${styles.name} font-cinzel`}>{gump.name}</span>
        <span className={styles.id}>{hexId}</span>
      </div>

      {gump.tags.length > 0 && (
        <div className={styles.tags}>
          {gump.tags.map((t) => (
            <span key={t} className={styles.tag}>{t}</span>
          ))}
        </div>
      )}

      <div className={styles.canvasWrap}>
        {loading && <div className={styles.loading}>Loading…</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 gump art</span>
          </div>
        )}
        <canvas
          ref={canvasRef}
          className={styles.artCanvas}
          style={{ display: loading || artState ? 'none' : 'block' }}
        />
      </div>

      {dims && (
        <div className={styles.meta}>
          {dims.w} × {dims.h}
        </div>
      )}
    </div>
  );
}
