import { useRef, useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';

import dynamic from 'next/dynamic';

import { useTranslation } from 'react-i18next';

import MapView from '@arcgis/core/views/MapView';
import WebMap from '@arcgis/core/WebMap';
import esriConfig from '@arcgis/core/config';
import ScaleBar from '@arcgis/core/widgets/ScaleBar';
import Legend from '@arcgis/core/widgets/Legend';
import VectorTileLayer from '@arcgis/core/layers/VectorTileLayer';
import TileLayer from '@arcgis/core/layers/TileLayer';
import Map from '@arcgis/core/Map.js';
import Basemap from '@arcgis/core/Basemap';
import * as intl from '@arcgis/core/intl';

// set asset path for ArcGIS Maps SDK widgets
esriConfig.assetsPath = './assets';

// ids of web map items in portal
const webMapDEID = '7d0768f73d3e4be2b32c22274c600cb3';
const webMapENID = 'dbf5532d06954c6a989d4f022de83f70';

// lazy load components
const Print = dynamic(() => import('./print'));
const Layers = dynamic(() => import('./layer-list'));
const Basemaps = dynamic(() => import('./basemap-list'));
const Search = dynamic(() => import('./search'));

// import Calcite components
import '@esri/calcite-components/dist/calcite/calcite.css';

import { setAssetPath } from '@esri/calcite-components/dist/components';
setAssetPath(window.location.href);

import '@esri/calcite-components/dist/components/calcite-shell';
import '@esri/calcite-components/dist/components/calcite-shell-panel';
import '@esri/calcite-components/dist/components/calcite-shell-center-row';
import '@esri/calcite-components/dist/components/calcite-action-bar';
import '@esri/calcite-components/dist/components/calcite-action';
import '@esri/calcite-components/dist/components/calcite-panel';
import {
  CalciteShell,
  CalciteShellPanel,
  CalciteActionBar,
  CalciteAction,
  CalcitePanel,
} from '@esri/calcite-components-react';

export default function MapComponent({ locale }: { locale: string }) {
  const legendRoot = useRef<HTMLDivElement>(null);
  const maskRoot = useRef<HTMLDivElement>(null);
  const tableRoot = useRef<HTMLDivElement>(null);
  const mapView = useRef<MapView | null>(null);
  const previousId = useRef<string | null>(null);

  const [actionBarExpanded, setActionBarExpanded] = useState<boolean>(false);

  const { t } = useTranslation();

  useEffect(() => {
    if (!mapView.current) {
      // set locale for ArcGIS Maps SDK widgets
      intl.setLocale(locale);

      const webMap = new WebMap({
        portalItem: {
          id: locale === 'de' ? webMapDEID : webMapENID,
          portal: {
            url: 'https://gis.geosphere.at/portal',
          },
        },
      });

      const lightgrayBase = new VectorTileLayer({
        url: 'https://gis.geosphere.at/portal/sharing/rest/content/items/291da5eab3a0412593b66d384379f89f/resources/styles/root.json',
        opacity: 0.5,
      });
      const lightGrayReference = new VectorTileLayer({
        url: 'https://gis.geosphere.at/portal/sharing/rest/content/items/1768e8369a214dfab4e2167d5c5f2454/resources/styles/root.json',
        opacity: 1,
      });
      const worldHillshade = new TileLayer({
        url: 'https://services.arcgisonline.com/arcgis/rest/services/Elevation/World_Hillshade/MapServer',
      });
      const basemapEsri = new Basemap({
        baseLayers: [worldHillshade, lightgrayBase, lightGrayReference],
        title: 'Esri',
        thumbnailUrl:
          'https://gis.geosphere.at/portal/sharing/rest/content/items/3eb1510943be4f29ae01c01ce229d8ba/data',
      });

      const map = new Map({
        basemap: basemapEsri,
      });

      const view = new MapView({
        container: 'map-container',
        map: map,
        padding: {
          left: 49,
        },
        popup: {
          dockOptions: {
            position: 'auto',
            breakpoint: {
              width: 5000,
            },
          },
          dockEnabled: true,
        },
        extent: {
          ymax: 6424330,
          xmin: 923200,
          xmax: 2017806,
          ymin: 5616270,
          spatialReference: {
            wkid: 3857,
          },
        },
      });

      mapView.current = view;
      view.ui.empty('top-left');

      webMap.load().then(() => {
        map.layers = webMap.layers;
        createRoot(document.createElement('div')).render(<Search view={view}></Search>);
      });

      // add further map related UI components
      const scaleBar = new ScaleBar({
        view: view,
        unit: 'metric',
      });

      view.ui.add([scaleBar], 'bottom-left');

      if (legendRoot.current) {
        new Legend({
          view: view,
          container: legendRoot.current,
        });
      }
    }

    return () => {};
  }, [locale]);

  const handleCalciteActionBarToggle = () => {
    setActionBarExpanded(!actionBarExpanded);
    if (mapView.current) {
      mapView.current.padding = !actionBarExpanded ? { left: 150 } : { left: 49 };
    }

    if (tableRoot.current) {
      if (!actionBarExpanded) {
        tableRoot.current.classList.add('left-40');
        tableRoot.current.classList.remove('left-14');
      } else {
        tableRoot.current.classList.add('left-14');
        tableRoot.current.classList.remove('left-40');
      }
    }
  };

  const handleClick = (event: any) => {
    if (event.target.tagName !== 'CALCITE-ACTION') {
      return;
    }

    const nextId = event.target.dataset.actionId;

    if (previousId.current) {
      const previousPanel = document.querySelector(`[data-panel-id=${previousId.current}]`) as HTMLCalcitePanelElement;
      if (previousPanel) {
        previousPanel.hidden = true;
      }

      if (previousId.current === 'print') {
        maskRoot.current?.classList.add('hidden');
      }
    }

    const nextPanel = document.querySelector(`[data-panel-id=${nextId}]`) as HTMLCalcitePanelElement;
    if (nextPanel && nextId !== previousId.current) {
      nextPanel.hidden = false;
      previousId.current = nextId;

      if (nextId === 'print') {
        maskRoot.current?.classList.remove('hidden');
      }
    } else {
      previousId.current = null;
    }
  };

  return (
    <div>
      <CalciteShell contentBehind>
        <CalciteShellPanel slot="panel-start" displayMode="float">
          <CalciteActionBar
            slot="action-bar"
            onCalciteActionBarToggle={handleCalciteActionBarToggle}
            className="border-r border-r-gray-400"
          >
            <CalciteAction
              data-action-id="layers"
              icon="layers"
              text={t('layers.title')}
              onClick={handleClick}
            ></CalciteAction>
            <CalciteAction
              data-action-id="basemaps"
              icon="basemap"
              text={t('basemaps.title')}
              onClick={handleClick}
            ></CalciteAction>
            <CalciteAction
              data-action-id="legend"
              icon="legend"
              text={t('legend.title')}
              onClick={handleClick}
            ></CalciteAction>
            <CalciteAction
              data-action-id="print"
              icon="print"
              text={t('print.heading')}
              onClick={handleClick}
            ></CalciteAction>
            <CalciteAction data-action-id="info" icon="information" text="Info" onClick={handleClick}></CalciteAction>
          </CalciteActionBar>

          <CalcitePanel data-panel-id="layers" heading={t('layers.title')} hidden>
            {mapView.current && tableRoot.current && (
              <Layers view={mapView.current} tableRoot={tableRoot.current}></Layers>
            )}
          </CalcitePanel>

          <CalcitePanel data-panel-id="basemaps" heading={t('basemaps.title')} hidden>
            {mapView.current && <Basemaps view={mapView.current}></Basemaps>}
          </CalcitePanel>

          <CalcitePanel data-panel-id="legend" heading={t('legend.title')} hidden>
            <div ref={legendRoot}></div>
          </CalcitePanel>

          <CalcitePanel data-panel-id="print" heading={t('print.heading')} hidden>
            {mapView.current && maskRoot.current && <Print view={mapView.current} maskRoot={maskRoot.current}></Print>}
          </CalcitePanel>

          <CalcitePanel data-panel-id="info" heading="Info" hidden>
            <div id="info-container"></div>
          </CalcitePanel>
        </CalciteShellPanel>
        <div className="h-screen w-full" id="map-container">
          <div ref={tableRoot} className="hidden absolute left-14 bottom-5 h-1/3 right-2 border border-gray-400"></div>
        </div>
        <div
          ref={maskRoot}
          className="hidden absolute bg-red-300 border-2 border-red-600 opacity-50 pointer-events-none"
        ></div>
      </CalciteShell>
    </div>
  );
}
