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

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

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

  const { language } = languageStore;
  const { createCityData, setCreateCityData, setCreateCityWeatherCode } =
    cityStore;
  const [isLoading, setIsLoading] = useState(false);
  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 { getCountries } = countryStore;
  const { getMedia } = mediaStore;

  useEffect(() => {
    (async () => {
      await getCountries("ru");
      await getCountries("en");
      await getCountries("zh");
      await getMedia();
    })();
  }, [language]);

  const handleCreate = async () => {
    try {
      setIsLoading(true);
      await cityStore.createCity();
      toast.success("Город успешно создан");
      navigate("/city");
    } catch (error) {
      toast.error("Ошибка при создании города");
    } finally {
      setIsLoading(false);
    }
  };

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

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

  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">{createCityData.ru.name}</h1>
        </div>
        <TextField
          fullWidth
          label="Название города"
          value={createCityData[language]?.name || ""}
          required
          onChange={(e) =>
            setCreateCityData(
              e.target.value,
              createCityData.country_code,
              createCityData.arms,
              language,
            )
          }
        />

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

        <TextField
          fullWidth
          label="Код города для погоды"
          value={createCityData.weather_city_code ?? 0}
          onChange={(e) => setCreateCityWeatherCode(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={() => {
              setCreateCityData(
                createCityData[language].name,
                createCityData.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={handleCreate}
          disabled={isLoading || !createCityData[language]?.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={createCityData[language]?.name}
        contextType="city"
        afterUpload={handleMediaSelect}
        hardcodeType={
          activeMenuType as "thumbnail" | "watermark_lu" | "watermark_rd" | null
        }
      />

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