'use client';

import { useId, useMemo, useState, type KeyboardEvent } from 'react';
import { cn } from '@/lib/cn';
import { interpolate } from '@/lib/i18n/interpolate';
import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { Icon } from '@/components/ui/icons/Icon';
import { QrCodeCard } from '@/components/ui/domain/QrCodeCard';
import { Image } from '@/components/ui/primitives/Image';

export interface VoucherCardFanVoucher {
  voucherId: string;
  qrPngUrl: string | null;
  expiresAt?: string | null;
}

export interface VoucherCardFanProps {
  vouchers: VoucherCardFanVoucher[];
  className?: string;
  cardClassName?: string;
}

const FAN_CARD_CLASSES = ['-rotate-6 md:-rotate-3', 'rotate-0', 'rotate-6 md:rotate-3'] as const;

function getWrappedIndex(index: number, total: number): number {
  if (total === 0) return 0;
  return (index + total) % total;
}

export function VoucherCardFan({ vouchers, className, cardClassName }: VoucherCardFanProps) {
  const t = useT('qr_redeem');
  const [activeIndex, setActiveIndex] = useState(0);
  const [expanded, setExpanded] = useState(false);
  const groupId = useId();

  const safeVouchers = useMemo(
    () => vouchers.filter((voucher) => Boolean(voucher.qrPngUrl)),
    [vouchers],
  );

  if (safeVouchers.length === 0) return null;

  if (safeVouchers.length === 1) {
    const voucher = safeVouchers[0];
    if (!voucher) return null;
    return (
      <QrCodeCard
        qrPngUrl={voucher.qrPngUrl ?? ''}
        expiryIso={voucher.expiresAt ?? undefined}
        className={cn('w-full max-w-xs', cardClassName, className)}
      />
    );
  }

  const activeVoucher = safeVouchers[activeIndex] ?? safeVouchers[0];

  function focusVoucherButton(index: number) {
    const element = document.getElementById(`${groupId}-voucher-${index}`);
    if (element instanceof HTMLButtonElement) element.focus();
  }

  function moveActiveIndex(nextIndex: number) {
    const wrappedIndex = getWrappedIndex(nextIndex, safeVouchers.length);
    setActiveIndex(wrappedIndex);
    focusVoucherButton(wrappedIndex);
  }

  function toggleExpanded(index: number) {
    setActiveIndex(index);
    setExpanded((current) => (index === activeIndex ? !current : true));
  }

  function handleButtonKeyDown(event: KeyboardEvent<HTMLButtonElement>, index: number) {
    const isRtl = getComputedStyle(event.currentTarget).direction === 'rtl';

    switch (event.key) {
      case 'ArrowLeft':
        event.preventDefault();
        moveActiveIndex(index + (isRtl ? 1 : -1));
        break;
      case 'ArrowUp':
        event.preventDefault();
        moveActiveIndex(index - 1);
        break;
      case 'ArrowRight':
        event.preventDefault();
        moveActiveIndex(index + (isRtl ? -1 : 1));
        break;
      case 'ArrowDown':
        event.preventDefault();
        moveActiveIndex(index + 1);
        break;
      case 'Home':
        event.preventDefault();
        moveActiveIndex(0);
        break;
      case 'End':
        event.preventDefault();
        moveActiveIndex(safeVouchers.length - 1);
        break;
      case 'Enter':
      case ' ':
        event.preventDefault();
        toggleExpanded(index);
        break;
      case 'Escape':
        if (expanded) {
          event.preventDefault();
          setExpanded(false);
        }
        break;
      default:
        break;
    }
  }

  return (
    <div className={cn('flex w-full flex-col items-center gap-4', className)}>
      <div
        role="group"
        aria-label={t('fan_group_label')}
        className="flex w-full max-w-sm items-end justify-center px-4 py-2"
      >
        {safeVouchers.map((voucher, index) => {
          const isActive = index === activeIndex;
          const isExpanded = expanded && isActive;
          const rotateClass = FAN_CARD_CLASSES[index % FAN_CARD_CLASSES.length];
          return (
            <Button
              key={voucher.voucherId}
              id={`${groupId}-voucher-${index}`}
              type="button"
              variant="ghost"
              tabIndex={isActive ? 0 : -1}
              aria-expanded={isExpanded}
              aria-controls={`${groupId}-panel`}
              aria-label={interpolate(t('fan_card_label'), {
                index: String(index + 1),
                total: String(safeVouchers.length),
              })}
              onClick={() => toggleExpanded(index)}
              onKeyDown={(event) => handleButtonKeyDown(event, index)}
              className={cn(
                'bg-surface-base border-border-default focus-visible:ring-brand-primary-500 relative -mx-3 flex h-36 w-24 shrink-0 origin-bottom flex-col items-center justify-between gap-0 overflow-hidden rounded-xl border p-2 text-center text-base font-normal text-inherit shadow-sm transition-transform duration-200 ease-out hover:bg-transparent focus-visible:z-20 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none active:bg-transparent motion-reduce:transition-none',
                rotateClass,
                isActive && 'border-brand-primary-500 z-10 -translate-y-2 shadow-md',
                expanded && !isActive && 'scale-95 opacity-70',
              )}
              data-testid={`voucher-fan-card-${index}`}
            >
              <div className="bg-surface-raised flex h-20 w-full items-center justify-center rounded-lg p-2">
                <Image
                  src={voucher.qrPngUrl ?? ''}
                  alt=""
                  decorative
                  width={64}
                  height={64}
                  className="h-16 w-16 object-contain"
                  loading="lazy"
                />
              </div>
              <span className="text-text-secondary text-xs font-medium">
                {interpolate(t('unit_label'), {
                  index: String(index + 1),
                  total: String(safeVouchers.length),
                })}
              </span>
            </Button>
          );
        })}
      </div>

      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={() => setExpanded((current) => !current)}
        aria-expanded={expanded}
        aria-controls={`${groupId}-panel`}
        iconStart={<Icon name={expanded ? 'ChevronUp' : 'ChevronDown'} size="sm" />}
      >
        {expanded ? t('fan_collapse') : t('fan_expand')}
      </Button>

      {activeVoucher && expanded ? (
        <div
          id={`${groupId}-panel`}
          aria-live="polite"
          className="flex w-full flex-col items-center gap-2"
          data-testid="voucher-fan-expanded-panel"
        >
          <span className="text-text-secondary text-xs font-medium">
            {interpolate(t('fan_active_label'), {
              index: String(activeIndex + 1),
              total: String(safeVouchers.length),
            })}
          </span>
          <QrCodeCard
            qrPngUrl={activeVoucher.qrPngUrl ?? ''}
            expiryIso={activeVoucher.expiresAt ?? undefined}
            className={cn('w-full max-w-xs', cardClassName)}
          />
        </div>
      ) : null}
    </div>
  );
}
