import type { ComponentType } from 'react';
import { useCallback } from 'react';
import { ArrowLeftRight, ChevronLeft, X, Maximize2, Minimize2, ZoomIn, ZoomOut } from 'lucide-react';
import type { LayoutPanel, AppRegistryMap, PanelComponents, PanelComponentEntry } from './types';
import { useWorkspace } from './WorkspaceContext';
import { ZOOM_MIN, ZOOM_MAX, ZOOM_STEP } from './layout-utils';
import { Card } from '@/components/Card';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { AppPicker } from './AppPicker';
import { PanelErrorFallback } from './PanelErrorFallback';
import {
  ContextMenu,
  ContextMenuTrigger,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
} from '@/components/ui/context-menu';

type PanelSlotProps = {
  panel: LayoutPanel;
  registry: AppRegistryMap;
  components?: PanelComponents;
  interactive: boolean;
  locked: boolean;
  noHeader: boolean;
  isLastPanel: boolean;
  onSetApp: (panelId: string, appType: string | null) => void;
  onSplit: (panelId: string, direction: 'horizontal' | 'vertical') => void;
  onRemove: (panelId: string) => void;
};

type PanelContextMenuProps = {
  panelId: string;
  hasApp: boolean;
  isLastPanel: boolean;
  // Current content scale, or null when the app opted out of zoom (no zoom entries in the menu).
  zoom: number | null;
  onSplit: (panelId: string, direction: 'horizontal' | 'vertical') => void;
  onRemove: (panelId: string) => void;
  onClearApp: () => void;
  children: React.ReactNode;
};

const isPanelEntry = (v: PanelComponents[string]): v is PanelComponentEntry =>
  typeof v === 'object' && v !== null && 'component' in v;

const PanelContextMenu = ({
  panelId,
  hasApp,
  isLastPanel,
  zoom,
  onSplit,
  onRemove,
  onClearApp,
  children,
}: PanelContextMenuProps) => {
  const { swapSourceId, setSwapSourceId } = useWorkspace();

  return (
    <ContextMenu>
      <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
      <ContextMenuContent>
        <FullscreenMenuItem panelId={panelId} />
        <ContextMenuSeparator />
        <ContextMenuItem onClick={() => onSplit(panelId, 'horizontal')}>Split horizontal</ContextMenuItem>
        <ContextMenuItem onClick={() => onSplit(panelId, 'vertical')}>Split vertical</ContextMenuItem>
        {hasApp && <ContextMenuItem onClick={onClearApp}>Clear app</ContextMenuItem>}
        {!isLastPanel && (
          <ContextMenuItem className="text-red-500 focus:text-red-500" onClick={() => onRemove(panelId)}>
            Remove panel
          </ContextMenuItem>
        )}
        <ContextMenuSeparator />
        {swapSourceId ? (
          <ContextMenuItem onClick={() => setSwapSourceId(null)}>Cancel swap</ContextMenuItem>
        ) : (
          <ContextMenuItem onClick={() => setSwapSourceId(panelId)}>Swap with...</ContextMenuItem>
        )}
        {zoom !== null && <ZoomMenuItems panelId={panelId} zoom={zoom} />}
      </ContextMenuContent>
    </ContextMenu>
  );
};

const SwapOverlay = ({ panelId }: { panelId: string }) => {
  const { swapSourceId, onSwap } = useWorkspace();

  if (!swapSourceId || swapSourceId === panelId) return null;

  return (
    <div
      className="absolute inset-0 z-20 flex items-center justify-center bg-duck-teal/10 hover:bg-duck-teal/20 transition-colors cursor-pointer"
      onClick={() => onSwap(swapSourceId, panelId)}
    >
      <div className="flex items-center gap-2 rounded-lg bg-background/90 backdrop-blur-sm px-3 py-2 shadow-lg border border-duck-teal/30">
        <ArrowLeftRight className="h-4 w-4 text-duck-teal" />
        <span className="text-sm font-medium text-duck-teal">Swap here</span>
      </div>
    </div>
  );
};

