'use client';

import { useCallback, useMemo } from 'react';
import { cn } from '@djangocfg/ui-core/lib';
import { Button } from '@djangocfg/ui-core/components';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useT } from '@djangocfg/i18n';
import type { TourNavigationProps } from '../types';

/**
 * Navigation buttons for tour steps.
 * For multi-page tours, use nextRoute/previousRoute with your router.
 * Skip button is now in TourContent header as × icon.
 */
export function TourNavigation({
  onNext,
  onPrevious,
  isFirstStep,
  isLastStep,
  nextLabel,
  previousLabel,
  finishLabel,
  nextRoute,
  previousRoute,
  className,
}: TourNavigationProps) {
  const t = useT();

  // Prepare labels
  const labels = useMemo(() => {
    const defaultNext = isLastStep ? t('tools.tour.finish') : t('tools.tour.next');
    return {
      next: nextLabel ?? finishLabel ?? defaultNext,
      previous: previousLabel ?? t('tools.tour.previous'),
    };
  }, [isLastStep, nextLabel, finishLabel, previousLabel, t]);

  // Prepare visibility flags
  const showPrevious = !isFirstStep;
  const showNextArrow = !isLastStep;

  // Handlers
  const handleNext = useCallback(() => {
    if (nextRoute && typeof window !== 'undefined') {
      window.location.href = nextRoute;
    }
    onNext();
  }, [nextRoute, onNext]);

  const handlePrevious = useCallback(() => {
    if (previousRoute && typeof window !== 'undefined') {
      window.location.href = previousRoute;
    }
    onPrevious();
  }, [previousRoute, onPrevious]);

  // Styles
  const containerClassName = cn('flex items-center gap-2', className);

  return (
    <div className={containerClassName}>
      {showPrevious ? (
        <Button variant="ghost" size="sm" onClick={handlePrevious} className="flex-1 gap-1">
          <ChevronLeft className="h-4 w-4 shrink-0" />
          <span className="truncate">{labels.previous}</span>
        </Button>
      ) : (
        <div className="flex-1" />
      )}

      <Button size="sm" onClick={handleNext} className="flex-1 gap-1">
        <span className="truncate">{labels.next}</span>
        {showNextArrow && <ChevronRight className="h-4 w-4 shrink-0" />}
      </Button>
    </div>
  );
}
