import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Typography,
  IconButton,
  Box,
} from "@mui/material";
import { stationsStore, languageStore } from "@shared";
import { observer } from "mobx-react-lite";
import { ArrowLeft } from "lucide-react";
import { toast } from "react-toastify";
import { useState, useEffect } from "react";

interface EditStationTransfersModalProps {
  open: boolean;
  onClose: () => void;
  stationId: number | null;
}

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 EditStationTransfersModal = observer(
  ({ open, onClose, stationId }: EditStationTransfersModalProps) => {
    const { stationLists, updateStationTransfers } = stationsStore;
    const { language } = languageStore;
    const [transfers, setTransfers] = useState<{
      bus: string;
      metro_blue: string;
      metro_green: string;
      metro_orange: string;
      metro_purple: string;
      metro_red: string;
      train: string;
      tram: string;
      trolleybus: string;
    }>({
      bus: "",
      metro_blue: "",
      metro_green: "",
      metro_orange: "",
      metro_purple: "",
      metro_red: "",
      train: "",
      tram: "",
      trolleybus: "",
    });
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
      if (open && stationId) {
        let station = stationLists[language].data.find(
          (s: any) => s.id === stationId
        );
        if (!station?.transfers) {
          for (const lang of ["ru", "en", "zh"] as const) {
            const foundStation = stationLists[lang].data.find(
              (s: any) => s.id === stationId
            );
            if (foundStation?.transfers) {
              station = foundStation;
              break;
            }
          }
        }

        if (station?.transfers) {
          setTransfers(station.transfers);
        }
      }
    }, [open, stationId, stationLists]);

    const handleSave = async () => {
      if (!stationId) return;

      try {
        setIsLoading(true);
        await updateStationTransfers(stationId, transfers);
        toast.success("Пересадки успешно обновлены");
        const { getStationList } = stationsStore;
        await getStationList();
        onClose();
      } catch (error) {
        console.error("Error updating transfers:", error);
        toast.error("Ошибка при обновлении пересадок");
      } finally {
        setIsLoading(false);
      }
    };

    const handleTransferChange = (key: string, value: string) => {
      setTransfers((prev) => ({
        ...prev,
        [key]: value,
      }));
    };

    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 }}>
            <Typography variant="h6" gutterBottom>
              Пересадки
            </Typography>
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: "repeat(3, 1fr)",
                gap: 2,
                mt: 2,
              }}
            >
              {transferFields.map(({ key, label }) => (
                <TextField
                  key={key}
                  label={label}
                  name={key}
                  fullWidth
                  value={transfers[key as keyof typeof transfers] || ""}
                  onChange={(e) => handleTransferChange(key, e.target.value)}
                />
              ))}
            </Box>
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: 3, justifyContent: "flex-end" }}>
          <Button onClick={onClose} variant="outlined">
            Отмена
          </Button>
          <Button
            onClick={handleSave}
            variant="contained"
            color="primary"
            disabled={isLoading}
          >
            {isLoading ? "Сохранение..." : "Сохранить"}
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
);
