import { Button, Paper, TextField } 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 } from "@shared";
import { useEffect, useState } from "react";
import { LanguageSwitcher } from "@widgets";

export const CountryEditPage = observer(() => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const { language } = languageStore;
  const { id } = useParams();
  const { editCountryData, editCountry, getCountry, setEditCountryData } =
    countryStore;

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

  useEffect(() => {
    (async () => {
      if (id) {
        const data = await getCountry(id as string, language);
        setEditCountryData(data.name, language);
      }
    })();
  }, [id, language]);

  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">
        <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>
  );
});
