import { useState, useRef, useEffect, type KeyboardEvent, type RefObject } from 'react';
import type { Project } from '../data/Project';

interface ProjectAction {
  type: 'github' | 'live';
  url: string;
}

interface UseProjectKeyboardNavigationProps {
  projects: Project[];
  announce: (message: string) => void;
  useTabToNavigateText: string;
}

interface UseProjectKeyboardNavigationReturn {
  activeCardIndex: number | null;
  focusedActionIndex: number;
  cardRefs: RefObject<(HTMLElement | null)[]>;
  actionRefs: RefObject<(HTMLAnchorElement | null)[]>;
  handleCardSelect: (index: number) => void;
  handleCardKeyDown: (event: KeyboardEvent<HTMLElement>, cardIndex: number) => void;
  handleActionKeyDown: (event: KeyboardEvent<HTMLAnchorElement>, cardIndex: number, actionIndex: number) => void;
  getProjectActions: (project: Project) => ProjectAction[];
}

/**
 * Custom hook for managing keyboard navigation in project cards
 * Handles card selection, focus management, and keyboard shortcuts
 */
export function useProjectKeyboardNavigation({
  projects,
  announce,
  useTabToNavigateText,
}: UseProjectKeyboardNavigationProps): UseProjectKeyboardNavigationReturn {
  const [activeCardIndex, setActiveCardIndex] = useState<number | null>(null);
  const [focusedActionIndex, setFocusedActionIndex] = useState<number>(0);
  const cardRefs = useRef<(HTMLElement | null)[]>([]);
  const actionRefs = useRef<(HTMLAnchorElement | null)[]>([]);

  // Get available actions for a project
  const getProjectActions = (project: Project): ProjectAction[] => {
    const actions: ProjectAction[] = [];
    if (project.github) actions.push({ type: 'github', url: project.github });
    if (project.live) actions.push({ type: 'live', url: project.live });
    return actions;
  };

  // Handle card selection
  const handleCardSelect = (index: number) => {
    setActiveCardIndex(index);
    setFocusedActionIndex(0);

    const project = projects[index];
    const actions = getProjectActions(project);
    const announcement = `${project.title} card selected. ${actions.length} actions available. ${useTabToNavigateText}, Escape to close.`;
    announce(announcement);
  };

  // Handle keyboard navigation within cards
  const handleCardKeyDown = (event: KeyboardEvent<HTMLElement>, cardIndex: number) => {
    const project = projects[cardIndex];
    const actions = getProjectActions(project);

    switch (event.key) {
      case 'Enter':
      case ' ':
        event.preventDefault();
        handleCardSelect(cardIndex);
        break;
      case 'Escape':
        if (activeCardIndex === cardIndex) {
          event.preventDefault();
          setActiveCardIndex(null);
          setFocusedActionIndex(0);
          cardRefs.current[cardIndex]?.focus();
          announce(`${project.title} card closed.`);
        }
        break;
      case 'Tab':
        if (activeCardIndex === cardIndex && actions.length > 0) {
          event.preventDefault();
          const nextActionIndex = event.shiftKey
            ? (focusedActionIndex - 1 + actions.length) % actions.length
            : (focusedActionIndex + 1) % actions.length;
          setFocusedActionIndex(nextActionIndex);

          // Focus the action button
          const actionButton = actionRefs.current[cardIndex * 2 + nextActionIndex];
          actionButton?.focus();
        }
        break;
      case 'ArrowDown':
      case 'ArrowUp':
        if (activeCardIndex !== null) {
          event.preventDefault();
          const direction = event.key === 'ArrowDown' ? 1 : -1;
          const nextCardIndex = (cardIndex + direction + projects.length) % projects.length;

          // Close current card and move to next
          setActiveCardIndex(null);
          setFocusedActionIndex(0);
          cardRefs.current[nextCardIndex]?.focus();
          announce(`Moved to ${projects[nextCardIndex].title} card.`);
        }
        break;
    }
  };

  // Handle action button keyboard navigation
  const handleActionKeyDown = (event: KeyboardEvent<HTMLAnchorElement>, cardIndex: number, actionIndex: number) => {
    const actions = getProjectActions(projects[cardIndex]);

    switch (event.key) {
      case 'Escape':
        event.preventDefault();
        setActiveCardIndex(null);
        setFocusedActionIndex(0);
        cardRefs.current[cardIndex]?.focus();
        announce(`${projects[cardIndex].title} card closed.`);
        break;
      case 'Tab':
        if (event.shiftKey && actionIndex === 0) {
          // Tab back to card
          event.preventDefault();
          cardRefs.current[cardIndex]?.focus();
        } else if (!event.shiftKey && actionIndex === actions.length - 1) {
          // Tab forward to next card
          event.preventDefault();
          const nextCardIndex = (cardIndex + 1) % projects.length;
          setActiveCardIndex(null);
          setFocusedActionIndex(0);
          cardRefs.current[nextCardIndex]?.focus();
          announce(`Moved to ${projects[nextCardIndex].title} card.`);
        }
        break;
    }
  };

  // Focus management effect
  useEffect(() => {
    if (activeCardIndex !== null) {
      const firstActionRef = actionRefs.current[activeCardIndex * 2];
      if (firstActionRef) {
        firstActionRef.focus();
      }
    }
  }, [activeCardIndex]);

  return {
    activeCardIndex,
    focusedActionIndex,
    cardRefs,
    actionRefs,
    handleCardSelect,
    handleCardKeyDown,
    handleActionKeyDown,
    getProjectActions,
  };
}