const SwapSourceIndicator = ({ panelId }: { panelId: string }) => {
  const { swapSourceId, setSwapSourceId } = useWorkspace();

  if (swapSourceId !== panelId) return null;

  return (
    <div className="absolute inset-0 z-20 pointer-events-none ring-2 ring-inset ring-duck-teal/50 rounded-lg">
      <div className="absolute top-2 left-2 pointer-events-auto">
        <button
          type="button"
          onClick={() => setSwapSourceId(null)}
          className="flex items-center gap-1.5 rounded-md bg-duck-teal/90 px-2.5 py-1 text-xs font-medium text-white shadow cursor-pointer hover:bg-duck-teal"
        >
          <ArrowLeftRight className="h-3 w-3" />
          Swapping... click to cancel
        </button>
      </div>
    </div>
  );
};

const TrafficLights = ({
  panelId,
  isLastPanel,
  onRemove,
  onClearApp,
}: {
  panelId: string;
  isLastPanel: boolean;
  onRemove: (panelId: string) => void;
  onClearApp: () => void;
}) => {
  // The button says "Close panel" unless this is the only panel left, and it used to call `onClearApp`
  // either way — `isLastPanel` reached here only to choose the tooltip. So closing a panel from its own
  // chrome was impossible: the panel stayed, emptied, and the only working path was the context menu.
  // Worse than cosmetic now that identity lives in the layout — clearing the app drops the `config` that
  // named the panel's agent while the panel itself survives to be renamed by the next thing put in it.
  const handleClose = useCallback(() => {
    if (isLastPanel) onClearApp();
    else onRemove(panelId);
  }, [isLastPanel, onClearApp, onRemove, panelId]);

  // One light, and it is not a traffic light any more. The green "maximize" and amber "restore" that used
  // to sit here drove a second, shallower depth that stopped below the nav header — the most a panel can
  // reach on its own, from inside the content region's stacking context. Once `FullscreenToggle` could
  // take the whole window, that half-measure was a state nobody chose on purpose, so both are gone and
  // full screen is the only depth.
  //
  // Red survives because it does something neither of them did, and it is already absent exactly where it
  // should be: locked screens render no traffic lights at all.
  return (
    <div className="flex items-center gap-1.5 shrink-0 ml-auto">
      <button
        type="button"
        onClick={handleClose}
        className="group/btn h-3 w-3 rounded-full bg-[#ff5f57] hover:brightness-90 transition-all cursor-pointer flex items-center justify-center"
        title={isLastPanel ? 'Clear app' : 'Close panel'}
      >
        <X
          className="h-2 w-2 text-[#4a0002] opacity-0 group-hover/btn:opacity-100 transition-opacity"
          strokeWidth={3}
        />
      </button>
    </div>
  );
};

// The only way to blow a panel up, and the only way back. It takes the whole browser window, nav header
// included — the shell hides its own chrome for it (`panel-fullscreen.ts`).
//
// Hidden until the header is hovered, like the zoom buttons — except while it is active, where it stays
// visible: the panel's own header is then the only chrome on screen, so a control that had to be
// discovered by hovering would be the way out of a state with no other exit.
const FullscreenToggle = ({ panelId }: { panelId: string }) => {
  const { fullscreenPanelId, setFullscreenPanelId } = useWorkspace();
  const isFullscreen = fullscreenPanelId === panelId;
  const Icon = isFullscreen ? Minimize2 : Maximize2;

  return (
    <button
      type="button"
      onClick={() => setFullscreenPanelId(isFullscreen ? null : panelId)}
      title={isFullscreen ? 'Exit full screen' : 'Full screen'}
      className={`cursor-pointer rounded p-1 transition-all hover:bg-black/10 focus-visible:opacity-100 ${isFullscreen ? '' : 'opacity-0 group-hover/header:opacity-100'}`}
    >
      <Icon className="h-3.5 w-3.5" />
    </button>
  );
};

