import { useRef } from "react";
import { RotateCw } from "lucide-react";
import { useApp } from "../app-state";
import { Chip } from "./ui/Chip";
import { Icon } from "./ui/Icon";

export function Preview() {
  const { state, lsp } = useApp();
  const iframeRef = useRef<HTMLIFrameElement | null>(null);

  const statusChip = () => {
    if (!state.currentProject) return <Chip tone="neutral">no project</Chip>;
    if (!state.openFile) return <Chip tone="neutral">open a file</Chip>;
    if (lsp.status !== "ready") return <Chip tone="amber" dot dotPulse>LSP {lsp.status}</Chip>;
    if (!lsp.previewReady) return <Chip tone="neutral">starting...</Chip>;
    return <Chip tone="teal" dot>live</Chip>;
  };

  return (
    <div className="h-full flex flex-col bg-surface">
      {/* Toolbar */}
      <div className="flex items-center gap-2 px-3 py-1.5 border-b border-line text-xs text-ink-muted shrink-0">
        <span className="font-medium">Preview</span>
        <span className="ml-auto flex items-center gap-1">
          {statusChip()}
        </span>
        {lsp.previewReady && (
          <button
            type="button"
            onClick={() => {
              iframeRef.current?.contentWindow?.location.reload();
            }}
            className="p-1 rounded-md text-ink-muted hover:bg-surface-hover transition-colors"
            aria-label="Reload preview"
          >
            <Icon icon={RotateCw} className="size-3.5" />
          </button>
        )}
        <span className="text-ink-subtle text-[11px] hidden sm:inline">Click preview to jump to source</span>
      </div>

      {/* Content */}
      <div className="flex-1 bg-surface relative min-h-0">
        {state.currentProject && state.openFile && lsp.status === "ready" && lsp.previewReady ? (
          <iframe
            ref={iframeRef}
            key={state.currentProject}
            src="/preview-app"
            title="Typst preview"
            className="absolute inset-0 w-full h-full bg-white"
          />
        ) : (
          <div className="absolute inset-0 flex flex-col items-center justify-center text-ink-subtle text-sm p-6 gap-2">
            <span>{statusChip()}</span>
            {lsp.status === "error" && lsp.error && (
              <pre className="mt-2 max-w-full overflow-auto text-xs text-rose-600 bg-rose-50 p-3 rounded whitespace-pre-wrap break-all">
                {lsp.error}
              </pre>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
