'use client';
import { FunctionComponent, useState } from 'react';
import { useTranslations } from 'next-intl';
import AppButton from '@/components/common/AppButton';
import ConfirmDialog from '@/components/common/ConfirmDialog';

export interface CheckOutConfirmButtonProps {
  /** Fires the real check-out mutation — called only after the nurse confirms. */
  onConfirm: () => void;
  /** The check-out mutation is in flight for this session. */
  busy?: boolean;
  /** Acquiring GPS for this session (pre-mutation). */
  acquiringLocation?: boolean;
  /** Renders as the full-width thumb-reach hero action (the day surface + the in-visit banner). */
  fullWidth?: boolean;
  variant?: 'contained' | 'outlined';
}

/**
 * The EVV check-out action, everywhere it appears (`SessionCard`'s hero CTA and `BookingDetailView`'s
 * promoted in-visit banner): a single tap opens a lightweight confirm — check-out ends the visit and
 * starts the payout clock, so a mis-tap is consequential enough to warrant one extra step, but never a
 * multi-field form. `onConfirm` fires the real mutation only after the nurse confirms.
 * @component CheckOutConfirmButton
 */
const CheckOutConfirmButton: FunctionComponent<CheckOutConfirmButtonProps> = ({
  onConfirm,
  busy = false,
  acquiringLocation = false,
  fullWidth = false,
  variant = 'contained',
}) => {
  const t = useTranslations('booking');
  const [confirmOpen, setConfirmOpen] = useState(false);
  const disabled = busy || acquiringLocation;

  return (
    <>
      <AppButton
        color="secondary"
        variant={variant}
        startIcon={acquiringLocation ? 'gps' : 'check_out'}
        disabled={disabled}
        onClick={() => setConfirmOpen(true)}
        sx={
          fullWidth
            ? { width: '100%', minHeight: 48, py: 1.5 }
            : { alignSelf: 'flex-start', py: 1 }
        }
      >
        {acquiringLocation ? t('evv_acquiring_location') : busy ? t('evv_checking_out') : t('evv_check_out')}
      </AppButton>
      <ConfirmDialog
        open={confirmOpen}
        title={t('evv_checkout_confirm_title')}
        body={t('evv_checkout_confirm_body')}
        confirmLabel={t('evv_checkout_confirm_cta')}
        cancelLabel={t('evv_checkout_confirm_cancel')}
        onClose={() => setConfirmOpen(false)}
        onConfirm={() => {
          setConfirmOpen(false);
          onConfirm();
        }}
      />
    </>
  );
};

export default CheckOutConfirmButton;
