import { Box, Stack, Typography, Button } from "@mui/material";
import { useNavigate, useNavigationType } from "react-router";
import { MediaViewer } from "@widgets";
import { useMapData } from "./MapDataContext";
import { observer } from "mobx-react-lite";
import { useEffect, useState } from "react";
import { authInstance, isMediaIdEmpty } from "@shared";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import LanguageSelector from "./web-gl/LanguageSelector";

type LeftSidebarProps = {
  open: boolean;
  onToggle: () => void;
};

export const LeftSidebar = observer(({ open, onToggle }: LeftSidebarProps) => {
  const navigate = useNavigate();
  const navigationType = useNavigationType(); // PUSH, POP, REPLACE
  const { routeData } = useMapData();
  const [carrierThumbnail, setCarrierThumbnail] = useState<string | null>(null);
  const [carrierLogo, setCarrierLogo] = useState<string | null>(null);
  useEffect(() => {
    async function fetchCarrierThumbnail() {
      if (routeData?.carrier_id) {
        const { city_id, logo } = (
          await authInstance.get(`/carrier/${routeData.carrier_id}`)
        ).data;
        const { arms } = (await authInstance.get(`/city/${city_id}`)).data;
        setCarrierThumbnail(arms);
        setCarrierLogo(logo);
      }
    }
    fetchCarrierThumbnail();
  }, [routeData?.carrier_id]);

  const handleBack = () => {
    if (navigationType === "PUSH") {
      navigate(-1);
    } else {
      navigate("/route");
    }
  };

  return (
    <Box
      sx={{
        position: "relative",
        height: "100%",
        color: "#fff",
        transition: "padding 0.3s ease",
        p: open ? 2 : 0,
        display: "flex",
        flexDirection: "column",
        alignItems: "stretch",
        justifyContent: "flex-start",
      }}
    >
      <Stack
        direction="column"
        height="100%"
        width="100%"
        spacing={4}
        alignItems="stretch"
        justifyContent="space-between"
        sx={{
          opacity: open ? 1 : 0,
          transition: "opacity 0.25s ease",
          pointerEvents: open ? "auto" : "none",
          display: open ? "flex" : "none",
        }}
      >
        <div>
          <Button
            onClick={handleBack}
            variant="contained"
            color="primary"
            sx={{
              backgroundColor: "#222",
              color: "#fff",
              borderRadius: 1.5,
              px: 2,
              py: 1,
              marginBottom: 10,
              "&:hover": {
                backgroundColor: "#2d2d2d",
              },
            }}
            fullWidth
            startIcon={<ArrowBackIcon />}
          >
            Назад
          </Button>

          <Stack
            direction="column"
            alignItems="center"
            justifyContent="center"
            spacing={3}
          >
            <div
              style={{
                maxWidth: 150,
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                gap: 10,
              }}
            >
              {carrierThumbnail && !isMediaIdEmpty(carrierThumbnail) && (
                <MediaViewer
                  media={{
                    id: carrierThumbnail,
                    media_type: 1, // Тип "Фото" для логотипа
                    filename: "route_thumbnail",
                  }}
                  fullWidth
                  fullHeight
                />
              )}
              <Typography sx={{ color: "#fff" }} textAlign="center">
                При поддержке Правительства
              </Typography>
            </div>
          </Stack>

          <div className="flex flex-col items-center justify-center gap-2 mt-10">
            <button className="bg-[#fcd500] text-black px-4 py-2 rounded-md w-full font-medium my-10">
              Обращение губернатора
            </button>
            <button className="bg-white text-black px-4 py-2 rounded-md w-full font-medium mx-5">
              Достопримечательности
            </button>
            <button className="bg-white text-black px-4 py-2 rounded-md w-full font-medium mx-5">
              Остановки
            </button>
          </div>
        </div>

        <Stack
          direction="column"
          alignItems="center"
          maxHeight={150}
          justifyContent="center"
          flexGrow={1}
        >
          {carrierLogo && !isMediaIdEmpty(carrierLogo) && (
            <MediaViewer
              media={{
                id: carrierLogo,
                media_type: 1, // Тип "Фото" для логотипа
                filename: "route_thumbnail_logo",
              }}
              fullHeight
            />
          )}
        </Stack>

        <Typography
          variant="h6"
          textAlign="center"
          sx={{ color: "#fff", marginTop: "auto" }}
        >
          #ВсемПоПути
        </Typography>
      </Stack>

      <div className="absolute bottom-[20px] -right-[520px] z-10">
        <LanguageSelector onBack={onToggle} isSidebarOpen={open} />
      </div>
    </Box>
  );
});
