import React, { useEffect } from "react";
import {
  FormControl,
  Select,
  MenuItem,
  SelectChangeEvent,
  Typography,
  Box,
} from "@mui/material";
import { observer } from "mobx-react-lite";
import { cityStore, selectedCityStore } from "@shared";
import { MapPin } from "lucide-react";

export const CitySelector: React.FC = observer(() => {
  const { getCities, cities } = cityStore;
  const { selectedCity, setSelectedCity } = selectedCityStore;

  useEffect(() => {
    getCities("ru");
  }, []);

  const handleCityChange = (event: SelectChangeEvent<string>) => {
    const cityId = event.target.value;
    if (cityId === "") {
      setSelectedCity(null);
      return;
    }

    const city = cities["ru"].data.find((c) => c.id === Number(cityId));
    if (city) {
      setSelectedCity(city);
    }
  };

  const currentCities = cities["ru"].data;

  return (
    <Box className="flex items-center gap-2">
      <MapPin size={16} className="text-white" />
      <FormControl size="medium" sx={{ minWidth: 120 }}>
        <Select
          value={selectedCity?.id?.toString() || ""}
          onChange={handleCityChange}
          displayEmpty
          sx={{
            height: "40px",
            color: "white",
            "& .MuiOutlinedInput-notchedOutline": {
              borderColor: "rgba(255, 255, 255, 0.3)",
            },
            "&:hover .MuiOutlinedInput-notchedOutline": {
              borderColor: "rgba(255, 255, 255, 0.5)",
            },
            "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
              borderColor: "white",
            },
            "& .MuiSvgIcon-root": {
              color: "white",
            },
          }}
          MenuProps={{
            PaperProps: {},
          }}
        >
          <MenuItem value="">
            <Typography variant="body2">Выберите город</Typography>
          </MenuItem>
          {currentCities.map((city) => (
            <MenuItem key={city.id} value={city.id?.toString()}>
              <Typography variant="body2">{city.name}</Typography>
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </Box>
  );
});
