import { useState } from 'react';
import * as Location from 'expo-location';
import { useWorkoutStore } from '@/store/useWorkoutStore';

const LOCATION_TASK_NAME = 'background-location-task';

export function useBackgroundGPS() {
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const isTracking = useWorkoutStore((state) => state.isTracking);

  const startTracking = async (type: 'RUNNING' | 'CYCLING' | 'WALKING' = 'RUNNING') => {
    try {
      const { status: foreground } = await Location.requestForegroundPermissionsAsync();
      const { status: background } = await Location.requestBackgroundPermissionsAsync();

      if (foreground !== 'granted' || background !== 'granted') {
        setErrorMsg('Quyền định vị Always (Luôn cho phép) bị từ chối.');
        return false;
      }

      useWorkoutStore.getState().startWorkout(type);
      
      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...",
          notificationColor: "#10b981"
        }
      });
      return true;
    } catch (error: any) {
      setErrorMsg(error.message || 'Lỗi khởi động GPS.');
      return false;
    }
  };

  const stopTracking = async () => {
    try {
      const isTaskRunning = await Location.hasStartedLocationUpdatesAsync(LOCATION_TASK_NAME);
      if (isTaskRunning) {
        await Location.stopLocationUpdatesAsync(LOCATION_TASK_NAME);
      }
      const workoutId = await useWorkoutStore.getState().stopWorkout();
      return workoutId;
    } catch (error: any) {
      setErrorMsg(error.message || 'Lỗi dừng GPS.');
      return null;
    }
  };

  return {
    isTracking,
    errorMsg,
    startTracking,
    stopTracking
  };
}
