import { useState } from 'react';
import { useLanguage } from './LanguageContext';
import Button from '@mui/material/Button';
import { FormControl, TextField, InputLabel } from '@mui/material';
import { DragDropContext, type DropResult } from '@hello-pangea/dnd';
import PointsList from './PointsList';
import AltitudeChart from './AltitudeChart';
import TotalDistance from './TotalDistance';
import LanguageSwitcher from './LanguageSwitcher';
import { translations } from '../constants/translations';
import './LeftBoard.css';
import { actionModes } from '../constants/actionModes';
import { DashedAreaIcon, HideSidebarIcon, ShowSidebarIcon } from '../icons/SidebarIcons';
import { FaLocationDot } from 'react-icons/fa6';
import { geocodeAddress } from '../services/GeocodeService';
import type { FlightPoint, CalculatedPointInfo, AircraftParams, LatLngPosition } from '../types';

interface LeftBoardProps {
  points: FlightPoint[];
  setPoints: React.Dispatch<React.SetStateAction<FlightPoint[]>>;
  calculatedPointInfo: CalculatedPointInfo[];
  setCalculatedPointInfo: React.Dispatch<React.SetStateAction<CalculatedPointInfo[]>>;
  aircraft: AircraftParams | null;
  initialAltitude: number;
  setInitialAltitude: (value: number) => void;
  currentAltitude: number;
  actionMode: string;
  setActionMode: (mode: string) => void;
  setRectangleColor: (color: string) => void;
  editAsJson: () => void;
  exportMap: () => void;
  updatePosition: (pos: LatLngPosition) => void;
  currentPosition: LatLngPosition;
}

