import { LayersControl, MapContainer, TileLayer, useMapEvents, ZoomControl } from 'react-leaflet';
import '@mantine/core/styles.css';
import 'leaflet/dist/leaflet.css';
import './App.css';
import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
import markerIcon from 'leaflet/dist/images/marker-icon.png';
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
import L from 'leaflet';
import { Header } from '@components/Header';
import AirportLayer from '@components/AirportLayer.tsx';
import { useEffect, useState } from 'react';
import { Airport } from '@lib/airport.types.ts';
import Index from '@components/AirportDrawer';
import { getWeatherMapUrl } from '@lib/rainViewer.ts';
import Cookies from 'js-cookie';
// import { createRoot } from 'react-dom/client';
import { UnstyledButton } from '@mantine/core';
import { IconBuildingAirport, IconRadar } from '@tabler/icons-react';
// Fix Leaflet's default icon path issues with Webpack
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
  iconRetinaUrl: markerIcon2x,
  iconUrl: markerIcon,
  shadowUrl: markerShadow
});

export interface LayerInfo {
  url: string;
  name: string;
  markerOutline: string;
}

const layerMap: LayerInfo[] = [
  { url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', name: 'Open Street Map', markerOutline: 'black' },
  { url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', name: 'Carto Light', markerOutline: 'black' },
  { url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', name: 'Carto Dark', markerOutline: 'white' }
];
// const dark1Url = 'https://maps.rainviewer.com/data/v3/5/10/11.pbf';
// const dark2Url = 'https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer/tile/2/0/3.pbf';
const defaultZoom = 6;
const defaultCenter: L.LatLngExpression = [38.944444, -77.455833];

// function CustomControl({ toggleRadar, showRadar, toggleShowNoMetar, showNoMetar }) {
//   const map = useMap();
//
//   useEffect(() => {
//     const CustomLeafletControl = L.Control.extend({
//       options: { position: 'bottomright' },
//       onAdd: function () {
//         // Create a container for the control
//         const container = L.DomUtil.create('div', 'leaflet-bar custom-control');
//
//         // Radar button
//         const radarButton = L.DomUtil.create('button', 'control-button radar-button', container);
//         // radarButton.innerHTML = 'Radar';
//         // if (showRadar) {
//         //   radarButton.classList.add('active');
//         // }
//         const radarRoot = createRoot(radarButton);
//         radarRoot.render(
//           <IconRadar
//             style={{ width: '24px', height: '24px', color: showRadar ? 'blue' : 'black' }}
//           />
//         );
//         // Prevent click events from propagating to the map
//         L.DomEvent.disableClickPropagation(radarButton);
//         L.DomEvent.on(radarButton, 'click', (e) => {
//           L.DomEvent.stopPropagation(e);
//           toggleRadar();
//         });
//
//         // Airports (no METARs) button
//         const airportButton = L.DomUtil.create('button', 'control-button', container);
//         airportButton.innerHTML = 'Airports';
//         if (showNoMetar) {
//           airportButton.classList.add('active');
//         }
//         L.DomEvent.disableClickPropagation(airportButton);
//         L.DomEvent.on(airportButton, 'click', (e) => {
//           L.DomEvent.stopPropagation(e);
//           toggleShowNoMetar();
//         });
//
//         return container;
//       }
//     });
//
//     const customControl = new CustomLeafletControl();
//     customControl.addTo(map);
//
//     // Remove control on cleanup
//     return () => {
//       customControl.remove();
//     };
//   }, [map, toggleRadar, toggleShowNoMetar, showRadar, showNoMetar]);
//
//   return null;
// }

function App() {
  const [airport, setAirport] = useState<Airport | null>(null);
  const [rainViewerUrl, setRainViewerUrl] = useState<string | null>(null);
  const initialRadarValue = Cookies.get('showRadar') === 'true';
  const [showRadar, setShowRadar] = useState<boolean>(initialRadarValue);
  const initialShowNoMetarValue = Cookies.get('showNoMetar') === 'true';
  const [showNoMetar, setShowNoMetar] = useState<boolean>(initialShowNoMetarValue);
  const [selectedLayerIndex, setSelectedLayerIndex] = useState<string>(Cookies.get('selectedLayer') || '0');
  const [selectedLayer, setSelectedLayer] = useState<LayerInfo>(layerMap[Number(selectedLayerIndex)]);

  useEffect(() => {
    if (showRadar) {
      getWeatherMapUrl().then((url) => {
        setRainViewerUrl(url);
      });
    }
  }, [showRadar]);

  function toggleRadar() {
    setShowRadar((prev) => {
      const newValue = !prev;
      Cookies.set('showRadar', newValue.toString(), { expires: 7 });
      return newValue;
    });
  }

  function toggleShowNoMetar() {
    setShowNoMetar((prev) => {
      const newValue = !prev;
      Cookies.set('showNoMetar', newValue.toString(), { expires: 7 });
      return newValue;
    });
  }

  function BaseLayerChangeHandler() {
    useMapEvents({
      baselayerchange: (e) => {
        const index = layerMap.findIndex((layer) => layer.name === e.name);
        setSelectedLayerIndex(`${index}`);
        Cookies.set('selectedLayer', `${index}`, { expires: 7 });
        setSelectedLayer(layerMap[index]);
      }
    });
    return null;
  }

  return (
    <div className='App'>
      <Header />
      <div className='map-wrapper'>
        <Index airport={airport} setAirport={setAirport} />
        <MapContainer
          className='leaflet-container'
          attributionControl={false}
          center={defaultCenter}
          zoom={defaultZoom}
          minZoom={3}
          maxZoom={19}
          maxBounds={[
            [-85.06, -181],
            [85.06, 181]
          ]}
          scrollWheelZoom={true}
          zoomControl={false}
        >
          <LayersControl>
            {layerMap.map((layer, index) => (
              <LayersControl.BaseLayer key={index} checked={selectedLayerIndex === `${index}`} name={layer.name}>
                <TileLayer url={layer.url} />
              </LayersControl.BaseLayer>
            ))}
          </LayersControl>
          {rainViewerUrl && showRadar && <TileLayer url={rainViewerUrl} opacity={0.5} zIndex={10} />}
          <ZoomControl position={'bottomright'} />
          <AirportLayer setAirport={setAirport} selectedLayer={selectedLayer} showNoMetar={showNoMetar} />
          <BaseLayerChangeHandler />
          {/*<CustomControl*/}
          {/*  toggleRadar={toggleRadar}*/}
          {/*  showRadar={showRadar}*/}
          {/*  toggleShowNoMetar={toggleShowNoMetar}*/}
          {/*  showNoMetar={showNoMetar}*/}
          {/*/>*/}
        </MapContainer>
        <UnstyledButton
          onClick={toggleShowNoMetar}
          style={{ bottom: '120px' }}
          className={`map-button ${showNoMetar ? 'active' : ''}`}
        >
          <IconBuildingAirport />
        </UnstyledButton>
        <UnstyledButton
          onClick={toggleRadar}
          style={{ bottom: '80px' }}
          className={`map-button ${showRadar ? 'active' : ''}`}
        >
          <IconRadar />
        </UnstyledButton>
      </div>
    </div>
  );
}

export default App;
