import clsx from 'clsx';
import { useAppSelector } from '@akinon/next/redux/hooks';
import { useLocalization } from '@akinon/next/hooks';
import SelectedPaymentOptionView from '@akinon/next/components/selected-payment-option-view';
import type { RootState } from '@theme/redux/store';
import AccordionSection, { SectionStatus } from '../accordion-section';
import PaymentOptionsGrid from '../payment-options-grid';
import { PaymentGridSkeleton } from '../skeletons/payment-skeleton';

interface PaymentSectionProps {
  status: SectionStatus;
  onEdit: () => void;
}

const PaymentSection = ({ status, onEdit }: PaymentSectionProps) => {
  const { t } = useLocalization();
  const isPaymentStepBusy = useAppSelector(
    (state: RootState) => state.checkout.steps.payment.busy
  );
  const paymentOption = useAppSelector(
    (state: RootState) => state.checkout.preOrder?.payment_option
  );
  const paymentOptionsCount = useAppSelector(
    (state: RootState) => state.checkout.paymentOptions.length
  );

  return (
    <AccordionSection
      step={4}
      title={t('checkout.one_page.payment.title')}
      status={status}
      onEdit={onEdit}
      editable={false}
      dataTestId="one-page-payment"
      padded={false}
    >
      <div
        className={clsx({
          'pointer-events-none opacity-50': isPaymentStepBusy
        })}
      >
        <div className="px-5 py-5">
          {paymentOptionsCount === 0 ? (
            <PaymentGridSkeleton />
          ) : (
            <PaymentOptionsGrid />
          )}
        </div>

        {paymentOption && (
          <div
            className="border-t border-gray-200"
            data-testid="one-page-selected-payment"
          >
            <SelectedPaymentOptionView />
          </div>
        )}

        {!paymentOption && paymentOptionsCount > 0 && (
          <div className="border-t border-gray-200 bg-gray-50/30 px-5 py-4">
            <p className="text-sm italic text-gray-700">
              {t('checkout.one_page.payment.select_method')}
            </p>
          </div>
        )}
      </div>
    </AccordionSection>
  );
};

export default PaymentSection;
