import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  SafeAreaView,
  Linking,
  Image,
} from 'react-native';
// Explicit .native imports so TypeScript (tsconfig.native.json) resolves the
// correct platform files — Metro handles implicit resolution at bundle time.
import MapPinSelector from './MapPinSelector.native';
import AddressForm from './AddressForm.native';
import type { CheckoutEvent, CheckoutWidgetProps, CompleteAddress } from '../core/types';
import CodAvailabilityBanner from './CodAvailabilityBanner';
import { styles, COLORS } from '../styles/checkout.native';

// ─── Types ────────────────────────────────────────────────────────────────────

type Step = 'map' | 'form' | 'done';

interface ConfirmedLocation {
  lat: number;
  lng: number;
  digipin: string;
}

// ─── Success screen ───────────────────────────────────────────────────────────

interface SuccessScreenProps {
  address: CompleteAddress;
  onEditAddress: () => void;
  isDark: boolean;
}

const SuccessScreen: React.FC<SuccessScreenProps> = ({ address, onEditAddress, isDark }) => (
  <View style={styles.successScreen}>
    <Text style={styles.successIcon}>✅</Text>

    <Text style={[styles.successTitle, isDark && styles.successTitleDark]}>
      Address Saved!
    </Text>

    <Text style={[styles.successAddress, isDark && styles.successAddressDark]}>
      {address.formattedAddress}
    </Text>

    {/* DigiPin badge */}
    <View style={[styles.successDigipinBadge, isDark && styles.successDigipinBadgeDark]}>
      <Text style={styles.digipinLabel}>DigiPin</Text>
      <Text style={styles.digipinCode}>{address.digipin}</Text>
    </View>

    <TouchableOpacity
      style={[styles.btnGhost, { marginTop: 4 }]}
      onPress={onEditAddress}
      activeOpacity={0.8}
      accessibilityRole="button"
    >
      <Text style={[styles.btnGhostText, isDark && styles.btnGhostTextDark]}>
        Change Address
      </Text>
    </TouchableOpacity>
  </View>
);

// ─── Main Widget ──────────────────────────────────────────────────────────────

/**
 * QuantaRoute Checkout Widget — native (iOS/Android) version.
 *
 * Two-step address collection:
 *   Step 1 – Map: drag pin to exact location (DigiPin computed offline, real-time)
 *   Step 2 – Form: auto-filled address + manual flat/building details
 *
 * Metro resolves this file on native; CheckoutWidget.tsx is used on web.
 *
 * Usage in Expo:
 *   import { CheckoutWidget } from '@quantaroute/checkout';
 *   <CheckoutWidget apiKey="..." onComplete={(addr) => console.log(addr)} />
 */
