import { ReactNode, useEffect, useRef, useId } from 'react';
import clsx from 'clsx';
import { useLocalization } from '@akinon/next/hooks';
import { Icon } from '@theme/components';

export type SectionStatus = 'locked' | 'active' | 'completed';

interface AccordionSectionProps {
  step: number;
  title: string;
  status: SectionStatus;
  summary?: ReactNode;
  onEdit?: () => void;
  editable?: boolean;
  children: ReactNode;
  dataTestId?: string;
  padded?: boolean;
}

export const AccordionSection = ({
  step,
  title,
  status,
  summary,
  onEdit,
  editable = true,
  children,
  dataTestId,
  padded = true
}: AccordionSectionProps) => {
  const { t } = useLocalization();
  const isOpen = status === 'active';
  const isCompleted = status === 'completed';
  const isLocked = status === 'locked';

  const contentRef = useRef<HTMLDivElement>(null);
  const headerId = useId();
  const panelId = useId();
  const wasOpenRef = useRef(isOpen);

  useEffect(() => {
    if (isOpen && !wasOpenRef.current && contentRef.current) {
      const firstFocusable = contentRef.current.querySelector<HTMLElement>(
        'input:not([disabled]), button:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])'
      );
      firstFocusable?.focus({ preventScroll: true });
    }
    wasOpenRef.current = isOpen;
  }, [isOpen]);

  return (
    <section
      className={clsx(
        'mb-4 overflow-hidden rounded-2xl bg-white last:mb-0',
        'transition-all duration-300 ease-out',
        isOpen
          ? 'shadow-[0_12px_40px_-16px_rgba(0,0,0,0.16)] ring-1 ring-black-800/10'
          : 'shadow-[0_1px_3px_rgba(0,0,0,0.04)] ring-1 ring-black/[0.04]',
        isLocked && 'opacity-50'
      )}
      data-testid={dataTestId}
      data-status={status}
      aria-labelledby={headerId}
    >
      <header
        id={headerId}
        className={clsx(
          'flex items-center justify-between gap-3 px-6 py-5 sm:px-7',
          isOpen && 'border-b border-gray-100'
        )}
      >
        <div className="flex items-center gap-3.5">
          <span
            className={clsx(
              'flex h-8 w-8 items-center justify-center rounded-full text-sm font-semibold transition-all',
              isOpen && 'bg-black-800 text-white',
              isCompleted && !isOpen && 'bg-black-800 text-white',
              isLocked && 'bg-gray-100 text-gray-400'
            )}
            aria-hidden="true"
          >
            {isCompleted ? (
              <Icon name="check" size={14} className="fill-white" />
            ) : (
              step
            )}
          </span>
          <h2
            className={clsx(
              'text-lg font-semibold leading-tight tracking-tight',
              isOpen || isCompleted ? 'text-black-800' : 'text-gray-500'
            )}
          >
            {title}
          </h2>
        </div>

        {isCompleted && editable && onEdit && (
          <button
            type="button"
            onClick={onEdit}
            className={clsx(
              'group flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium',
              'text-gray-700 transition-all duration-150',
              'hover:bg-gray-100 hover:text-black-800',
              'focus:outline-none focus-visible:ring-2 focus-visible:ring-black-800 focus-visible:ring-offset-1'
            )}
            data-testid={`${dataTestId}-edit`}
            aria-label={`${t('checkout.one_page.edit')} ${title}`}
          >
            <span>{t('checkout.one_page.edit')}</span>
          </button>
        )}
      </header>

      <div
        id={panelId}
        role="region"
        aria-labelledby={headerId}
        hidden={!isOpen}
        className={clsx(
          'transition-opacity duration-300 ease-out',
          isOpen ? 'opacity-100' : 'opacity-0'
        )}
      >
        <div ref={contentRef} className={padded ? 'px-6 py-6 sm:px-7' : undefined}>
          {children}
        </div>
      </div>

      {isCompleted && summary && (
        <div className="border-t border-gray-100 px-6 py-4 text-sm text-gray-700 sm:px-7">
          {summary}
        </div>
      )}
    </section>
  );
};

export default AccordionSection;
