import React from 'react';
import { View, Text, Alert } from 'react-native';
import { useAppTheme } from '@theme';
import { PrimaryButton } from '@components';
import { useAppDispatch, useAppSelector } from '@store';
import { advanceJobStatus } from '@store/commonReducers/job';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { AppStackParamList } from '@navigation/navigationTypes';
import { RouteNames, JobStatus } from '@utils/constants';
import { getStyles } from './liveTrackingScreen.styles';

export const LiveTrackingScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const dispatch = useAppDispatch();
  const navigation =
    useNavigation<NativeStackNavigationProp<AppStackParamList>>();
  const route =
    useRoute<RouteProp<AppStackParamList, RouteNames.OrderPickedUp>>();
  const { jobId } = route.params;

  const { activeDeliveries } = useAppSelector(state => state.deliveries);
  const activeJob = activeDeliveries?.delivery;

  const handleArrived = () => {
    dispatch(advanceJobStatus(JobStatus.ArrivedAtCustomer));
    navigation.navigate(RouteNames.DeliverOrder, {
      jobId: jobId,
    });
  };

  const handleContact = () => {
    Alert.alert(
      'Contact Customer',
      `Calling ${activeJob?.order?.customer?.user?.name || 'Customer'} at ${
        activeJob?.order?.customer?.user?.phone
      } `,
    );
  };

  // if (!activeJob) return null;

  return (
    <View style={styles.container}>
      {/* Top Floating ETA Card */}
      <View style={styles.etaCard}>
        <Text style={styles.etaTitle}>Arriving in 8 mins</Text>
        <Text style={styles.etaSub}>
          Distance: {activeJob?.estimatedDistanceKm} km • Speed: 24 km/h
        </Text>
      </View>

      {/* Map Background Placeholder */}
      <View style={styles.mapPlaceholder}>
        <Text style={styles.placeholderText}>[ Map Placeholder ]</Text>
      </View>

      {/* Customer Location Bottom Card */}
      <View style={styles.bottomCard}>
        <Text style={styles.cardTitle}>Deliver to</Text>
        <Text style={styles.customerName}>
          {activeJob?.order?.customer?.user?.name}
        </Text>
        <Text style={styles.customerAddress}>
          {activeJob?.order?.dropAddress?.houseNumber +
            ', ' +
            activeJob?.order?.dropAddress?.addressLine1}
        </Text>

        <View style={styles.btnRow}>
          <PrimaryButton
            title="Call"
            onPress={handleContact}
            style={styles.contactBtn}
            textStyle={{ color: colors.text }}
          />
          <PrimaryButton
            title="Arrived at Location"
            onPress={handleArrived}
            style={styles.arrivedBtn}
          />
        </View>
      </View>
    </View>
  );
};

export default LiveTrackingScreen;
