import { Box, Tab, Tabs } from "@mui/material";
import {
  articlesStore,
  authStore,
  cityStore,
  createSightStore,
  languageStore,
  selectedCityStore,
} from "@shared";
import {
  CreateInformationTab,
  CreateLeftTab,
  CreateRightTab,
  LeaveAgree,
} from "@widgets";
import { useEffect, useState } from "react";
import { observer } from "mobx-react-lite";
import { runInAction } from "mobx";

function a11yProps(index: number) {
  return {
    id: `sight-tab-${index}`,
    "aria-controls": `sight-tabpanel-${index}`,
  };
}

import { useBlocker } from "react-router";

export const CreateSightPage = observer(() => {
  const [value, setValue] = useState(0);
  const { getCities } = cityStore;
  const { getArticles } = articlesStore;
  const needLeave = createSightStore.needLeaveAgree;

  useEffect(() => {
    selectedCityStore.setIsLocked(true);
    return () => selectedCityStore.setIsLocked(false);
  }, []);

  const handleChange = (_: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };

  let blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      needLeave && currentLocation.pathname !== nextLocation.pathname,
  );

  useEffect(() => {
    if (blocker.state === "blocked" && !needLeave) {
      blocker.proceed();
    }
  }, [blocker.state, needLeave]);

  useEffect(() => {
    const fetchData = async () => {
      if (!authStore.me) {
        await authStore.getMeAction().catch(() => undefined);
      }
      if (authStore.canRead("cities")) {
        await getCities("ru");
      } else {
        await authStore.fetchMeCities().catch(() => undefined);
      }
      await getArticles(languageStore.language);

      const { selectedCityId, selectedCity } = selectedCityStore;
      if (selectedCityId && selectedCity && !createSightStore.sight.city_id) {
        runInAction(() => {
          createSightStore.sight.city_id = selectedCityId;
          createSightStore.sight.city = selectedCity.name;
        });
      }
    };
    fetchData();
  }, []);

  return (
    <Box
      sx={{
        width: "100%",
        display: "flex",
        flexDirection: "column",
        minHeight: "100vh",
        z: 10,
      }}
    >
      <Box
        sx={{
          borderBottom: 1,
          borderColor: "divider",
          display: "flex",
          justifyContent: "center",
        }}
      >
        <Tabs
          value={value}
          onChange={handleChange}
          aria-label="sight tabs"
          sx={{
            width: "100%",
            "& .MuiTabs-flexContainer": {
              justifyContent: "center",
            },
          }}
        >
          <Tab sx={{ flex: 1 }} label="Общая информация" {...a11yProps(0)} />
          <Tab sx={{ flex: 1 }} label="Левый виджет" {...a11yProps(1)} />
          <Tab sx={{ flex: 1 }} label="Правый виджет" {...a11yProps(2)} />
        </Tabs>
      </Box>

      <div className="flex-1">
        <CreateInformationTab value={value} index={0} />
        <CreateLeftTab value={value} index={1} />
        <CreateRightTab value={value} index={2} />
      </div>

      {blocker.state === "blocked" ? <LeaveAgree blocker={blocker} /> : null}
    </Box>
  );
});
