import React, { useEffect, useState } from 'react';
import { checkCodEligibility, type CheckoutApiConfig } from '../core/checkout-api';

function messageForReason(
  reason: 'cod_disabled' | 'pincode_blocked' | 'invalid_pincode' | 'cart_value_exceeded'
): string {
  switch (reason) {
    case 'cod_disabled':
      return 'Cash on Delivery is not enabled for this store.';
    case 'pincode_blocked':
      return 'COD is not available for this pincode.';
    case 'cart_value_exceeded':
      return 'COD is not available for this order value.';
    case 'invalid_pincode':
      return 'Enter a valid pincode to check COD.';
    default:
      return 'COD is not available.';
  }
}

export interface CodAvailabilityBannerProps {
  checkoutConfig: CheckoutApiConfig;
  sessionToken: string;
  pincode: string;
  cartTotalPaise?: number;
  theme?: 'light' | 'dark';
  /** Called when COD eligibility is resolved (for prepaid nudge gating). */
  onCodAllowedChange?: (allowed: boolean) => void;
}

/**
 * Shows COD availability after checkout using `cod_eligibility` (merchant `enable_cod` + D1/D2).
 */
const CodAvailabilityBanner: React.FC<CodAvailabilityBannerProps> = ({
  checkoutConfig,
  sessionToken,
  pincode,
  cartTotalPaise,
  theme = 'light',
  onCodAllowedChange,
}) => {
  const [phase, setPhase] = useState<'loading' | 'ready' | 'error'>('loading');
  const [allowed, setAllowed] = useState(false);
  const [detail, setDetail] = useState<string | undefined>();

  useEffect(() => {
    let cancelled = false;
    setPhase('loading');
    (async () => {
      try {
        const r = await checkCodEligibility(
          checkoutConfig,
          sessionToken,
          pincode,
          cartTotalPaise
        );
        if (cancelled) return;
        setAllowed(r.cod_allowed);
        onCodAllowedChange?.(r.cod_allowed);
        setDetail(
          r.cod_allowed
            ? undefined
            : r.reason
              ? messageForReason(r.reason)
              : undefined
        );
        setPhase('ready');
      } catch {
        if (!cancelled) {
          setPhase('error');
          setAllowed(false);
          setDetail('Could not verify COD. Try again.');
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [checkoutConfig, sessionToken, pincode, cartTotalPaise]);

  const isDark = theme === 'dark';

  return (
    <div
      className={`qr-cod-banner${isDark ? ' qr-cod-banner--dark' : ''}`}
      role="status"
      aria-live="polite"
    >
      <div className="qr-cod-banner__title">Cash on Delivery</div>
      {phase === 'loading' && (
        <p className="qr-cod-banner__text qr-cod-banner__text--muted">Checking availability…</p>
      )}
      {phase === 'error' && <p className="qr-cod-banner__text qr-cod-banner__text--warn">{detail}</p>}
      {phase === 'ready' && allowed && (
        <p className="qr-cod-banner__text qr-cod-banner__text--ok">Available for this address.</p>
      )}
      {phase === 'ready' && !allowed && detail && (
        <p className="qr-cod-banner__text qr-cod-banner__text--muted">{detail}</p>
      )}
    </div>
  );
};

export default CodAvailabilityBanner;
