import React, { useEffect, useRef, useState } from 'react';
import '@reticlejs/pro';
import type { AnnotationState, MarkerArea } from '@reticlejs/pro';
import { createReticleReactComponents } from '@reticlejs/pro/wrappers/react';
import { createToolbarState, type ToolbarController, type ToolbarSnapshot } from '@reticlejs/pro/ui';
import type { AiRedactPlugin, RedactionProposal } from '@reticlejs/pro/ai-redact';

const { ReticleEditor } = createReticleReactComponents(React);

const TOOLS = [
  { type: 'FrameMarker', label: 'Frame' },
  { type: 'ArrowMarker', label: 'Arrow' },
  { type: 'CalloutMarker', label: 'Callout' },
  { type: 'BlurMarker', label: 'Blur' },
  { type: 'PixelateMarker', label: 'Pixelate' },
] as const;

export interface AppProps {
  imageSrc?: string;
}

export default function App({ imageSrc = '/sample.png' }: AppProps) {
  const editorRef = useRef<MarkerArea | null>(null);
  const toolbarRef = useRef<ToolbarController | null>(null);
  const aiRedactRef = useRef<AiRedactPlugin | null>(null);

  const [targetImage, setTargetImage] = useState<HTMLImageElement | null>(null);
  const [toolbar, setToolbar] = useState<ToolbarSnapshot | null>(null);
  const [proposals, setProposals] = useState<readonly RedactionProposal[]>([]);
  const [scanning, setScanning] = useState(false);
  const [markerCount, setMarkerCount] = useState(0);

  // Load the target image for <marker-area>.
  useEffect(() => {
    const img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = () => setTargetImage(img);
    img.src = imageSrc;
  }, [imageSrc]);

  // Bind the headless toolbar controller to the underlying Editor kernel.
  useEffect(() => {
    const area = editorRef.current;
    if (!area) return;

    const controller = createToolbarState(
      area.editor,
      TOOLS.map((t) => t.type)
    );
    toolbarRef.current = controller;
    setToolbar(controller.getSnapshot());

    const unsubscribe = controller.subscribe((snapshot) => {
      setToolbar(snapshot);
    });

    return () => {
      unsubscribe();
      controller.destroy();
      toolbarRef.current = null;
    };
  }, [targetImage]);

  // Lazily load `reticlejs/ai-redact` only when the user clicks "AI Auto-Redact".
  async function handleAiRedactScan() {
    const area = editorRef.current;
    if (!area || !targetImage) return;

    setScanning(true);
    try {
      if (!aiRedactRef.current) {
        const { createAiRedactPlugin } = await import('@reticlejs/pro/ai-redact');
        const plugin = createAiRedactPlugin({
          defaultMarkerType: 'BlurMarker',
          defaultStrength: 14,
          onProposalsChange: (next) => setProposals(next),
        });
        area.editor.use(plugin);
        aiRedactRef.current = plugin;
      }

      const detected = await aiRedactRef.current.scan(targetImage);
      setProposals(detected);
    } finally {
      setScanning(false);
    }
  }

  function handleStateChange(detail: { state?: AnnotationState }) {
    if (detail.state) {
      setMarkerCount(detail.state.markers.length);
    }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12, padding: 16, fontFamily: 'sans-serif' }}>
      <header style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
        {TOOLS.map((tool) => {
          const active = toolbar?.activeTool === tool.type;
          return (
            <button
              key={tool.type}
              type="button"
              onClick={() => toolbarRef.current?.selectTool(tool.type)}
              style={{
                padding: '6px 12px',
                borderRadius: 6,
                border: '1px solid #cbd5e1',
                background: active ? '#2563eb' : '#ffffff',
                color: active ? '#ffffff' : '#0f172a',
                cursor: 'pointer',
              }}
            >
              {tool.label}
            </button>
          );
        })}

        <button
          type="button"
          disabled={!toolbar?.canUndo}
          onClick={() => toolbarRef.current?.undo()}
        >
          Undo
        </button>
        <button
          type="button"
          disabled={!toolbar?.canRedo}
          onClick={() => toolbarRef.current?.redo()}
        >
          Redo
        </button>
        <button
          type="button"
          disabled={!toolbar?.hasSelection}
          onClick={() => toolbarRef.current?.deleteSelected()}
        >
          Delete
        </button>
        <button
          type="button"
          disabled={!targetImage || scanning}
          onClick={handleAiRedactScan}
        >
          {scanning ? 'Scanning…' : 'AI Auto-Redact (On-Device)'}
        </button>
        <span style={{ marginLeft: 'auto', fontSize: 13, color: '#475569' }}>
          Markers: {markerCount}
        </span>
      </header>

      {proposals.length > 0 && (
        <aside style={{ display: 'flex', flexWrap: 'wrap', gap: 8, padding: 10, background: '#f8fafc', borderRadius: 8 }}>
          <strong>Detected PII / Faces ({proposals.filter((p) => p.status === 'pending').length} pending):</strong>
          {proposals.map((p) => (
            <span key={p.id} style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
              <span>
                {p.label} ({p.masked}) — {p.status}
              </span>
              {p.status === 'pending' && (
                <button
                  type="button"
                  onClick={() => aiRedactRef.current?.acceptProposal(p.id)}
                >
                  Redact
                </button>
              )}
            </span>
          ))}
        </aside>
      )}

      <div style={{ border: '1px solid #e2e8f0', borderRadius: 8, overflow: 'hidden', minHeight: 480 }}>
        <ReticleEditor
          editorRef={editorRef}
          targetImage={targetImage}
          autoZoomToFit
          snapEnabled
          onStateChange={handleStateChange}
          style={{ display: 'block', width: '100%', height: '540px' }}
        />
      </div>
    </div>
  );
}
