import {
  Modal,
  Box,
  Button,
  TextField,
  Typography,
  Grid,
  Paper,
} from "@mui/material";

import { observer } from "mobx-react-lite";
import { useForm } from "@refinedev/react-hook-form";
import { Controller } from "react-hook-form";
import "easymde/dist/easymde.min.css";
import { memo, useMemo, useEffect } from "react";
import { MarkdownEditor } from "../../MarkdownEditor";
import { Edit } from "@refinedev/mui";
import { languageStore } from "../../../store/LanguageStore";
import { LanguageSwitch } from "../../LanguageSwitch/index";

import { useState } from "react";
import { stationStore } from "../../../store/StationStore";
import { useCustom } from "@refinedev/core";
import { useApiUrl } from "@refinedev/core";
import { StationItem } from "src/pages/route/types";
const MemoizedSimpleMDE = memo(MarkdownEditor);

const TRANSFER_FIELDS = [
  { name: "bus", label: "Автобус" },
  { name: "metro_blue", label: "Метро (синяя)" },
  { name: "metro_green", label: "Метро (зеленая)" },
  { name: "metro_orange", label: "Метро (оранжевая)" },
  { name: "metro_purple", label: "Метро (фиолетовая)" },
  { name: "metro_red", label: "Метро (красная)" },
  { name: "train", label: "Электричка" },
  { name: "tram", label: "Трамвай" },
  { name: "trolleybus", label: "Троллейбус" },
];

const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  width: "60%",
  bgcolor: "background.paper",
  border: "2px solid #000",
  boxShadow: 24,
  p: 4,
};

export const StationEditModal = observer(() => {
  const {
    stationModalOpen,
    setStationModalOpenAction,
    selectedStationId,
    selectedRouteId,
  } = stationStore;
  const { language } = languageStore;

  useEffect(() => {
    return () => {
      setStationModalOpenAction(false);
    };
  }, []);

  const apiUrl = useApiUrl();

  const { data: stationQuery, isLoading: isStationLoading } = useCustom({
    url: `${apiUrl}/route/${selectedRouteId ?? 1}/station`,
    method: "get",
  });

  const {
    register,
    control,
    formState: { errors },
    saveButtonProps,
    reset,
    setValue,
    watch,
    handleSubmit,
  } = useForm({
    refineCoreProps: {
      resource: `route/${selectedRouteId ?? 1}/station`,
      action: "edit",
      id: "",
      redirect: false,
      onMutationSuccess: (data) => {
        setStationModalOpenAction(false);
        reset();
        window.location.reload();
      },
      meta: {
        headers: {
          "Accept-Language": language,
        },
      },
    },
  });

  useEffect(() => {
    if (stationModalOpen) {
      const station = stationQuery?.data?.find(
        (station: StationItem) => station.id === selectedStationId
      );
      if (!station) return;
      for (const key in station) {
        setValue(key, station[key]);
      }
      setValue("station_id", station.id);
    }
  }, [stationModalOpen, stationQuery]);

  return (
    <Modal
      open={stationModalOpen}
      onClose={() => setStationModalOpenAction(false)}
      aria-labelledby="modal-modal-title"
      aria-describedby="modal-modal-description"
    >
      <Box sx={style}>
        <Edit
          title={<Typography variant="h5">Редактирование остановки</Typography>}
          saveButtonProps={saveButtonProps}
        >
          <Box
            component="form"
            sx={{ display: "flex", flexDirection: "column" }}
            autoComplete="off"
          >
            <TextField
              {...register("offset_x", {
                setValueAs: (value) => parseFloat(value),
              })}
              error={!!(errors as any)?.offset_x}
              helperText={(errors as any)?.offset_x?.message}
              margin="normal"
              fullWidth
              InputLabelProps={{ shrink: true }}
              type="number"
              label={"Смещение (X)"}
              name="offset_x"
            />

            <TextField
              {...register("offset_y", {
                required: "Это поле является обязательным",
                setValueAs: (value) => parseFloat(value),
              })}
              error={!!(errors as any)?.offset_y}
              helperText={(errors as any)?.offset_y?.message}
              margin="normal"
              fullWidth
              InputLabelProps={{ shrink: true }}
              type="number"
              label={"Смещение (Y)"}
              name="offset_y"
            />

            {/* Группа полей пересадок */}
            <Paper sx={{ p: 2, mt: 2 }}>
              <Typography variant="h6" gutterBottom>
                Пересадки
              </Typography>
              <Grid container spacing={2}>
                {TRANSFER_FIELDS.map((field) => (
                  <Grid item xs={12} sm={6} md={4} key={field.name}>
                    <TextField
                      {...register(`transfers.${field.name}`)}
                      error={!!(errors as any)?.transfers?.[field.name]}
                      helperText={
                        (errors as any)?.transfers?.[field.name]?.message
                      }
                      margin="normal"
                      fullWidth
                      InputLabelProps={{ shrink: true }}
                      type="text"
                      label={field.label}
                      name={`transfers.${field.name}`}
                    />
                  </Grid>
                ))}
              </Grid>
            </Paper>
          </Box>
        </Edit>
      </Box>
    </Modal>
  );
});
