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 } from "react-router-dom";
import { toast } from "react-toastify";
import { countryStore, languageStore } from "@shared";
import { useState } from "react";
import { LanguageSwitcher } from "@widgets";

export const CountryCreatePage = observer(() => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const { language } = languageStore;
  const { createCountryData, setCountryData, createCountry } = countryStore;

  const handleCreate = async () => {
    try {
      setIsLoading(true);
      await createCountry();
      toast.success("Страна успешно создана");
      navigate("/country");
    } catch (error) {
      toast.error("Ошибка при создании страны");
    } finally {
      setIsLoading(false);
    }
  };

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

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