import { Box, Tab, Tabs } from "@mui/material";
import { InformationTab, LeaveAgree, RightWidgetTab } from "@widgets";
import { LeftWidgetTab } from "@widgets";
import { useEffect, useState } from "react";
import { observer } from "mobx-react-lite";
import {
  articlesStore,
  cityStore,
  editSightStore,
  languageStore,
} from "@shared";
import { useBlocker, useParams } from "react-router-dom";

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

export const EditSightPage = observer(() => {
  const [value, setValue] = useState(0);
  const { sight, getSightInfo, needLeaveAgree } = editSightStore;
  const { getArticles } = articlesStore;
  const { language } = languageStore;
  const { id } = useParams();
  const { getRuCities } = cityStore;

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

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

  useEffect(() => {
    const fetchData = async () => {
      if (id) {
        await getSightInfo(+id, language);
        await getArticles(language);
        await getRuCities();
      }
    };
    fetchData();
  }, [id, language]);

  return (
    <Box
      sx={{
        width: "100%",
        display: "flex",
        flexDirection: "column",
        minHeight: "100vh",
      }}
    >
      <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>

      {sight.common.id !== 0 && (
        <div className="flex-1">
          <InformationTab value={value} index={0} />
          <LeftWidgetTab value={value} index={1} />
          <RightWidgetTab value={value} index={2} />
        </div>
      )}

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