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;
}

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>
        </DialogContent>
        <DialogActions sx={{ p: 3, justifyContent: "flex-end" }}>
          <Button onClick={handleSave} variant="contained" color="primary">
            Сохранить
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
);
