import { useLocalSearchParams } from 'expo-router';
import { useEffect, useMemo, useState } from 'react';
import { Image, Linking, SafeAreaView, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { io, type Socket } from 'socket.io-client';
import { CustomerBottomNav } from '../components/customer-bottom-nav';
import { CustomerPageHeader } from '../components/customer-page-header';
import { API_URL } from '../src/runtime-config';
import { useCustomerSession } from '../src/store/session';
import { getCustomerTheme, useCustomerTheme } from '../src/store/theme';

type TrackingPayload = {
  orderId: string;
  status: string;
  trackingStatusLabel: string;
  restaurant: { name: string; latitude: number | string | null; longitude: number | string | null; addressLabel?: string | null };
  customer: { name: string; latitude: number | string | null; longitude: number | string | null; addressLabel?: string | null };
  driver: { name: string; rating?: number | null; vehiclePlate?: string | null; vehicleModel?: string | null } | null;
  delivery?: { etaMinutes?: number | null } | null;
  route: { estimatedPickupTime?: number | null; estimatedDeliveryTime?: number | null } | null;
  latestLocation: { latitude: number | string; longitude: number | string; createdAt?: string } | null;
};

const WS_URL = process.env.EXPO_PUBLIC_WS_URL ?? 'http://192.168.1.71:3001';

const statusFlow = [
  'Pedido confirmado',
  'Restaurante preparando',
  'Buscando entregador',
  'Entregador indo ao restaurante',
  'Pedido retirado',
  'Entregador a caminho',
  'Pedido entregue',
];

function toNumber(value?: number | string | null) {
  const parsed = Number(value ?? 0);
  return Number.isFinite(parsed) ? parsed : null;
}

function buildStaticMapUrl(tracking: TrackingPayload | null) {
  const driverLat = toNumber(tracking?.latestLocation?.latitude);
  const driverLng = toNumber(tracking?.latestLocation?.longitude);
  const customerLat = toNumber(tracking?.customer.latitude);
  const customerLng = toNumber(tracking?.customer.longitude);
  const restaurantLat = toNumber(tracking?.restaurant.latitude);
  const restaurantLng = toNumber(tracking?.restaurant.longitude);
  const centerLat = driverLat ?? customerLat ?? restaurantLat;
  const centerLng = driverLng ?? customerLng ?? restaurantLng;

  if (centerLat === null || centerLng === null) {
    return null;
  }

  const markers = [
    driverLat !== null && driverLng !== null ? `${driverLng},${driverLat},pm2blm` : null,
    restaurantLat !== null && restaurantLng !== null ? `${restaurantLng},${restaurantLat},pm2orgm` : null,
    customerLat !== null && customerLng !== null ? `${customerLng},${customerLat},pm2grm` : null,
  ].filter(Boolean);

  return `https://static-maps.yandex.ru/1.x/?lang=pt_BR&ll=${centerLng},${centerLat}&z=13&size=650,320&l=map&pt=${markers.join('~')}`;
}

async function openLiveMap(tracking: TrackingPayload | null) {
  const driverLat = toNumber(tracking?.latestLocation?.latitude);
  const driverLng = toNumber(tracking?.latestLocation?.longitude);
  const customerLat = toNumber(tracking?.customer.latitude);
  const customerLng = toNumber(tracking?.customer.longitude);
  const restaurantLat = toNumber(tracking?.restaurant.latitude);
  const restaurantLng = toNumber(tracking?.restaurant.longitude);
  const lat = driverLat ?? customerLat ?? restaurantLat;
  const lng = driverLng ?? customerLng ?? restaurantLng;

  if (lat === null || lng === null) {
    return;
  }

  await Linking.openURL(`https://www.google.com/maps/search/?api=1&query=${lat},${lng}`);
}

export default function OrderTrackingScreen() {
  const params = useLocalSearchParams<{ orderId?: string }>();
  const orderId = typeof params.orderId === 'string' ? params.orderId : '';
  const { token, initialized, loading: sessionLoading, error: sessionError, bootstrap } = useCustomerSession();
  const { mode } = useCustomerTheme();
  const theme = getCustomerTheme(mode);
  const [tracking, setTracking] = useState<TrackingPayload | null>(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!initialized) {
      void bootstrap();
    }
  }, [bootstrap, initialized]);

  useEffect(() => {
    if (!orderId) {
      setError('Pedido nao informado.');
      setLoading(false);
      return;
    }
    if (!token) {
      return;
    }

    let active = true;
    let socket: Socket | null = null;

    const fetchTracking = async () => {
      const response = await fetch(`${API_URL}/customer/orders/${orderId}/tracking`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      const payload = await response.json().catch(() => null);
      if (!response.ok) {
        throw new Error(payload?.message ?? 'Falha ao carregar rastreio.');
      }
      if (!active) {
        return;
      }
      setTracking(payload);
      setError('');
      setLoading(false);
    };

    const bootstrapTracking = async () => {
      try {
        await fetchTracking();
        socket = io(WS_URL, { transports: ['websocket', 'polling'] });
        socket.on('connect', () => socket?.emit('orders.subscribe', { orderId }));
        ['driver.assigned', 'driver.location.updated', 'eta.updated', 'route.updated', 'order.picked_up', 'order.delivered'].forEach((eventName) => {
          socket?.on(eventName, () => {
            void fetchTracking();
          });
        });
      } catch (loadError) {
        if (active) {
          setError(loadError instanceof Error ? loadError.message : 'Falha ao carregar rastreio.');
          setLoading(false);
        }
      }
    };

    void bootstrapTracking();
    const intervalId = setInterval(() => {
      void fetchTracking().catch(() => undefined);
    }, 15000);

    return () => {
      active = false;
      clearInterval(intervalId);
      socket?.disconnect();
    };
  }, [orderId, token]);

  const activeIndex = tracking ? Math.max(statusFlow.findIndex((status) => status === tracking.trackingStatusLabel), 0) : -1;
  const mapUrl = useMemo(() => buildStaticMapUrl(tracking), [tracking]);

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: theme.background }]}>
      <View style={[styles.screen, { backgroundColor: theme.background }]}>
        <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
          <CustomerPageHeader title="Acompanhar pedido" subtitle="Veja o motoboy, a rota e o tempo estimado." backHref="/orders" backLabel="Pedidos" />

          {sessionLoading || loading ? <View style={[styles.warningCard, { backgroundColor: theme.surface }]}><Text style={[styles.warningText, { color: theme.textMuted }]}>Carregando rastreio...</Text></View> : null}
          {sessionError ? <View style={[styles.warningCard, { backgroundColor: theme.surface }]}><Text style={[styles.warningText, { color: '#B91C1C' }]}>{sessionError}</Text></View> : null}
          {error ? <View style={[styles.warningCard, { backgroundColor: theme.surface }]}><Text style={[styles.warningText, { color: '#B91C1C' }]}>{error}</Text></View> : null}

          <View style={[styles.mapCard, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            {mapUrl ? <Image source={{ uri: mapUrl }} style={styles.mapImage} resizeMode="cover" /> : null}
            <Text style={[styles.mapCopy, { color: theme.text }]}>{tracking?.trackingStatusLabel ?? 'Aguardando atualizacao'}</Text>
            <Text style={[styles.mapMeta, { color: theme.textMuted }]}>
              ETA {tracking?.route?.estimatedDeliveryTime ?? tracking?.route?.estimatedPickupTime ?? tracking?.delivery?.etaMinutes ?? '--'} min
            </Text>
            <TouchableOpacity onPress={() => void openLiveMap(tracking)} style={[styles.mapButton, { backgroundColor: theme.accent }]}>
              <Text style={[styles.mapButtonText, { color: theme.accentText }]}>Abrir no mapa</Text>
            </TouchableOpacity>
          </View>

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Entregador</Text>
            <Text style={[styles.driverName, { color: theme.text }]}>
              {tracking?.driver?.name ?? 'Aguardando definicao'}{tracking?.driver?.rating ? ` • Nota ${tracking.driver.rating}` : ''}
            </Text>
            <Text style={[styles.driverMeta, { color: theme.textMuted }]}>
              {tracking?.driver?.vehicleModel ?? 'Veiculo pendente'}{tracking?.driver?.vehiclePlate ? ` • ${tracking.driver.vehiclePlate}` : ''}
            </Text>
            <Text style={[styles.driverMeta, { color: theme.textSoft }]}>
              Ultimo ping {tracking?.latestLocation?.createdAt ? new Date(tracking.latestLocation.createdAt).toLocaleTimeString('pt-BR') : 'sem localizacao'}
            </Text>
          </View>

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Rota</Text>
            <Text style={[styles.driverMeta, { color: theme.textMuted }]}>Retirada: {tracking?.restaurant.addressLabel ?? tracking?.restaurant.name}</Text>
            <Text style={[styles.driverMeta, { color: theme.textMuted }]}>Entrega: {tracking?.customer.addressLabel ?? 'Endereco do cliente pendente'}</Text>
          </View>

          <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.cardBorder }]}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Status</Text>
            <View style={styles.list}>
              {statusFlow.map((status, index) => (
                <View key={status} style={styles.statusRow}>
                  <View style={[styles.dot, { backgroundColor: activeIndex >= index ? theme.accent : theme.textSoft }]} />
                  <Text style={[styles.statusText, { color: theme.textMuted }]}>{status}</Text>
                </View>
              ))}
            </View>
          </View>
        </ScrollView>
        <CustomerBottomNav />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1 },
  screen: { flex: 1 },
  content: { padding: 16, gap: 12, paddingBottom: 22 },
  warningCard: { borderRadius: 18, padding: 14 },
  warningText: { fontSize: 13, lineHeight: 18, fontWeight: '700' },
  mapCard: { borderRadius: 20, padding: 15, borderWidth: 1 },
  mapImage: { width: '100%', height: 196, borderRadius: 16, backgroundColor: '#111827' },
  mapCopy: { marginTop: 12, fontSize: 15, lineHeight: 20, fontWeight: '900' },
  mapMeta: { marginTop: 6, fontSize: 13, lineHeight: 18, fontWeight: '600' },
  mapButton: { marginTop: 12, borderRadius: 999, paddingHorizontal: 16, paddingVertical: 11, alignItems: 'center' },
  mapButtonText: { fontWeight: '800' },
  card: { borderRadius: 20, padding: 16, borderWidth: 1 },
  sectionTitle: { fontSize: 18, fontWeight: '900' },
  list: { marginTop: 12, gap: 9 },
  statusRow: { flexDirection: 'row', alignItems: 'center', gap: 10 },
  dot: { width: 10, height: 10, borderRadius: 999 },
  statusText: { fontSize: 13, fontWeight: '700' },
  driverName: { marginTop: 8, fontSize: 16, fontWeight: '900' },
  driverMeta: { marginTop: 6, fontSize: 13, fontWeight: '600' },
});
