/**
 * CopyDownBanner Component
 *
 * Shows instruction banner when copy-down mode is active.
 * Positions above the source cell for better context.
 * Memoized with minimal subscriptions for performance.
 */

import { memo, useEffect, useState, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { X, ArrowDownToLine } from 'lucide-react';
import { useValidationStore } from '../store/validationStore';
import { useIsCopyDownActive } from '../store/selectors';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';

/**
 * Copy-down instruction banner
 *
 * PERFORMANCE: Only subscribes to copyDownMode.isActive boolean.
 * Uses getState() for the cancel action to avoid additional subscriptions.
 *
 * POSITIONING: Uses the source row index to find the row element and position
 * the banner above it for better visual context.
 */
export const CopyDownBanner = memo(() => {
  const isActive = useIsCopyDownActive();
  // Subscribe only to the primitives we need to compute "rows below source".
  // These are cheap to compare and only change while copy-down is active.
  const rowCount = useValidationStore((state) => state.rows.length);
  const sourceRowIndex = useValidationStore((state) => state.copyDownMode.sourceRowIndex);
  const rowsBelow = sourceRowIndex !== null ? Math.max(0, rowCount - 1 - sourceRowIndex) : 0;
  const [position, setPosition] = useState<{ top: number; left: number } | null>(null);
  const bannerRef = useRef<HTMLDivElement>(null);

  // Update position based on source cell
  useEffect(() => {
    if (!isActive) {
      setPosition(null);
      return;
    }

    const updatePosition = () => {
      const { copyDownMode } = useValidationStore.getState();
      if (copyDownMode.sourceRowIndex === null || !copyDownMode.sourceFieldKey) return;

      // Find the source cell by row index and field key
      const rowElement = document.querySelector(
        `[data-row-index="${copyDownMode.sourceRowIndex}"]`
      ) as HTMLElement | null;

      if (!rowElement) return;

      const cellElement = rowElement.querySelector(
        `[data-cell-field="${copyDownMode.sourceFieldKey}"]`
      ) as HTMLElement | null;

      if (!cellElement) return;

      // Get the table container (parent of scroll container)
      const tableContainer = rowElement.closest('.relative') as HTMLElement | null;
      if (!tableContainer) return;

      const tableRect = tableContainer.getBoundingClientRect();
      const cellRect = cellElement.getBoundingClientRect();

      // Measure actual banner height so it sits the right distance above the cell.
      // Fallback covers the very first paint before the ref is attached.
      const bannerHeight = bannerRef.current?.offsetHeight ?? 32;
      const GAP = 10;

      // Always position above the cell. Clamp to the top of the table container
      // so the banner stays visible — a small overlap with the source cell is
      // acceptable for top-row sources since the compact pill rarely needs it.
      const topPosition = Math.max(cellRect.top - tableRect.top - bannerHeight - GAP, 8);
      const leftPosition = cellRect.left - tableRect.left + cellRect.width / 2;

      setPosition({
        top: topPosition,
        left: leftPosition,
      });
    };

    // Initial position (with small delay to ensure DOM is ready)
    setTimeout(updatePosition, 0);

    // Update on scroll
    const scrollContainer = document.querySelector('.overflow-auto');
    if (scrollContainer) {
      scrollContainer.addEventListener('scroll', updatePosition);
      return () => scrollContainer.removeEventListener('scroll', updatePosition);
    }
  }, [isActive]);

  if (!isActive) return null;

  const handleCancel = () => {
    useValidationStore.getState().cancelCopyDown();
  };

  const handleApplyToAll = () => {
    const state = useValidationStore.getState();
    const lastRowIndex = state.rows.length - 1;
    if (lastRowIndex <= (state.copyDownMode.sourceRowIndex ?? -1)) return;
    state.completeCopyDown(lastRowIndex);
  };

  return (
    <div
      className="absolute z-30 pointer-events-none"
      style={{
        top: position?.top ?? 8,
        left: position?.left ?? '50%',
        transform: 'translateX(-50%)',
      }}
    >
      <div ref={bannerRef} className="pointer-events-auto">
        <div className="bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-full shadow-lg pl-3 pr-1 py-1 flex items-center gap-2 animate-in fade-in slide-in-from-top-2 duration-200">
          <div className="w-1.5 h-1.5 bg-blue-500 rounded-full animate-pulse" />
          <span className="text-xs font-medium text-blue-700 dark:text-blue-300 whitespace-nowrap">
            Click row to copy to
          </span>
          {rowsBelow > 0 && (
            <>
              <div className="h-4 w-px bg-blue-200 dark:bg-blue-800" />
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleApplyToAll}
                    className="h-6 px-2 text-xs font-medium text-blue-700 hover:text-blue-900 hover:bg-blue-100 dark:text-blue-300 dark:hover:bg-blue-900 dark:hover:text-blue-100"
                  >
                    <ArrowDownToLine className="h-3 w-3 mr-1" />
                    All
                  </Button>
                </TooltipTrigger>
                <TooltipContent side="top" align="center">
                  {rowsBelow === 1
                    ? "Copy to 1 row below"
                    : `Copy to all ${rowsBelow} rows below`}
                </TooltipContent>
              </Tooltip>
            </>
          )}
     
     
     
          <Button
            variant="ghost"
            size="sm"
            onClick={handleCancel}
            className="h-6 w-6 p-0 text-blue-600 hover:text-blue-800 hover:bg-blue-100 dark:hover:bg-blue-900"
          >
            <X className="h-3.5 w-3.5" />
          </Button>
        </div>
      </div>
    </div>
  );
});

CopyDownBanner.displayName = 'CopyDownBanner';
