"use client";

import * as React from "react";
import { Maximize2, Minimize2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

type DashboardWidgetExpandContextValue = {
  expandedId: string | null;
  toggle: (layoutId: string) => void;
  collapse: () => void;
};

const DashboardWidgetExpandContext = React.createContext<DashboardWidgetExpandContextValue | null>(
  null,
);

export function DashboardWidgetExpandProvider({
  expandedId,
  onExpandedIdChange,
  children,
}: {
  expandedId: string | null;
  onExpandedIdChange: (layoutId: string | null) => void;
  children: React.ReactNode;
}) {
  const value = React.useMemo<DashboardWidgetExpandContextValue>(
    () => ({
      expandedId,
      toggle: (layoutId) => onExpandedIdChange(expandedId === layoutId ? null : layoutId),
      collapse: () => onExpandedIdChange(null),
    }),
    [expandedId, onExpandedIdChange],
  );
  return (
    <DashboardWidgetExpandContext.Provider value={value}>{children}</DashboardWidgetExpandContext.Provider>
  );
}

export function useDashboardWidgetExpand(layoutId?: string) {
  const ctx = React.useContext(DashboardWidgetExpandContext);
  if (!layoutId || !ctx) {
    return {
      supported: false as const,
      expanded: false,
      toggle: () => {},
      collapse: () => {},
    };
  }
  return {
    supported: true as const,
    expanded: ctx.expandedId === layoutId,
    toggle: () => ctx.toggle(layoutId),
    collapse: ctx.collapse,
  };
}

/** Header control for in-dashboard full-width resize (same as Deliveries / Performance). */
export function DashboardWidgetExpandButton({
  layoutId,
  className,
}: {
  layoutId?: string;
  className?: string;
}) {
  const expand = useDashboardWidgetExpand(layoutId);
  const { expanded, collapse } = expand;

  React.useEffect(() => {
    if (!expanded) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") collapse();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [expanded, collapse]);

  if (!expand.supported) return null;

  return (
    <Button
      type="button"
      variant="ghost"
      size="icon"
      className={cn(
        "size-8 rounded-lg text-muted-foreground hover:text-foreground",
        className,
      )}
      onClick={(event) => {
        event.stopPropagation();
        expand.toggle();
      }}
      title={expand.expanded ? "Exit full width" : "Expand to full width"}
      aria-label={expand.expanded ? "Exit full width" : "Expand to full width"}
      aria-pressed={expand.expanded}
    >
      {expand.expanded ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
    </Button>
  );
}
