import { useEffect, useState } from 'react';
import clsx from 'clsx';
import { useAppSelector } from '@akinon/next/redux/hooks';
import { useLocalization } from '@akinon/next/hooks';
import { Price, Icon } from '@theme/components';
import type { RootState } from '@theme/redux/store';
import OnePageSummary from './one-page-summary';
import type { SectionId } from './hooks/use-section-state';

interface MobileSummarySheetProps {
  onEditSection: (section: SectionId) => void;
  showReview?: boolean;
}

const MobileSummarySheet = ({
  onEditSection,
  showReview = true
}: MobileSummarySheetProps) => {
  const { t } = useLocalization();
  const [isOpen, setIsOpen] = useState(false);
  const preOrder = useAppSelector(
    (state: RootState) => state.checkout.preOrder
  );

  useEffect(() => {
    if (!isOpen) return undefined;
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') setIsOpen(false);
    };
    document.addEventListener('keydown', onKey);
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = previousOverflow;
    };
  }, [isOpen]);

  if (!preOrder) return null;
  const paymentName = preOrder.payment_option?.name;

  return (
    <>
      {isOpen && (
        <button
          type="button"
          aria-label={t('checkout.one_page.summary.hide_summary')}
          className="fixed inset-0 z-40 bg-black/50 backdrop-blur-sm lg:hidden"
          onClick={() => setIsOpen(false)}
          data-testid="one-page-mobile-summary-backdrop"
        />
      )}

      <div className="relative z-50">
        <button
          type="button"
          onClick={() => setIsOpen((prev) => !prev)}
          aria-expanded={isOpen}
          aria-controls="mobile-summary-content"
          className="flex w-full items-center justify-between gap-3 border-t border-gray-200 bg-white px-5 py-4 shadow-[0_-8px_24px_-12px_rgba(0,0,0,0.12)] focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-secondary"
          data-testid="one-page-mobile-summary-toggle"
        >
          <span className="flex flex-col items-start gap-1">
            <span className="flex items-center gap-2 text-[11px] font-medium uppercase tracking-wider text-gray-600">
              <Icon name="basket" size={12} aria-hidden="true" />
              {isOpen
                ? t('checkout.one_page.summary.hide_summary')
                : t('checkout.one_page.summary.show_summary')}
              <Icon
                name="chevron-end"
                size={10}
                aria-hidden="true"
                className={clsx('transition-transform duration-200', {
                  'rotate-90': isOpen,
                  '-rotate-90': !isOpen
                })}
              />
            </span>
            {paymentName && (
              <span className="text-xs font-medium text-black-800">
                {paymentName}
              </span>
            )}
          </span>
          <span className="text-xl font-bold tabular-nums text-black-800">
            <Price value={preOrder.unpaid_amount} />
          </span>
        </button>

        {isOpen && (
          <div
            id="mobile-summary-content"
            role="dialog"
            aria-modal="true"
            aria-label={t('checkout.summary.title')}
            className="max-h-[75vh] overflow-y-auto border-t border-gray-200 bg-[#fafafa] px-4 py-5"
          >
            <OnePageSummary
              onEditSection={onEditSection}
              showReview={showReview}
            />
          </div>
        )}
      </div>
    </>
  );
};

export default MobileSummarySheet;
