import React, { useEffect } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
import { useNavigation, useRoute, RouteProp } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { getStyles } from './liveTrackingScreen.styles';
import { Header, PrimaryButton, TrackingMap } from '@components';
import { useAppTheme } from '@theme';
import { AppStackParamList } from '../../../navigation/appStack';
import { RootState, useAppDispatch, useAppSelector } from '@store';
import { getOrderByIdThunk } from '../checkoutPaymentScreen';
import { useOrderTracking } from './hooks';

type LiveTrackingNavProp = StackNavigationProp<
  AppStackParamList,
  'LiveTrackingScreen'
>;
type LiveTrackingRouteProp = RouteProp<AppStackParamList, 'LiveTrackingScreen'>;

export const LiveTrackingScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const navigation = useNavigation<LiveTrackingNavProp>();
  const route = useRoute<LiveTrackingRouteProp>();
  const orderId = route.params?.orderId || 'ORD-123456';

  const dispatch = useAppDispatch();
  const { accessToken } = useAppSelector((state: RootState) => state.auth);
  const { orderDetails, orderDetailsLoading } = useAppSelector(
    (state: RootState) => state.paymentMethods,
  );
  // console.log('[LiveTrackingScreen] orderDetails:', orderDetails);

  const { driverLocation, orderStatus } = useOrderTracking(
    orderId,
    accessToken,
  );

  // Fetch order details if not matching or missing
  useEffect(() => {
    if (orderId && (!orderDetails || orderDetails.id !== orderId)) {
      dispatch(getOrderByIdThunk(orderId));
    }
  }, [dispatch, orderId, orderDetails]);

  // Navigate to delivered screen once status transitions to DELIVERED
  useEffect(() => {
    if (orderStatus === 'DELIVERED') {
      console.log(
        `[LiveTrackingScreen] Order ${orderId} delivered! Navigating to OrderDeliveredScreen.`,
      );
      navigation.navigate('OrderDeliveredScreen', { orderId });
    }
  }, [orderStatus, navigation, orderId]);

  if (orderDetailsLoading || !orderDetails) {
    return (
      <View style={styles.container}>
        <Header title="Live Tracking" onBack={() => navigation.goBack()} />
        <View
          style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}
        >
          <ActivityIndicator size="large" color={colors.primary} />
          <Text style={{ marginTop: 8, color: colors.textSecondary }}>
            Loading tracking details...
          </Text>
        </View>
      </View>
    );
  }

  // Get drop address coordinates from orderDetails
  const dropCoords = {
    latitude: orderDetails.dropAddress?.latitude || 12.9352,
    longitude: orderDetails.dropAddress?.longitude || 77.6245,
  };

  return (
    <View style={styles.container}>
      <Header title="Live Tracking" onBack={() => navigation.goBack()} />
      <View style={{ flex: 1 }}>
        <TrackingMap
          customerDropoff={dropCoords}
          driverLocation={driverLocation}
          showRoute={true}
        />
      </View>
      <View style={styles.agentSheet}>
        <PrimaryButton
          title="Simulate Order Delivered"
          onPress={() =>
            navigation.navigate('OrderDeliveredScreen', { orderId })
          }
          style={{ marginBottom: 16 }}
        />
        <Text style={styles.agentName}>Rahul Sharma</Text>
        <Text style={styles.agentRating}>⭐ 4.8</Text>
        <Text style={styles.agentVehicle}>KA-01-AB-1234 • Honda Activa</Text>
        <View style={styles.agentActions}>
          <PrimaryButton
            title="Call"
            onPress={() => {}}
            style={{ flex: 1, marginRight: 8 }}
          />
          <PrimaryButton
            title="Message"
            onPress={() => {}}
            style={{ flex: 1, marginLeft: 8 }}
          />
        </View>
      </View>
    </View>
  );
};
export default LiveTrackingScreen;
