import { Button, Paper, TextField, Box } from "@mui/material";
import { observer } from "mobx-react-lite";
import { ArrowLeft, Save } from "lucide-react";
import { Loader2 } from "lucide-react";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import { countryStore, languageStore, LoadingSpinner, selectedCityStore } from "@shared";
import { useEffect, useState } from "react";
import { LanguageSwitcher } from "@widgets";

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

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

  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingData, setIsLoadingData] = useState(true);
  const { language } = languageStore;
  const { id } = useParams();
  const { editCountryData, editCountry, getCountry, setEditCountryData } =
    countryStore;

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

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

  useEffect(() => {
    (async () => {
      if (id) {
        setIsLoadingData(true);
        try {
          const ruData = await getCountry(id as string, "ru");
          const enData = await getCountry(id as string, "en");
          const zhData = await getCountry(id as string, "zh");

          setEditCountryData(ruData.name, "ru");
          setEditCountryData(enData.name, "en");
          setEditCountryData(zhData.name, "zh");
        } finally {
          setIsLoadingData(false);
        }
      } else {
        setIsLoadingData(false);
      }
    })();
  }, [id]);

  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 t">{editCountryData.ru.name}</h1>
        </div>
        <TextField
          fullWidth
          label="Код страны"
          value={id as string}
          required
          disabled
        />
        <TextField
          fullWidth
          label="Название"
          value={editCountryData[language].name}
          required
          onChange={(e) =>
            countryStore.setEditCountryData(e.target.value, language)
          }
        />

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