import React, { useEffect, useState } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
import { checkCodEligibility, type CheckoutApiConfig } from '../core/checkout-api';
import { styles, COLORS } from '../styles/checkout.native';

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';
  onCodAllowedChange?: (allowed: boolean) => void;
}

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>();
  const isDark = theme === 'dark';

  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]);

  return (
    <View style={[styles.codBanner, isDark && styles.codBannerDark]}>
      <Text style={[styles.codBannerTitle, isDark && styles.codBannerTitleDark]}>
        Cash on Delivery
      </Text>
      {phase === 'loading' && (
        <View style={styles.codBannerRow}>
          <ActivityIndicator size="small" color={COLORS.primary} />
          <Text style={[styles.codBannerMuted, isDark && styles.codBannerMutedDark]}>
            Checking availability…
          </Text>
        </View>
      )}
      {phase === 'error' && (
        <Text style={[styles.codBannerWarn, isDark && styles.codBannerWarnDark]}>{detail}</Text>
      )}
      {phase === 'ready' && allowed && (
        <Text style={[styles.codBannerOk, isDark && styles.codBannerOkDark]}>
          Available for this address.
        </Text>
      )}
      {phase === 'ready' && !allowed && detail ? (
        <Text style={[styles.codBannerMuted, isDark && styles.codBannerMutedDark]}>{detail}</Text>
      ) : null}
    </View>
  );
};

export default CodAvailabilityBanner;
