import {
  Button,
  Paper,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Box,
} from "@mui/material";
import { observer } from "mobx-react-lite";
import { ArrowLeft, Loader2, Save } from "lucide-react";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import {
  cityStore,
  countryStore,
  languageStore,
  mediaStore,
  isMediaIdEmpty,
  CashedCities,
  LoadingSpinner,
  SelectMediaDialog,
  UploadMediaDialog,
  PreviewMediaDialog,
  selectedCityStore,
} from "@shared";
import { useEffect, useState } from "react";
import { LanguageSwitcher, ImageUploadCard } from "@widgets";

export const CityEditPage = observer(() => {
  const navigate = useNavigate();

  useEffect(() => {
    selectedCityStore.setIsLocked(true);
    return () => selectedCityStore.setIsLocked(false);
  }, []);

  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingData, setIsLoadingData] = useState(true);
  const [isSelectMediaOpen, setIsSelectMediaOpen] = useState(false);
  const [isUploadMediaOpen, setIsUploadMediaOpen] = useState(false);
  const [isPreviewMediaOpen, setIsPreviewMediaOpen] = useState(false);
  const [mediaId, setMediaId] = useState("");
  const [activeMenuType, setActiveMenuType] = useState<
    "thumbnail" | "watermark_lu" | "watermark_rd" | "image" | null
  >(null);
  const { language } = languageStore;
  const { id } = useParams();
  const {
    editCityData,
    editCity,
    getCity,
    setEditCityData,
    setEditCityWeatherCode,
  } = cityStore;
  const { getCountries } = countryStore;
  const { getMedia, getOneMedia } = mediaStore;

  useEffect(() => {
    languageStore.setLanguage("ru");
  }, []);

  const handleEdit = async () => {
    try {
      setIsLoading(true);
      await editCity(id as string);
      toast.success("Город успешно обновлен");
    } catch (error) {
      toast.error("Ошибка при обновлении города");
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    (async () => {
      if (id) {
        setIsLoadingData(true);
        try {
          await getCountries("ru");

          const ruData = await getCity(id as string, "ru");
          const enData = await getCity(id as string, "en");
          const zhData = await getCity(id as string, "zh");

          setEditCityData(ruData.name, ruData.country_code, ruData.arms, "ru");
          setEditCityData(enData.name, enData.country_code, enData.arms, "en");
          setEditCityData(zhData.name, zhData.country_code, zhData.arms, "zh");
          setEditCityWeatherCode(ruData.weather_city_code ?? 0);

          await getOneMedia(ruData.arms as string);

          await getMedia();
        } finally {
          setIsLoadingData(false);
        }
      } else {
        setIsLoadingData(false);
      }
    })();
  }, [id]);

  const handleMediaSelect = (media: {
    id: string;
    filename: string;
    media_name?: string;
    media_type: number;
  }) => {
    setEditCityData(
      editCityData[language].name,
      editCityData.country_code,
      media.id,
      language,
    );
  };

  const selectedMedia =
    editCityData.arms && !isMediaIdEmpty(editCityData.arms)
      ? mediaStore.media.find((m) => m.id === editCityData.arms)
      : null;
  const effectiveArmsUrl = isMediaIdEmpty(editCityData.arms)
    ? null
    : (selectedMedia?.id ?? editCityData.arms);

  if (isLoadingData) {
    return (
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "60vh",
        }}
      >
        <LoadingSpinner message="Загрузка данных города..." />
      </Box>
    );
  }

  return (
    <Paper className="w-full h-full p-3 flex flex-col gap-10">
      <LanguageSwitcher />
      <div className="flex items-center gap-4">
        <button
          className="flex items-center gap-2"
          onClick={() => navigate(-1)}
        >
          <ArrowLeft size={20} />
          Назад
        </button>
      </div>

      <div className="flex flex-col gap-10 w-full items-end">
        <div className="flex gap-10 items-center mb-5 max-w-[80%] self-start    ">
          <h1 className="text-3xl break-words">{editCityData.ru.name}</h1>
        </div>
        <TextField
          fullWidth
          label="Название"
          value={editCityData[language].name}
          required
          onChange={(e) =>
            setEditCityData(
              e.target.value,
              editCityData.country_code,
              editCityData.arms,
              language,
            )
          }
        />

        <FormControl fullWidth>
          <InputLabel>Страна</InputLabel>
          <Select
            value={editCityData.country_code || ""}
            label="Страна"
            required
            onChange={(e) => {
              setEditCityData(
                editCityData[language].name,
                e.target.value,
                editCityData.arms,
                language,
              );
            }}
          >
            {countryStore.countries.ru.data.map((country) => (
              <MenuItem key={country.code} value={country.code}>
                {country.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <TextField
          fullWidth
          label="Код города для погоды"
          value={editCityData.weather_city_code ?? 0}
          onChange={(e) => setEditCityWeatherCode(Number(e.target.value))}
          helperText="ID города брать с ресурса openweathermap.org"
        />

        <div className="w-full flex flex-col gap-4 max-w-[300px] mx-auto">
          <ImageUploadCard
            title="Герб города"
            imageKey="image"
            imageUrl={effectiveArmsUrl}
            onImageClick={() => {
              setIsPreviewMediaOpen(true);
              setMediaId(effectiveArmsUrl ?? "");
            }}
            onDeleteImageClick={() => {
              setEditCityData(
                editCityData[language].name,
                editCityData.country_code,
                "",
                language,
              );
              setActiveMenuType(null);
            }}
            onSelectFileClick={() => {
              setActiveMenuType("image");
              setIsSelectMediaOpen(true);
            }}
            setUploadMediaOpen={() => {
              setIsUploadMediaOpen(true);
              setActiveMenuType("image");
            }}
            setHardcodeType={() => {
              setActiveMenuType("image");
            }}
          />
        </div>

        <Button
          variant="contained"
          className="w-min flex gap-2 items-center"
          startIcon={<Save size={20} />}
          onClick={handleEdit}
          disabled={
            isLoading || !editCityData[language as keyof CashedCities]?.name
          }
        >
          {isLoading ? (
            <Loader2 size={20} className="animate-spin" />
          ) : (
            "Сохранить"
          )}
        </Button>
      </div>

      <SelectMediaDialog
        open={isSelectMediaOpen}
        onClose={() => setIsSelectMediaOpen(false)}
        onSelectMedia={handleMediaSelect}
        mediaType={1}
      />

      <UploadMediaDialog
        open={isUploadMediaOpen}
        onClose={() => setIsUploadMediaOpen(false)}
        contextObjectName={editCityData[language].name}
        contextType="city"
        afterUpload={handleMediaSelect}
        hardcodeType={
          activeMenuType as
            | "thumbnail"
            | "watermark_lu"
            | "watermark_rd"
            | "image"
            | null
        }
      />

      <PreviewMediaDialog
        open={isPreviewMediaOpen}
        onClose={() => setIsPreviewMediaOpen(false)}
        mediaId={mediaId}
      />
    </Paper>
  );
});
