'use client';

import { ChevronDown, ChevronUp, Download } from 'lucide-react';
import React from 'react';

import { Button, CopyButton } from '@djangocfg/ui-core/components';

interface JsonToolbarProps {
  /** Viewport right coordinate (distance from right edge) for fixed positioning */
  right: number;
  /** Bottom edge of the container in viewport coords */
  bottom: number;
  /** Top edge — used only to detect if block is fully off-screen */
  top: number;
  isExpanded: boolean;
  onToggleExpand: () => void;
  jsonString: string;
  onDownload: () => void;
  showExpandControls: boolean;
  showActionButtons: boolean;
}

const BUTTON_CLASS = 'h-6 w-6 rounded-sm bg-muted/80 hover:bg-muted border border-border/50 backdrop-blur-sm';
const TOOLBAR_H = 24 + 8 + 8;
const OFFSET = 8;

export const JsonToolbar: React.FC<JsonToolbarProps> = ({
  top,
  right,
  bottom,
  isExpanded,
  onToggleExpand,
  jsonString,
  onDownload,
  showExpandControls,
  showActionButtons,
}) => {
  const viewportHeight = window.visualViewport?.height ?? document.documentElement.clientHeight;

  // Hide when block is fully above or below viewport
  if (bottom <= 0 || top >= viewportHeight) return null;
  // Hide when block is too small to fit toolbar
  if (bottom - top < TOOLBAR_H) return null;

  // Anchor to bottom-right of block, clamped so toolbar stays in viewport
  const toolbarBottom = Math.min(bottom - OFFSET, viewportHeight - OFFSET);

  return (
    <div
      className="flex items-center gap-1"
      style={{ position: 'fixed', bottom: viewportHeight - toolbarBottom, right: right + OFFSET, zIndex: 30 }}
    >
      {showExpandControls && (
        <Button
          variant="ghost"
          size="icon"
          onClick={onToggleExpand}
          className={BUTTON_CLASS}
          title={isExpanded ? 'Collapse All' : 'Expand All'}
        >
          {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
        </Button>
      )}

      {showActionButtons && (
        <>
          <CopyButton
            value={jsonString}
            variant="ghost"
            size="icon"
            className={BUTTON_CLASS}
            iconClassName="h-3 w-3"
            title="Copy JSON"
          />
          <Button
            variant="ghost"
            size="icon"
            onClick={onDownload}
            className={BUTTON_CLASS}
            title="Download JSON"
          >
            <Download className="h-3 w-3" />
          </Button>
        </>
      )}
    </div>
  );
};
