/**
 * 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 } from 'lucide-react';
import { useValidationStore } from '../store/validationStore';
import { useIsCopyDownActive } from '../store/selectors';

/**
 * 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();
  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();

      // Calculate position relative to the table container
      // Position banner centered horizontally on the cell, above it
      const topPosition = cellRect.top - tableRect.top - 55; // 55px above the cell (enough to not cover it)
      const leftPosition = cellRect.left - tableRect.left + cellRect.width / 2;

      setPosition({
        top: Math.max(topPosition, 8), // Minimum 8px from top
        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();
  };

  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-xl shadow-lg px-4 py-2.5 flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-200">
          <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse" />
          <span className="text-sm font-medium text-blue-700 dark:text-blue-300">
            Click on the last row you want to copy to
          </span>
          <Button
            variant="ghost"
            size="sm"
            onClick={handleCancel}
            className="h-7 w-7 p-0 text-blue-600 hover:text-blue-800 hover:bg-blue-100 dark:hover:bg-blue-900"
          >
            <X className="h-4 w-4" />
          </Button>
        </div>
      </div>
    </div>
  );
});

CopyDownBanner.displayName = 'CopyDownBanner';
