import {
  Paper,
  Flex,
  ScrollArea,
  Autocomplete,
  Title,
  Text,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { HeaderSimple } from "./Header";
import { FooterLinks } from "./Footer";
import headerLinks from "./assets/header.json";
import footerLinks from "./assets/footer.json";
import { PlaceCard } from "./PlaceCard";
// import { ArticleCardMobile } from "./ArticleCardMobile";
import Map, {
  Source,
  Layer,
  ScaleControl,
  GeolocateControl,
  Popup,
} from "react-map-gl/maplibre";
import "maplibre-gl/dist/maplibre-gl.css";
import { useState, useEffect, useRef } from "react";

// import mapstyle from './assets/basemap.json';
import mapstyle from "./assets/basemap-mapbox.json";
import plus from "./assets/plus.png";
import minus from "./assets/minus.png";

export function TripPage() {
  const mapRef = useRef(null);
  // const [initial, setInitial] = useState([]);
  const [places, setPlaces] = useState(null);
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState(-1);
  const [cursor, setCursor] = useState("grab");
  const [popupInfo, setPopupInfo] = useState(null);
  const [openedMenu, menuactions] = useDisclosure(false);

  const host = "https://strapi.litmusmap.ru";

  useEffect(() => {
    fetch("/prishvin-trip/prishvin.geojson")
      .then((r) => r.json())
      .then((j) => setPlaces(j.features));
  }, []);

  // Select article interaction
  useEffect(() => {
    if (selected > 0) {
      const selectedIndex = places.findIndex(
        (p) => p.properties.fid == selected
      );
      const selectedObject = places[selectedIndex];
      // const reordered = [
      //   selectedObject,
      //   ...places.filter((p) => p.properties.fid !== selected),
      // ];
      // setPlaces(reordered);
      mapRef.current?.flyTo({
        center: [
          selectedObject.geometry.coordinates[0],
          selectedObject.geometry.coordinates[1],
        ],
        zoom: 10,
      });
    } else {
      mapRef.current?.flyTo({
        center: [35, 57],
        zoom: 3,
      });
    }
  }, [selected]);

  const handleClick = (id) => {
    setSelected(id);
  };

  // Zoom
  const ZoomControl = (props) => {
    const zoomIn = () => {
      mapRef.current.zoomTo(mapRef.current.getZoom() + 1);
    };
    const zoomOut = () => {
      mapRef.current.zoomTo(mapRef.current.getZoom() - 1);
    };
    return (
      <Flex
        style={{
          position: "absolute",
          bottom: props.bottom,
          right: props.right,
        }}
      >
        <Paper
          onClick={zoomOut}
          radius="xl"
          bg={"none"}
          sx={{ "&:hover": { backgroundColor: "white", cursor: "pointer" } }}
          maw={48}
          mah={48}
        >
          <img src={minus} style={{ width: "48px", height: "48px" }}></img>
        </Paper>
        <Paper
          onClick={zoomIn}
          radius="xl"
          bg={"none"}
          sx={{ "&:hover": { backgroundColor: "white", cursor: "pointer" } }}
          maw={48}
          mah={48}
        >
          <img src={plus} style={{ width: "48px", height: "48px" }}></img>
        </Paper>
      </Flex>
    );
  };

  return (
    <>
      <HeaderSimple
        links={headerLinks.links}
        openedMenuKarta={openedMenu}
        menuactionskarta={menuactions}
      />
      <div style={{ position: "relative" }}>
        <Map
          ref={mapRef}
          initialViewState={{
            longitude: 35,
            latitude: 60,
            zoom: 3,
          }}
          minZoom={3.5}
          maxZoom={16}
          maxBounds={[
            [-60, 35],
            [200, 80],
          ]}
          style={{
            height: "90vh",
          }}
          cursor={cursor}
          mapStyle={mapstyle}
          interactiveLayerIds={["trip-layer"]}
          onClick={(e) => {
            // console.log(e.features);
            if (e.features[0]) {
              setSelected(e.features[0].properties.fid);
              if (mapRef.current.getZoom() < 14) {
                mapRef.current.flyTo({
                  center: e.features[0].geometry.coordinates,
                  zoom: mapRef.current.getZoom() + 6,
                });
                setPopupInfo({
                  longitude: e.features[0].geometry.coordinates[0],
                  latitude: e.features[0].geometry.coordinates[1],
                  text: `${
                    e.features[0].properties.date_start ==
                    e.features[0].properties.date_finish
                      ? e.features[0].properties.date_start
                      : `${e.features[0].properties.date_start} - ${e.features[0].properties.date_finish}`
                  } ${e.features[0].properties.place_name}`,
                });
              }
            } else {
              setSelected(-1);
            }
          }}
          onMouseEnter={() => setCursor("pointer")}
          onMouseLeave={() => setCursor("grab")}
          // onLoad={handleMapLoad}
        >
          <Source
            id="trip"
            type="geojson"
            data="/prishvin-trip/prishvin.geojson"
            maxzoom={10}
          >
            {popupInfo && (
              <Popup
                key={popupInfo.id}
                longitude={popupInfo.longitude}
                latitude={popupInfo.latitude}
                closeButton={false}
                onClose={() => setPopupInfo(null)}
              >
                {popupInfo.text}
              </Popup>
            )}
            <Layer
              id="trip-layer"
              type="circle"
              paint={{
                "circle-color": [
                  "match",
                  ["get", "fid"],
                  selected,
                  "#e66a5a",
                  "#F2994A",
                ],
                "circle-radius": ["step", ["zoom"], 5, 7, 10, 12, 15, 14, 20],
                "circle-opacity": 0.8,
              }}
            />
          </Source>
          <ScaleControl position="bottom-right" />
          <ZoomControl bottom="35px" right="4px" />
          <GeolocateControl
            showAccuracyCircle={false}
            position="bottom-right"
            style={{
              marginBottom: "55px",
              marginRight: "14px",
              background: "none",
              boxShadow: "none",
            }}
          />
        </Map>

        {/* Search mobile */}
        <Paper
          shadow={"md"}
          radius={0}
          display={!openedMenu && "none"}
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            height: "340px",
            opacity: "95%",
            padding: "55px 0 1rem 1rem",
          }}
          sx={{
            "@media (min-width: 60em)": {
              display: "none",
            },
          }}
        >
          <Autocomplete
            mr={20}
            mb={10}
            placeholder="Поиск"
            limit={2}
            value={search}
            onChange={setSearch}
            data={[]}
          />
          <ScrollArea h={"225px"} type="auto">
            <Flex
              // mih={50}
              gap="xs"
              justify="flex-start"
              align="start"
              direction="column"
              wrap="wrap"
              mr={20}
            >
              {/* {articles !== null &&
                articles.length > 0 &&
                articles.map((article) => (
                  <ArticleCardMobile
                    key={article.id}
                    id={article.id}
                    image={
                      article.attributes.cover.data !== null
                        ? host + article.attributes.cover.data.attributes.url
                        : ""
                    }
                    category="музеи"
                    title={article.attributes.title}
                    address={article.attributes.address}
                    longitude={article.attributes.longitude}
                    latitude={article.attributes.latitude}
                    selected={selected}
                    clickAddressAction={handleAddressClick}
                  />
                ))} */}
            </Flex>
          </ScrollArea>
        </Paper>

        {/* Search pc */}
        <Paper
          shadow={"md"}
          withBorder
          style={{
            position: "absolute",
            top: "1rem",
            left: "1rem",
            width: "36rem",
            height: "80%",
            opacity: "95%",
            padding: "1rem 0 1rem 1rem",
          }}
          sx={{
            "@media (max-width: 60em)": {
              display: "none",
            },
          }}
        >
          <Title order={3} mb={10}>
            Места
          </Title>
          <ScrollArea
            h={"80%"}
            type="auto"
            sx={{
              "@media (max-height: 700px)": {
                height: "60%",
              },
              "@media (max-height: 400px)": {
                height: "50%",
              },
            }}
          >
            <Text mr={20} mb={10}>
              География пришвинской биографии невероятно богата. Писатель много
              где жил и много где путешествовал. Главная особенность творчества
              Пришвина в том, что фактически все места обитания и все маршруты
              путешествий непреложно отражались в его произведениях. Если и есть
              исключения – поездка на Уралмаш в 1933 году, то она описана в
              Дневнике писателя.
            </Text>
            <Flex
              mih="40rem"
              gap="md"
              justify="flex-start"
              align="start"
              direction="column"
              wrap="wrap"
              mr={20}
            >
              {places &&
                places
                  .sort(
                    (a, b) => a.properties.date_start - b.properties.date_start
                  )
                  .map((place) => (
                    <PlaceCard
                      key={place.properties.fid}
                      {...place.properties}
                      coordinates={place.geometry.coordinates}
                      selected={selected}
                      clickAction={handleClick}
                    />
                  ))}
            </Flex>
          </ScrollArea>
        </Paper>
      </div>
      <FooterLinks data={footerLinks.data} />
    </>
  );
}
