import {
  Button,
  Paper,
  TextField,
  Autocomplete,
  FormControl,
} 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,
  RU_COUNTRIES,
  EN_COUNTRIES,
  ZH_COUNTRIES,
  selectedCityStore,
} from "@shared";
import { useState, useEffect } from "react";

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

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

  const [isLoading, setIsLoading] = useState(false);
  const { createCountryData, setCountryData, createCountry } = countryStore;

  const handleCountryCodeChange = (code: string) => {
    const ruCountry = RU_COUNTRIES.find((c) => c.code === code);
    const enCountry = EN_COUNTRIES.find((c) => c.code === code);
    const zhCountry = ZH_COUNTRIES.find((c) => c.code === code);

    if (ruCountry && enCountry && zhCountry) {
      setCountryData(code, ruCountry.name, "ru");
      setCountryData(code, enCountry.name, "en");
      setCountryData(code, zhCountry.name, "zh");
    }
  };

  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">
      <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">
        <FormControl fullWidth>
          <Autocomplete
            value={
              RU_COUNTRIES.find((c) => c.code === createCountryData.code) ||
              null
            }
            onChange={(_, newValue) => {
              if (newValue) {
                handleCountryCodeChange(newValue.code);
              }
            }}
            options={RU_COUNTRIES}
            getOptionLabel={(option) => `${option.code} - ${option.name}`}
            renderInput={(params) => (
              <TextField
                {...params}
                label="Страна"
                required
                inputProps={{
                  ...params.inputProps,
                  maxLength: 2,
                }}
              />
            )}
            filterOptions={(options, { inputValue }) => {
              const searchValue = inputValue.toUpperCase();
              return options.filter(
                (option) =>
                  option.code.includes(searchValue) ||
                  option.name.toLowerCase().includes(inputValue.toLowerCase())
              );
            }}
          />
        </FormControl>

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