const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
  apiKey,
  apiBaseUrl = 'https://api.quantaroute.com',
  onComplete,
  onError,
  defaultLat,
  defaultLng,
  theme = 'light',
  style,
  mapHeight = 380,
  title = 'Add Delivery Address',
  brandColor,
  logoUrl,
  headerBanner,
  onCheckoutEvent,
  merchantId = '',
  supabaseFunctionBaseUrl = '',
  enableCod = false,
  enableServiceabilityCheck = false,
  showIndiaPostDeliveryWarning = false,
  serviceabilityBlockCheckout,
  codCartTotalPaise,
  codSessionToken = '',
}) => {
  const [step, setStep] = useState<Step>('map');
  const [confirmedLocation, setConfirmedLocation] = useState<ConfirmedLocation | null>(null);
  const [completedAddress, setCompletedAddress] = useState<CompleteAddress | null>(null);

  const checkoutConfig = {
    functionBaseUrl: supabaseFunctionBaseUrl,
    merchantId,
  };
  const codSession = codSessionToken;

  const isDark = theme === 'dark';
  const accent = brandColor ?? COLORS.primary;

  /** Fire an analytics event without blocking the UI. */
  const emit = (partial: Omit<CheckoutEvent, 'timestamp'>) => {
    if (!onCheckoutEvent) return;
    try {
      onCheckoutEvent({ ...partial, timestamp: new Date().toISOString() });
    } catch {
      // Never let analytics crash the checkout
    }
  };

  useEffect(() => {
    const viewedMap: Record<Step, CheckoutEvent['type']> = {
      map: 'map_step_viewed',
      form: 'form_step_viewed',
      done: 'address_completed',
    };
    emit({ type: viewedMap[step], step });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [step]);

  // ── Handlers ──────────────────────────────────────────────────────────────

  const handleLocationConfirm = (lat: number, lng: number, digipin: string) => {
    setConfirmedLocation({ lat, lng, digipin });
    emit({ type: 'location_confirmed', step: 'form', digipin });
    setStep('form');
  };

  const handleAddressComplete = (address: CompleteAddress) => {
    setCompletedAddress(address);
    emit({ type: 'address_completed', step: 'done', digipin: address.digipin });
    setStep('done');
    onComplete(address);
  };

  const handleBack = () => setStep('map');

  const handleEditAddress = () => {
    emit({ type: 'widget_reset', step: 'map' });
    setStep('map');
    setConfirmedLocation(null);
    setCompletedAddress(null);
  };

  // ── Step indicator ─────────────────────────────────────────────────────────

  const renderStepDots = () => (
    <View style={styles.progress}>
      <View style={[styles.progressDot, { backgroundColor: accent }]} />
      <View
        style={[
          styles.progressLine,
          (step === 'form' || step === 'done') && { backgroundColor: accent },
        ]}
      />
      <View
        style={[
          styles.progressDot,
          (step === 'form' || step === 'done') && { backgroundColor: accent },
        ]}
      />
    </View>
  );

  // ── Render ─────────────────────────────────────────────────────────────────

  return (
    <SafeAreaView
      style={[
        styles.container,
        isDark && styles.containerDark,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        style as any,
      ]}
      accessibilityLabel="QuantaRoute checkout widget"
    >
      {/* Widget header (hidden on success screen) */}
      {step !== 'done' ? (
        <>
          <View style={[styles.header, isDark && styles.headerDark]}>
            <View style={styles.headerBrand}>
              {logoUrl ? (
                <Image
                  source={{ uri: logoUrl }}
                  style={styles.headerLogoImg}
                  resizeMode="contain"
                  accessibilityRole="image"
                  accessibilityLabel=""
                />
              ) : (
                <Text style={[styles.headerIcon, { color: accent }]}>📍</Text>
              )}
              <Text style={[styles.headerTitle, isDark && styles.headerTitleDark]}>
                {title}
              </Text>
            </View>
            {renderStepDots()}
          </View>
          {headerBanner ? (
            <View style={[styles.headerBannerSlot, isDark && styles.headerBannerSlotDark]}>
              {headerBanner}
            </View>
          ) : null}
        </>
      ) : null}

      {/* ── Step 1: Map ── */}
      {step === 'map' ? (
        <MapPinSelector
          onLocationConfirm={handleLocationConfirm}
          defaultLat={defaultLat}
          defaultLng={defaultLng}
          mapHeight={mapHeight}
          theme={theme}
          brandColor={brandColor}
        />
      ) : null}

      {/* ── Step 2: Form ── */}
      {step === 'form' && confirmedLocation ? (
        <AddressForm
          digipin={confirmedLocation.digipin}
          lat={confirmedLocation.lat}
          lng={confirmedLocation.lng}
          apiKey={apiKey}
          apiBaseUrl={apiBaseUrl}
          onAddressComplete={handleAddressComplete}
          onBack={handleBack}
          onError={onError}
          theme={theme}
          checkoutConfig={checkoutConfig}
          serviceabilitySessionToken={codSession}
          enableServiceabilityCheck={enableServiceabilityCheck}
          showIndiaPostDeliveryWarning={showIndiaPostDeliveryWarning}
          serviceabilityBlockCheckout={serviceabilityBlockCheckout}
        />
      ) : null}

      {/* ── Step 3: Done ── */}
      {step === 'done' && completedAddress ? (
        <>
          <SuccessScreen
            address={completedAddress}
            onEditAddress={handleEditAddress}
            isDark={isDark}
          />
          {enableCod && merchantId && supabaseFunctionBaseUrl && codSession ? (
            <CodAvailabilityBanner
              checkoutConfig={checkoutConfig}
              sessionToken={codSession}
              pincode={completedAddress.pincode}
              cartTotalPaise={codCartTotalPaise}
              theme={theme}
            />
          ) : null}
        </>
      ) : null}

      {/* Powered-by footer */}
      <View style={[styles.footer, isDark && styles.footerDark]}>
        <Text style={[styles.footerText, isDark && styles.footerTextDark]}>Powered by</Text>
        <TouchableOpacity
          onPress={() => void Linking.openURL('https://quantaroute.com')}
          accessibilityRole="link"
          accessibilityLabel="QuantaRoute website"
        >
          <Text style={styles.footerLink}>QuantaRoute</Text>
        </TouchableOpacity>
        <Text style={[styles.footerText, isDark && styles.footerTextDark]}>  🇮🇳</Text>
      </View>
    </SafeAreaView>
  );
};

export default CheckoutWidget;