// The two menus below are the locked and unlocked halves of the same panel, and full screen is the one
// thing both of them keep — so it is written once.
const FullscreenMenuItem = ({ panelId }: { panelId: string }) => {
  const { fullscreenPanelId, setFullscreenPanelId } = useWorkspace();
  const isFullscreen = fullscreenPanelId === panelId;

  return (
    <ContextMenuItem onClick={() => setFullscreenPanelId(isFullscreen ? null : panelId)}>
      {isFullscreen ? 'Exit full screen' : 'Full screen'}
    </ContextMenuItem>
  );
};

// Per-panel content scale. The percentage only appears once the panel is off 100%, so an untouched
// header looks exactly as it did before; the +/- buttons reveal on header hover. Clicking the
// percentage resets to 100%.
const ZoomControls = ({ panelId, zoom }: { panelId: string; zoom: number }) => {
  const { onSetZoom } = useWorkspace();
  const atDefault = zoom === 1;

  return (
    <div className="flex shrink-0 items-center gap-0.5">
      <button
        type="button"
        onClick={() => onSetZoom(panelId, zoom - ZOOM_STEP)}
        disabled={zoom <= ZOOM_MIN}
        title="Zoom out"
        className="cursor-pointer rounded p-1 opacity-0 transition-all group-hover/header:opacity-100 hover:bg-black/10 focus-visible:opacity-100 disabled:cursor-default disabled:opacity-0 disabled:group-hover/header:opacity-30"
      >
        <ZoomOut className="h-3.5 w-3.5" />
      </button>
      <button
        type="button"
        onClick={() => onSetZoom(panelId, 1)}
        title="Reset zoom"
        className={`w-9 cursor-pointer rounded px-1 text-center text-[11px] tabular-nums text-black/60 transition-all hover:bg-black/10 hover:text-black ${atDefault ? 'opacity-0 group-hover/header:opacity-100' : ''}`}
      >
        {Math.round(zoom * 100)}%
      </button>
      <button
        type="button"
        onClick={() => onSetZoom(panelId, zoom + ZOOM_STEP)}
        disabled={zoom >= ZOOM_MAX}
        title="Zoom in"
        className="cursor-pointer rounded p-1 opacity-0 transition-all group-hover/header:opacity-100 hover:bg-black/10 focus-visible:opacity-100 disabled:cursor-default disabled:opacity-0 disabled:group-hover/header:opacity-30"
      >
        <ZoomIn className="h-3.5 w-3.5" />
      </button>
    </div>
  );
};

const ZoomMenuItems = ({ panelId, zoom }: { panelId: string; zoom: number }) => {
  const { onSetZoom } = useWorkspace();

  return (
    <>
      <ContextMenuSeparator />
      <ContextMenuItem disabled={zoom >= ZOOM_MAX} onClick={() => onSetZoom(panelId, zoom + ZOOM_STEP)}>
        Zoom in
      </ContextMenuItem>
      <ContextMenuItem disabled={zoom <= ZOOM_MIN} onClick={() => onSetZoom(panelId, zoom - ZOOM_STEP)}>
        Zoom out
      </ContextMenuItem>
      <ContextMenuItem disabled={zoom === 1} onClick={() => onSetZoom(panelId, 1)}>
        Reset zoom
      </ContextMenuItem>
    </>
  );
};

const LockedContextMenu = ({
  panelId,
  zoom,
  children,
}: {
  panelId: string;
  zoom: number | null;
  children: React.ReactNode;
}) => {
  return (
    <ContextMenu>
      <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
      <ContextMenuContent>
        <FullscreenMenuItem panelId={panelId} />
        {zoom !== null && <ZoomMenuItems panelId={panelId} zoom={zoom} />}
      </ContextMenuContent>
    </ContextMenu>
  );
};