export default function LeftBoard({
  points,
  setPoints,
  calculatedPointInfo,
  setCalculatedPointInfo,
  aircraft,
  initialAltitude,
  setInitialAltitude,
  currentAltitude,
  actionMode,
  setActionMode,
  setRectangleColor,
  editAsJson,
  exportMap,
  updatePosition,
  currentPosition,
}: LeftBoardProps) {
  const { targetLanguage } = useLanguage();
  const t = translations[targetLanguage];
  const [isShowed, setIsShowed] = useState(true);
  const [locationInput, setLocationInput] = useState('');

  const changeShowing = () => {
    setIsShowed(!isShowed);
  };

  const removePoint = (id: string) => {
    const index = points.findIndex((point) => point.id === id);
    setCalculatedPointInfo(calculatedPointInfo.filter((_pi, i) => i !== index));
    setPoints(points.filter(point => point.id !== id));
  };

  const onDragEnd = (result: DropResult) => {
    if (!result.destination) return;
    const items = Array.from(points);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);
    setPoints(items);
  };

  const handleChangeActionMode = (mode: string) => {
    setActionMode(mode);
    mode === actionModes.workArea ? setRectangleColor('green')
      : setRectangleColor('red');
  };

  const handleLocationSearch = async (e: React.KeyboardEvent<HTMLDivElement>) => {
    if (e.key === 'Enter') {
      const coords = parseCoordinates(locationInput);
      if (coords) {
        updatePosition({ lat: coords.lat, lng: coords.lng });
      } else {
        const geocodedCoords = await geocodeAddress(locationInput);
        if (geocodedCoords) {
          updatePosition({ lat: geocodedCoords.lat, lng: geocodedCoords.lng });
        }
      }
    }
  };

  const parseCoordinates = (input: string): LatLngPosition | null => {
    const cleaned = input.trim().replace(/[°NSEW]/gi, '');
    const parts = cleaned.split(/[,\s]+/).filter(p => p);

    if (parts.length >= 2) {
      const lat = parseFloat(parts[0]);
      const lng = parseFloat(parts[1]);

      if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
        return { lat, lng };
      }
    }
    return null;
  };

  return (
    <>
      {isShowed ?
        <div className={'left-board'}>
          <div className={'top-menu'}>
            <div className='selectors'>
              <LanguageSwitcher />

              <div className='editor-container'>
                <InputLabel id='altitude-label'>{t.initialAltitude}</InputLabel>
                <FormControl fullWidth margin="none">
                  <TextField
                    type="number"
                    value={initialAltitude}
                    onChange={(e) => setInitialAltitude(Number(e.target.value))}
                  />
                </FormControl>
              </div>
            </div>

            <Button className='arrow-btn' onClick={changeShowing}>
              <HideSidebarIcon />
            </Button>
          </div>

          <div className='actions-block'>
            <div className='action-buttons-row'>
              <Button className={actionMode !== actionModes.points ? 'btn action-btn' : 'btn active-mode-btn'}
                variant="contained" onClick={() => handleChangeActionMode(actionModes.points)}>
                <FaLocationDot className='action-btn-icon' />
                {t.addPoints}
              </Button>
              <Button className={actionMode !== actionModes.workArea ? 'btn action-btn' : 'btn active-mode-btn'}
                variant="contained" onClick={() => handleChangeActionMode(actionModes.workArea)}>
                <DashedAreaIcon className='action-btn-icon' color='green' />
                {t.workArea}
              </Button>
              <Button className={actionMode !== actionModes.prohibitedArea ? 'btn action-btn' : 'btn active-mode-btn'}
                variant="contained" onClick={() => handleChangeActionMode(actionModes.prohibitedArea)}>
                <DashedAreaIcon className='action-btn-icon' color='red' />
                {t.prohibitedArea}
              </Button>
            </div>

            <div className='location-search'>
              <InputLabel id='location-label'>{t.location}:</InputLabel>
              <FormControl fullWidth margin="none">
                <TextField
                  placeholder="47.242, 35.024"
                  value={locationInput}
                  onChange={(e) => setLocationInput(e.target.value)}
                  onKeyDown={handleLocationSearch}
                />
              </FormControl>
              <div className='current-location-label'>
                {t.currentLocation}: {currentPosition?.lat.toFixed(6)}, {currentPosition?.lng.toFixed(6)}
              </div>
            </div>
          </div>

          <DragDropContext onDragEnd={onDragEnd}>
            <PointsList
              points={points}
              setPoints={setPoints}
              calculatedPointInfo={calculatedPointInfo}
              setCalculatedPointInfo={setCalculatedPointInfo}
              removePoint={removePoint}
              aircraft={aircraft}
              initialAltitude={currentAltitude}
            />
          </DragDropContext>

          <TotalDistance points={points} calculatedPointInfo={calculatedPointInfo} aircraft={aircraft} initialAltitude={currentAltitude} />

          <AltitudeChart points={points} />

          <div className='operations-section'>
            <InputLabel id='operations-label'>{t.operations}:</InputLabel>
          </div>

          <div className='section-buttons-row'>
            <Button className='btn section-btn' size="small"
              variant="contained" onClick={editAsJson}>
              {t.editAsJson}
            </Button>
            <Button className='btn section-btn' size="small"
              variant="contained" onClick={exportMap}>
              {t.exportMapData}
            </Button>
          </div>
        </div>
        :
        <div className='toolbar'>
          <Button className='toolbar-btn' onClick={changeShowing}>
            <ShowSidebarIcon />
          </Button>
          <Button className={actionMode !== actionModes.points ? 'toolbar-btn' : 'active-toolbar-btn'} id='point-btn'
            onClick={() => handleChangeActionMode(actionModes.points)}>
            <FaLocationDot size={'70%'} color='red' />
          </Button>
          <Button className={actionMode !== actionModes.workArea ? 'toolbar-btn' : 'active-toolbar-btn'}
            onClick={() => handleChangeActionMode(actionModes.workArea)}>
            <DashedAreaIcon color='green' />
          </Button>
          <Button className={actionMode !== actionModes.prohibitedArea ? 'toolbar-btn' : 'active-toolbar-btn'}
            onClick={() => handleChangeActionMode(actionModes.prohibitedArea)}>
            <DashedAreaIcon color='red' />
          </Button>
        </div>
      }
    </>
  );
}
