import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Typography,
  IconButton,
  Box,
} from "@mui/material";
import { routeStore } from "@shared";
import { observer } from "mobx-react-lite";
import { ArrowLeft } from "lucide-react";
import { useParams } from "react-router-dom";
import { toast } from "react-toastify";

interface EditStationModalProps {
  open: boolean;
  onClose: () => void;
}

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

export const EditStationModal = observer(
  ({ open, onClose }: EditStationModalProps) => {
    const { id: routeId } = useParams<{ id: string }>();
    const {
      selectedStationId,
      setRouteStations,
      saveRouteStations,
      routeStations,
    } = routeStore;

    const handleSave = async () => {
      await saveRouteStations(Number(routeId), selectedStationId);
      toast.success("Успешно сохранено");
      onClose();
    };

    const station = routeStations[Number(routeId)]?.find(
      (station: any) => station.id === selectedStationId
    );

    return (
      <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
        <DialogTitle>
          <Box display="flex" alignItems="center" gap={2}>
            <IconButton onClick={onClose}>
              <ArrowLeft />
            </IconButton>
            <Box>
              <Typography variant="caption" color="text.secondary">
                Маршруты / Редактировать
              </Typography>
              <Typography variant="h6">Редактирование остановки</Typography>
            </Box>
          </Box>
        </DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2, display: "flex", gap: 2, flexDirection: "column" }}>
            <TextField
              label="Смещение (X)"
              name="offset_x"
              type="number"
              fullWidth
              onChange={(e) => {
                setRouteStations(Number(routeId), selectedStationId, {
                  offset_x: Number(e.target.value),
                });
              }}
              defaultValue={station?.offset_x}
            />

            <TextField
              label="Смещение (Y)"
              name="offset_y"
              type="number"
              fullWidth
              onChange={(e) => {
                setRouteStations(Number(routeId), selectedStationId, {
                  offset_y: Number(e.target.value),
                });
              }}
              defaultValue={station?.offset_y}
            />
          </Box>
          <Box sx={{ mt: 4 }}>
            <Typography variant="h6" gutterBottom>
              Пересадки
            </Typography>
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: "repeat(3, 1fr)",
                gap: 2,
              }}
            >
              {transferFields.map(({ key, label }) => (
                <TextField
                  key={key}
                  label={label}
                  name={key}
                  fullWidth
                  defaultValue={station?.transfers?.[key]}
                  onChange={(e) => {
                    setRouteStations(Number(routeId), selectedStationId, {
                      ...station,
                      transfers: {
                        ...station?.transfers,
                        [key]: e.target.value,
                      },
                    });
                  }}
                />
              ))}
            </Box>
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: 3, justifyContent: "flex-end" }}>
          <Button onClick={handleSave} variant="contained" color="primary">
            Сохранить
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
);
