import { Eye, EyeSlash, Lock, LockOpen, X } from "@phosphor-icons/react";
import type { ImageDocument } from "@core/document";
import type { Layer } from "@core/layer";
import type { SelectionState } from "@editor/state";

export type LayersSheetProps = {
  document: ImageDocument;
  selection: SelectionState;
  open: boolean;
  onClose: () => void;
};

export function LayersSheet({ document, selection, open, onClose }: LayersSheetProps) {
  return (
    <aside
      aria-hidden={!open}
      className={`pointer-events-auto absolute right-3 top-12 z-20 w-72 rounded-xl border border-white/10 bg-black/75 text-xs text-white shadow-xl backdrop-blur transition-all duration-200 ${
        open ? "translate-x-0 opacity-100" : "pointer-events-none translate-x-4 opacity-0"
      }`}
    >
      <header className="flex h-10 items-center justify-between border-b border-white/10 px-3">
        <span className="font-medium">Layers</span>
        <button type="button" className={iconButtonClass()} aria-label="Close layers" onClick={onClose}>
          <X size={16} weight="regular" />
        </button>
      </header>
      <div className="max-h-96 overflow-auto p-2">
        {document.artboards.map((artboard) => (
          <section key={artboard.id} className="mb-2 last:mb-0">
            <div className={`rounded-md px-2 py-1 text-white/60 ${selection.artboardId === artboard.id ? "bg-white/10 text-white" : ""}`}>
              {artboard.name}
            </div>
            <div className="mt-1 space-y-1 pl-2">
              {artboard.layers.length === 0 ? (
                <div className="px-2 py-1 text-white/40">No layers</div>
              ) : (
                artboard.layers.map((layer) => <LayerRow key={layer.id} layer={layer} depth={0} selectedLayerIds={selection.layerIds} />)
              )}
            </div>
          </section>
        ))}
      </div>
    </aside>
  );
}

function LayerRow({ layer, depth, selectedLayerIds }: { layer: Layer; depth: number; selectedLayerIds: string[] }) {
  const selected = selectedLayerIds.includes(layer.id);
  return (
    <div>
      <div className={`flex items-center gap-2 rounded-md px-2 py-1 ${selected ? "bg-white text-black" : "text-white/80 hover:bg-white/10 hover:text-white"}`} style={{ paddingLeft: 8 + depth * 12 }}>
        {layer.visible ? <Eye size={14} weight="regular" /> : <EyeSlash size={14} weight="regular" />}
        {layer.locked ? <Lock size={14} weight="regular" /> : <LockOpen size={14} weight="regular" />}
        <span className="min-w-0 flex-1 truncate">{layer.name}</span>
      </div>
      {layer.type === "group" ? layer.children.map((child) => <LayerRow key={child.id} layer={child} depth={depth + 1} selectedLayerIds={selectedLayerIds} />) : null}
    </div>
  );
}

function iconButtonClass() {
  return "grid size-7 place-items-center rounded-full text-white/80 transition hover:bg-white/10 hover:text-white focus:outline-none focus-visible:outline-none";
}
