import type { FlightPoint } from '../types';

export const calculateDistance = (
  point1: FlightPoint,
  point2: FlightPoint,
  aircraftType: string,
  initialAltitude: number,
  downang: number,
  upang: number,
): number => {
  if (!point1?.position || !point2?.position) {
    console.error('Invalid points provided:', { point1, point2 });
    return 0;
  }

  const R = 6371;
  const { lat: lat1, lng: lon1 } = point1.position;
  const { lat: lat2, lng: lon2 } = point2.position;
  const alt1 = point1.altitude || 0;
  const alt2 = point2.altitude || 0;

  const toRad = (value: number) => (value * Math.PI) / 180;
  const dLat = toRad(lat2 - lat1);
  const dLon = toRad(lon2 - lon1);

  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(toRad(lat1)) *
    Math.cos(toRad(lat2)) *
    Math.sin(dLon / 2) *
    Math.sin(dLon / 2);

  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const horizontalDistance = R * c;

  const initialAltitudeKm = initialAltitude / 1000;
  const altitude1Km = alt1 / 1000;
  const altitude2Km = alt2 / 1000;

  const descentAngleRad = toRad(downang || 0.01);
  const ascentAngleRad = toRad(upang || 0.01);

  if (aircraftType === 'Plane') {
    const ascentDistanceInclined = Math.max(0, (initialAltitudeKm - altitude1Km) / Math.sin(ascentAngleRad));
    const descentDistanceInclined = Math.max(0, (initialAltitudeKm - altitude2Km) / Math.sin(descentAngleRad));

    const horizontalAscentProjection = Math.max(0, ascentDistanceInclined * Math.cos(ascentAngleRad));
    const horizontalDescentProjection = Math.max(0, descentDistanceInclined * Math.cos(descentAngleRad));

    const adjustedHorizontalDistance = horizontalDistance - (horizontalDescentProjection + horizontalAscentProjection);
    const totalDistance = adjustedHorizontalDistance + Math.max(0, descentDistanceInclined) + Math.max(0, ascentDistanceInclined);
    return totalDistance;
  } else if (aircraftType === 'VTOL') {
    const ascentDistanceVertical = Math.abs(initialAltitudeKm - altitude1Km);
    const horizontalFlightDistance = horizontalDistance;
    const descentDistanceVertical = Math.abs(initialAltitudeKm - altitude2Km);
    const totalDistance = ascentDistanceVertical + horizontalFlightDistance + descentDistanceVertical;
    return totalDistance;
  }

  return 0;
};
