import React, { useEffect, useRef, useState } from 'react';
import { View, Text, TouchableOpacity, Alert, SafeAreaView } from 'react-native';
import MapView, { Polyline, PROVIDER_GOOGLE } from 'react-native-maps';
import { useWorkoutStore } from '@/store/useWorkoutStore';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import { Ionicons } from '@expo/vector-icons';
import { fetchCurrentWeather } from '@/services/weatherService';

const LOCATION_TASK_NAME = 'background-location-task';

export default function RecordScreen({ navigation }: any) {
  const {
    isTracking,
    distance,
    duration,
    currentSpeed,
    currentHeartRate,
    caloriesBurned,
    startWorkout,
    stopWorkout,
    routePoints
  } = useWorkoutStore();

  const [weather, setWeather] = useState({ temp: '--', icon: 'cloud-outline' });
  const mapRef = useRef<MapView | null>(null);

  // 1. Lấy dữ liệu thời tiết thực tế từ Weather Service
  useEffect(() => {
    const getWeather = async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') return;
      const loc = await Location.getCurrentPositionAsync({});
      const wData = await fetchCurrentWeather(loc.coords.latitude, loc.coords.longitude);
      setWeather(wData);
    };
    getWeather();
  }, []);

  // 2. Chạy đồng hồ đếm thời gian tập
  useEffect(() => {
    let interval: any = null;
    if (isTracking) {
      interval = setInterval(() => {
        useWorkoutStore.getState().updateTimer();
      }, 1000);
    } else {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isTracking]);

  // 3. Khởi tạo tác vụ ghi GPS chạy ngầm
  const handleToggleTracking = async () => {
    if (!isTracking) {
      const { status: foreground } = await Location.requestForegroundPermissionsAsync();
      const { status: background } = await Location.requestBackgroundPermissionsAsync();

      if (foreground !== 'granted' || background !== 'granted') {
        Alert.alert('Quyền Định Vị', 'Bạn cần cấp quyền định vị Always (Luôn cho phép) để ứng dụng chạy ngầm không bị mất log.');
        return;
      }

      startWorkout('RUNNING');
      
      await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
        accuracy: Location.Accuracy.BestForNavigation,
        timeInterval: 5000,
        distanceInterval: 5,
        foregroundService: {
          notificationTitle: "GeoSport Log đang hoạt động",
          notificationBody: "Đang ghi lại lộ trình di chuyển của bạn...",
          notificationColor: "#10b981"
        }
      });
    } else {
      await Location.stopLocationUpdatesAsync(LOCATION_TASK_NAME);
      const savedId = await stopWorkout();
      if (savedId) {
        Alert.alert('Thành Công', 'Đã lưu lại hành trình của bạn vào Nhật ký cục bộ.');
      }
    }
  };

  const formatTime = (secs: number) => {
    const m = Math.floor(secs / 60).toString().padStart(2, '0');
    const s = (secs % 60).toString().padStart(2, '0');
    return `${m}:${s}`;
  };

  return (
    <View className="flex-1 bg-[#050811]">
      <MapView
        ref={mapRef}
        provider={PROVIDER_GOOGLE}
        customMapStyle={darkMapStyle}
        className="flex-1"
        initialRegion={{
          latitude: 16.0684,
          longitude: 108.2460,
          latitudeDelta: 0.01,
          longitudeDelta: 0.01,
        }}
        showsUserLocation
        followsUserLocation
      >
        {routePoints.length > 0 && (
          <Polyline
            coordinates={routePoints.map(p => ({ latitude: p.lat, longitude: p.lng }))}
            strokeColor="#10b981"
            strokeWidth={5}
          />
        )}
      </MapView>

      {/* HEADER OVERLAY HUD */}
      <SafeAreaView className="absolute top-4 left-4 right-4 flex-row justify-between items-center z-10">
        <View className="bg-slate-950/90 border border-slate-800/80 rounded-2xl px-3 py-2 flex-row items-center gap-2">
          <Ionicons name={weather.icon as any} size={18} color="#f59e0b" />
          <Text className="text-xs font-bold text-white">{weather.temp}</Text>
        </View>

        <View className="bg-slate-950/90 border border-slate-800/80 px-4 py-2 rounded-2xl">
          <Text className="font-extrabold text-xs text-white uppercase">
            GEOSPORT <Text className="text-emerald-400">LOG</Text>
          </Text>
        </View>

        <TouchableOpacity 
          onPress={() => navigation?.openDrawer?.()}
          className="w-10 h-10 rounded-2xl bg-slate-950/90 border border-slate-800 flex items-center justify-center text-white"
        >
          <Ionicons name="menu-outline" size={20} color="white" />
        </TouchableOpacity>
      </SafeAreaView>

      {/* LOWER STATUS AND CONTROL HUD */}
      <View className="absolute bottom-6 left-4 right-4 z-10 gap-3">
        <View className="bg-slate-950/90 border border-slate-800/80 rounded-3xl p-4 shadow-2xl">
          <View className="flex-row justify-between mb-4">
            <View className="align-center flex-1">
              <Text className="text-[9px] font-extrabold text-slate-500 uppercase">Cự ly</Text>
              <Text className="text-xl font-black text-white">{distance.toFixed(2)} <Text className="text-xs font-normal">km</Text></Text>
            </View>
            <View className="align-center flex-1 border-l border-slate-800/60 pl-3">
              <Text className="text-[9px] font-extrabold text-slate-500 uppercase">Thời gian</Text>
              <Text className="text-xl font-black text-white">{formatTime(duration)}</Text>
            </View>
            <View className="align-center flex-1 border-l border-slate-800/60 pl-3">
              <Text className="text-[9px] font-extrabold text-slate-500 uppercase">Tốc độ</Text>
              <Text className="text-xl font-black text-emerald-400">{currentSpeed.toFixed(1)} <Text className="text-xs font-normal">km/h</Text></Text>
            </View>
          </View>

          <View className="flex-row justify-between pt-3 border-t border-slate-800/40">
            <View className="flex-row items-center gap-1.5">
              <Ionicons name="heart-sharp" size={16} color="#ef4444" className="animate-pulse" />
              <Text className="text-xs font-bold text-slate-300">{currentHeartRate} BPM</Text>
            </View>
            <View className="flex-row items-center gap-1.5">
              <Ionicons name="flame-sharp" size={16} color="#f97316" />
              <Text className="text-xs font-bold text-slate-300">{Math.round(caloriesBurned)} Kcal</Text>
            </View>
          </View>
        </View>

        <TouchableOpacity
          onPress={handleToggleTracking}
          className={`w-full py-4 rounded-2xl flex-row items-center justify-center gap-2 shadow-lg ${
            isTracking ? 'bg-rose-600' : 'bg-emerald-500'
          }`}
        >
          <Ionicons name={isTracking ? 'stop-sharp' : 'play-sharp'} size={18} color={isTracking ? 'white' : '#090d16'} />
          <Text className={`font-extrabold text-xs tracking-widest ${isTracking ? 'text-white' : 'text-slate-950'}`}>
            {isTracking ? 'KẾT THÚC & LƯU CHUYẾN ĐI' : 'BẮT ĐẦU GHI HÀNH TRÌNH'}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

// Only define task once, check if task is registered to avoid development re-register errors
if (!TaskManager.isTaskDefined(LOCATION_TASK_NAME)) {
  TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }: any) => {
    if (error) return;
    if (data) {
      const { locations } = data;
      const location = locations[0];
      
      const speedKmh = location.coords.speed ? location.coords.speed * 3.6 : 10;
      const simulatedHR = Math.round(110 + (speedKmh * 3.5) + (Math.random() * 8 - 4));

      useWorkoutStore.getState().addTrackpoint({
        lat: location.coords.latitude,
        lng: location.coords.longitude,
        speed: parseFloat(speedKmh.toFixed(1)),
        hr: Math.min(Math.max(simulatedHR, 70), 185),
        timestamp: location.timestamp
      });
    }
  });
}

const darkMapStyle = [
  { "elementType": "geometry", "stylers": [{ "color": "#050811" }] },
  { "elementType": "labels.text.fill", "stylers": [{ "color": "#747985" }] },
  { "elementType": "labels.text.stroke", "stylers": [{ "color": "#050811" }] },
  { "featureType": "road", "elementType": "geometry", "stylers": [{ "color": "#0d1527" }] },
  { "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#02040a" }] }
];
