/**
 * Showing cart — multi-showing route with GPS optimization.
 * SmartRoute replacement: optimizes order, shows drive times, launches navigation.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
} from 'react-native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { ShowingsStackParamList } from '../../navigation/stacks/ShowingsStack';
import { useTheme } from '../../themes/ThemeProvider';
import { getTodayShowings, Showing } from '../../services/api';
import {
  getCurrentLocation,
  optimizeShowingRoute,
  openMultiStopNavigation,
  getRouteStats,
  ShowingStop,
  Coordinates,
} from '../../services/location';

type Props = NativeStackScreenProps<ShowingsStackParamList, 'ShowingCart'>;

export default function ShowingCart({ navigation }: Props) {
  const { theme } = useTheme();
  const [showings, setShowings] = useState<Showing[]>([]);
  const [optimizedStops, setOptimizedStops] = useState<ShowingStop[]>([]);
  const [currentLocation, setCurrentLocation] = useState<Coordinates | null>(null);
  const [routeStats, setRouteStats] = useState<{
    totalMiles: number;
    totalMinutes: number;
    legs: { from: string; to: string; miles: number; minutes: number }[];
  } | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    const [showingsRes, location] = await Promise.all([
      getTodayShowings(),
      getCurrentLocation(),
    ]);

    if (location) {
      setCurrentLocation(location);
    }

    if (showingsRes.success && showingsRes.value?.data) {
      const confirmed = (showingsRes.value?.data ?? showingsRes.data ?? []) as Showing[];
      setShowings(confirmed);

      // Build stops for route optimization
      const stops: ShowingStop[] = confirmed
        .filter((s: Showing) => s.latitude && s.longitude && s.status !== 'cancelled')
        .map((s: Showing) => ({
          id: s.id,
          address: `Property #${s.property_id}`,
          latitude: s.latitude!,
          longitude: s.longitude!,
          showing_time: s.showing_time,
          instructions: s.instructions,
          lockbox_code: s.lockbox_code,
        }));

      if (location && stops.length > 0) {
        const optimized = optimizeShowingRoute(location, stops);
        setOptimizedStops(optimized);
        setRouteStats(getRouteStats(location, optimized));
      } else {
        setOptimizedStops(stops);
      }
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const startNavigation = () => {
    if (optimizedStops.length === 0) {
      Alert.alert('No Stops', 'Add confirmed showings with locations to start a tour.');
      return;
    }
    openMultiStopNavigation(optimizedStops);
  };

  const formatTime = (time: string): string => {
    try {
      const [hours, minutes] = time.split(':').map(Number);
      const ampm = hours >= 12 ? 'PM' : 'AM';
      return `${hours % 12 || 12}:${minutes.toString().padStart(2, '0')} ${ampm}`;
    } catch {
      return time;
    }
  };

  return (
    <ScrollView style={[styles.container, { backgroundColor: theme.colors.background }]}>
      {/* Route Summary */}
      {routeStats && (
        <View style={[styles.summary, theme.shadow.md, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.summaryTitle, { color: theme.colors.text }]}>Route Summary</Text>
          <View style={styles.statRow}>
            <View style={styles.stat}>
              <Text style={[styles.statValue, { color: theme.colors.primary }]}>
                {optimizedStops.length}
              </Text>
              <Text style={[styles.statLabel, { color: theme.colors.textSecondary }]}>Stops</Text>
            </View>
            <View style={styles.stat}>
              <Text style={[styles.statValue, { color: theme.colors.primary }]}>
                {routeStats.totalMiles.toFixed(1)}
              </Text>
              <Text style={[styles.statLabel, { color: theme.colors.textSecondary }]}>Miles</Text>
            </View>
            <View style={styles.stat}>
              <Text style={[styles.statValue, { color: theme.colors.primary }]}>
                {routeStats.totalMinutes}
              </Text>
              <Text style={[styles.statLabel, { color: theme.colors.textSecondary }]}>Min Drive</Text>
            </View>
          </View>
          <TouchableOpacity
            style={[styles.navBtn, { backgroundColor: theme.colors.success }]}
            onPress={startNavigation}
          >
            <Text style={styles.navBtnText}>Start Navigation</Text>
          </TouchableOpacity>
        </View>
      )}

      {/* Optimized Stop List */}
      <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>
        {currentLocation ? 'Optimized Route' : 'Today\'s Stops'}
      </Text>

      {loading && (
        <Text style={[styles.loadingText, { color: theme.colors.textSecondary }]}>
          Calculating optimal route...
        </Text>
      )}

      {optimizedStops.map((stop, index) => {
        const leg = routeStats?.legs[index];
        return (
          <View key={stop.id}>
            {leg && index > 0 && (
              <View style={styles.legInfo}>
                <View style={[styles.legLine, { backgroundColor: theme.colors.border }]} />
                <Text style={[styles.legText, { color: theme.colors.textSecondary }]}>
                  {leg.miles.toFixed(1)} mi • ~{leg.minutes} min drive
                </Text>
                <View style={[styles.legLine, { backgroundColor: theme.colors.border }]} />
              </View>
            )}
            <TouchableOpacity
              style={[styles.stopCard, theme.shadow.sm, { backgroundColor: theme.colors.card }]}
              onPress={() => navigation.navigate('ShowingDetail', { id: stop.id })}
            >
              <View style={[styles.stopNumber, { backgroundColor: theme.colors.primary }]}>
                <Text style={styles.stopNumberText}>{index + 1}</Text>
              </View>
              <View style={styles.stopInfo}>
                <Text style={[styles.stopAddress, { color: theme.colors.text }]}>
                  {stop.address}
                </Text>
                <Text style={[styles.stopTime, { color: theme.colors.textSecondary }]}>
                  {formatTime(stop.showing_time)}
                </Text>
                {stop.lockbox_code && (
                  <Text style={[styles.stopLockbox, { color: theme.colors.accent }]}>
                    Lockbox: {stop.lockbox_code}
                  </Text>
                )}
              </View>
            </TouchableOpacity>
          </View>
        );
      })}

      {optimizedStops.length === 0 && !loading && (
        <View style={styles.empty}>
          <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>
            No confirmed showings with locations for today.
          </Text>
        </View>
      )}

      <View style={styles.bottomPad} />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  summary: {
    margin: 16,
    borderRadius: 14,
    padding: 20,
  },
  summaryTitle: { fontSize: 18, fontWeight: '700', marginBottom: 14 },
  statRow: { flexDirection: 'row', justifyContent: 'space-around', marginBottom: 16 },
  stat: { alignItems: 'center' },
  statValue: { fontSize: 28, fontWeight: '800' },
  statLabel: { fontSize: 12, marginTop: 2 },
  navBtn: {
    height: 48,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
  navBtnText: { color: '#FFF', fontSize: 17, fontWeight: '700' },
  sectionTitle: {
    fontSize: 17,
    fontWeight: '700',
    paddingHorizontal: 16,
    paddingTop: 8,
    paddingBottom: 10,
  },
  loadingText: { paddingHorizontal: 16, fontSize: 14 },
  legInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 6,
    gap: 8,
  },
  legLine: { flex: 1, height: 1 },
  legText: { fontSize: 12, fontWeight: '500' },
  stopCard: {
    flexDirection: 'row',
    marginHorizontal: 16,
    marginVertical: 4,
    borderRadius: 10,
    padding: 14,
    alignItems: 'center',
  },
  stopNumber: {
    width: 32,
    height: 32,
    borderRadius: 16,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  stopNumberText: { color: '#FFF', fontWeight: '800', fontSize: 14 },
  stopInfo: { flex: 1 },
  stopAddress: { fontSize: 15, fontWeight: '600' },
  stopTime: { fontSize: 13, marginTop: 2 },
  stopLockbox: { fontSize: 12, fontWeight: '600', marginTop: 4 },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 15, textAlign: 'center' },
  bottomPad: { height: 40 },
});