// TODO: drag-to-reposition needs work (visual feedback, edge cases)
// const DragHandle = ({ panelId }: { panelId: string }) => {
//   const { setDragSourceId, dragSourceId } = useWorkspace();
//   const onPointerDown = useCallback((ev: React.PointerEvent) => { ev.preventDefault(); setDragSourceId(panelId); }, [panelId, setDragSourceId]);
//   if (dragSourceId) return null;
//   return (
//     <div className="absolute top-2 right-2 z-10 p-1.5 rounded-md bg-duck-dark/5 text-duck-dark/30 opacity-0 group-hover/panel:opacity-100 hover:!bg-duck-dark/10 hover:!text-duck-dark/60 transition-all cursor-grab" onPointerDown={onPointerDown}>
//       <GripVertical className="h-5 w-5" />
//     </div>
//   );
// };
//
// const DragSourceDimmer = ({ panelId }: { panelId: string }) => {
//   const { dragSourceId } = useWorkspace();
//   if (dragSourceId !== panelId) return null;
//   return <div className="absolute inset-0 z-20 rounded-lg bg-duck-dark/10 pointer-events-none" />;
// };

export const PanelSlot = ({
  panel,
  registry,
  components,
  interactive,
  locked,
  noHeader,
  isLastPanel,
  onSetApp,
  onSplit,
  onRemove,
}: PanelSlotProps) => {
  const { fullscreenPanelId, transitioningPanelId, isMobile, onMobileBack } = useWorkspace();
  const isFullscreen = fullscreenPanelId === panel.id;

  const rawPanelComponent = components?.[panel.id];
  const panelEntry = rawPanelComponent && isPanelEntry(rawPanelComponent) ? rawPanelComponent : null;
  const PanelComponent = panelEntry
    ? panelEntry.component
    : (rawPanelComponent as ComponentType<{ panelId: string }> | undefined);

  const entry = panel.appType ? registry[panel.appType] : null;
  const AppComponent = PanelComponent ?? entry?.component;

  // Resolve header, provider, onClose from PanelComponentEntry or registry
  const HeaderComponent = panelEntry?.header ?? entry?.header;
  const ProviderComponent = panelEntry?.provider ?? entry?.provider;
  const onClose = panelEntry?.onClose;

  // null = this app opted out of zoom, so no control and no menu entries.
  const zoom = entry?.zoomable === false ? null : (panel.zoom ?? 1);

  const contextMenu = interactive
    ? locked
      ? (content: React.ReactNode) => (
          <LockedContextMenu panelId={panel.id} zoom={zoom}>
            {content}
          </LockedContextMenu>
        )
      : (content: React.ReactNode) => (
          <PanelContextMenu
            panelId={panel.id}
            hasApp={!!AppComponent}
            isLastPanel={isLastPanel}
            zoom={zoom}
            onSplit={onSplit}
            onRemove={onRemove}
            onClearApp={() => onSetApp(panel.id, null)}
          >
            {content}
          </PanelContextMenu>
        )
    : (content: React.ReactNode) => <>{content}</>;

  // One app throwing must not take the workspace with it — the other panels are still live, and on a
  // dashboard left running overnight they are the result. Keyed on the panel's identity, so swapping the
  // app or clearing it is itself a recovery. A locked layout offers no "clear": it isn't the user's to edit.
  const guardApp = (node: React.ReactNode) => (
    <ErrorBoundary
      resetKeys={[panel.id, panel.appType]}
      fallback={({ error, reset }) => (
        <PanelErrorFallback
          error={error}
          reset={reset}
          onClearApp={interactive && !locked ? () => onSetApp(panel.id, null) : null}
        />
      )}
    >
      {node}
    </ErrorBoundary>
  );

  const overlays =
    interactive && !locked ? (
      <>
        <SwapOverlay panelId={panel.id} />
        <SwapSourceIndicator panelId={panel.id} />
      </>
    ) : null;

  if (!AppComponent) {
    if (!interactive || locked) {
      return (
        <div className="h-full w-full p-1">
          <div className="h-full w-full rounded-lg border-3 border-duck-teal/50" />
        </div>
      );
    }

    return contextMenu(
      <div data-panel-id={panel.id} className="group/panel relative h-full w-full p-1">
        <Card className="relative h-full w-full flex flex-col items-center justify-center gap-3 p-4">
          <AppPicker registry={registry} onSelect={(type) => onSetApp(panel.id, type)} />
        </Card>
        {overlays}
      </div>,
    );
  }

  if (entry?.transparent) {
    return contextMenu(
      <div data-panel-id={panel.id} className="group/panel relative h-full w-full p-1">
        <div className="@container relative h-full w-full overflow-hidden">
          {guardApp(<AppComponent panelId={panel.id} />)}
        </div>
        {overlays}
      </div>,
    );
  }

  // All apps get a chrome header — a custom HeaderComponent, or the registry's icon and name. The default
  // used to be a component declared here, which makes it a new component *type* on every render: React
  // cannot match it to the previous one, so the header subtree unmounted and remounted continuously. It is
  // harmless while the default is stateless, and stops being harmless the moment it isn't. Elements, not
  // types, are the thing to build inside a render.
  const header = HeaderComponent ? (
    <HeaderComponent panelId={panel.id} />
  ) : entry ? (
    <>
      <entry.icon className="h-3.5 w-3.5 shrink-0" />
      <span className="text-xs font-medium truncate flex-1">{entry.name}</span>
    </>
  ) : null;

  // Locked screens get none: the red light edits the layout, and that is the one thing a locked screen
  // withholds. Their only chrome is the fullscreen toggle below, which changes nothing persistent.
  const trafficLights =
    interactive && !isMobile && !locked ? (
      <TrafficLights
        panelId={panel.id}
        isLastPanel={isLastPanel}
        onRemove={onRemove}
        onClearApp={() => onSetApp(panel.id, null)}
      />
    ) : null;

  const mobileBackButton =
    isMobile && onMobileBack ? (
      <button
        type="button"
        onClick={onMobileBack}
        className="flex items-center gap-0.5 text-xs font-medium text-black/70 hover:text-black transition-colors cursor-pointer shrink-0"
      >
        <ChevronLeft className="h-4 w-4" />
        Back
      </button>
    ) : null;

  const zoomControls =
    interactive && !isMobile && zoom !== null ? <ZoomControls panelId={panel.id} zoom={zoom} /> : null;

  // Unlike zoom, no app opts out: taking the window is a property of the frame, not of what is inside it.
  const fullscreenToggle = interactive && !isMobile ? <FullscreenToggle panelId={panel.id} /> : null;

  const headerContent = (
    <div className="group/header shrink-0 flex items-center gap-2 px-3 py-1.5 border-b border-black/10 text-black font-semibold">
      {mobileBackButton}
      {header}
      {!mobileBackButton && onClose && (
        <button onClick={onClose} className="p-1 rounded hover:bg-black/10 transition-colors cursor-pointer">
          <X className="h-3.5 w-3.5" />
        </button>
      )}
      {(zoomControls || fullscreenToggle || trafficLights) && (
        // One shrink-to-fit container so TrafficLights' own ml-auto has no free space left to claim —
        // two competing auto margins would split the header's slack and strand the zoom control mid-row.
        <div className="ml-auto flex shrink-0 items-center gap-2">
          {zoomControls}
          {fullscreenToggle}
          {trafficLights}
        </div>
      )}
    </div>
  );

  const headerBar = interactive ? (
    locked ? (
      <LockedContextMenu panelId={panel.id} zoom={zoom}>
        {headerContent}
      </LockedContextMenu>
    ) : (
      <PanelContextMenu
        panelId={panel.id}
        hasApp={!!AppComponent}
        isLastPanel={isLastPanel}
        zoom={zoom}
        onSplit={onSplit}
        onRemove={onRemove}
        onClearApp={() => onSetApp(panel.id, null)}
      >
        {headerContent}
      </PanelContextMenu>
    )
  ) : (
    headerContent
  );

  // CSS `zoom`, not `transform: scale`. A transform paints the content at a different size without
  // re-laying it out, so the panel keeps the geometry it had at 100% and anything sized against the
  // viewport or a percentage lands in the wrong place — visible immediately in Chat, whose composer is
  // pinned to the bottom of a box the transform no longer agrees with. `zoom` scales the used lengths
  // instead: children reflow, `h-full` and percentages still resolve to the panel, and rem-based
  // Tailwind text sizes scale too (a container font-size would not — rem is root-relative). Percentages
  // resolve across the zoom boundary, so the wrapper still fills the panel exactly at any factor.
  //
  // @container sits on the zoomed element on purpose: at 1.4 a 700px panel measures 500 layout px, so
  // container queries collapse the same way they would in a genuinely narrower panel. That is the point
  // of the control — bigger content, same layout rules.
  const body = (
    <div className="flex-1 min-h-0">
      <Card className="h-full w-full overflow-hidden p-0 rounded-none border-0 shadow-none">
        <div className="@container h-full w-full" style={zoom !== null && zoom !== 1 ? { zoom } : undefined}>
          {guardApp(<AppComponent panelId={panel.id} />)}
        </div>
      </Card>
    </div>
  );

  const inner = ProviderComponent ? (
    <ProviderComponent panelId={panel.id}>
      {!noHeader && headerBar}
      {body}
    </ProviderComponent>
  ) : (
    <>
      {!noHeader && headerBar}
      {body}
    </>
  );

  // Full screen is a CSS state toggle on THE SAME element — no portal, no remount — so the panel's
  // content (scroll position, media playback, in-flight state) is preserved exactly across it.
  //
  // `inset-0` is genuinely the whole window only because the shell stands its own header down while a
  // panel is fullscreen (`panel-fullscreen.ts`). Nothing here can achieve that alone: the panel is
  // confined to the layout's `absolute z-2` content stacking context, which sits under the fixed nav
  // Header (z-10), so no z-index it gives itself will paint over the nav. This used to have a second,
  // shallower mode that simply accepted that and started at `top-[56px]`; it was removed once this one
  // worked, along with the green/amber traffic lights that drove it.
  //
  // No gutter, no rounding, no shadow — those read as "a window floating above the app", and here there
  // is no app left to float above.
  //
  // Denser glass than a tiled panel, not a darker one. Panel chrome — header text, icons, the zoom
  // control — is black throughout, so the old near-opaque dark fill left every one of them unreadable.
  // This is the nav Header's exact recipe (`rgba(255,255,255,0.25)` over a 0.35 border), which is the
  // app's established "raised above the rest" surface and is already proven to carry black text.
  const fullscreenStyle = { backgroundColor: 'rgba(255, 255, 255, 0.25)', borderColor: 'rgba(255, 255, 255, 0.35)' };
  const normalStyle = noHeader
    ? { backgroundColor: 'rgba(255, 255, 255, 0.12)', borderColor: 'rgba(0, 0, 0, 0.25)' }
    : { backgroundColor: 'rgba(255, 255, 255, 0.12)', borderColor: 'rgba(255, 255, 255, 0.2)' };
  const panelStyle = {
    ...(isFullscreen ? fullscreenStyle : normalStyle),
    ...(transitioningPanelId === panel.id ? { viewTransitionName: `panel-${panel.id}` } : {}),
  } as React.CSSProperties;

  return (
    <div data-panel-id={panel.id} className="group/panel relative h-full w-full p-1">
      <div
        className={
          isFullscreen
            ? 'fixed inset-0 z-50 overflow-hidden backdrop-blur-xl p-2 flex flex-col'
            : 'relative h-full w-full overflow-hidden rounded-lg border backdrop-blur-xl p-2 flex flex-col'
        }
        style={panelStyle}
      >
        {inner}
      </div>
      {overlays}
    </div>
  );
};
