import { useLanguage } from './LanguageContext';
import { calculateDistance } from '../services/calculateDistance';
import { translations } from '../constants/translations';
import './TotalDistance.css';
import type { FlightPoint, CalculatedPointInfo, AircraftParams, TranslationStrings } from '../types';

interface BatteryStatus {
  color: string;
  message: string;
}

const getBatteryStatus = (batteryPercent: number, t: TranslationStrings): BatteryStatus => {
  if (batteryPercent > 12) {
    return { color: 'green', message: t.flightStatus.good };
  } else if (batteryPercent > 5) {
    return { color: 'yellow', message: t.flightStatus.caution };
  } else {
    return { color: 'red', message: t.flightStatus.low };
  }
};

interface TotalDistanceProps {
  points: FlightPoint[];
  calculatedPointInfo: CalculatedPointInfo[];
  aircraft: AircraftParams | null;
  initialAltitude: number;
}

const TotalDistance = ({ points, calculatedPointInfo, aircraft, initialAltitude }: TotalDistanceProps) => {
  const { targetLanguage } = useLanguage();
  const t = translations[targetLanguage];

  const returnPoint = points[points.length - 1];

  if (!aircraft || !points || (returnPoint ? points.length < 1 : points.length < 2)) {
    return null;
  }

  const totalDistance = points.reduce((acc, point, index) => {
    if (index === 0) return acc;

    const prevPoint = points[index - 1];

    return acc + calculateDistance(
      prevPoint,
      point,
      aircraft.type,
      initialAltitude,
      aircraft.downang,
      aircraft.upang,
    );
  }, 0);

  const formattedReturnPoint = returnPoint?.position
    ? { position: { lat: returnPoint.position.lat, lng: returnPoint.position.lng } } as FlightPoint
    : null;

  const distanceToReturnPoint = formattedReturnPoint
    ? calculateDistance(points[points.length - 1], formattedReturnPoint, aircraft.type, initialAltitude, aircraft.downang, aircraft.upang)
    : 0;

  const totalDistanceWithReturn = totalDistance + distanceToReturnPoint;

  if (isNaN(totalDistanceWithReturn) || totalDistanceWithReturn <= 0) {
    console.error('Invalid total distance:', totalDistanceWithReturn);
    return <div>{t.error}</div>;
  }

  const lastPointInfo = calculatedPointInfo?.[calculatedPointInfo.length - 1];
  if (!lastPointInfo || lastPointInfo.bat === undefined) {
    return null;
  }

  const status = getBatteryStatus(lastPointInfo.bat, t);

  const time = totalDistanceWithReturn / aircraft.speed;
  const hours = Math.floor(time);
  const minutes = Math.floor((time - hours) * 60);

  return (
    <div className='distance-container' style={{ display: 'flex', flexDirection: 'row', gap: '10px' }}>
      <p className='info-block'>{totalDistanceWithReturn.toFixed(2)}{t.km} {t.calc}</p>
      {hours >= 1 &&
        <p className='info-block'>{hours}{t.hour} </p>
      }
      <p className='info-block'>{minutes}{t.minutes} </p>
      <p className='info-block' style={{ color: status.color }}>{status.message}</p>
    </div>
  );
};

export default TotalDistance;
