import {
  Button,
  FormControlLabel,
  Checkbox,
  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 { userStore } from "@shared";
import { useEffect, useState } from "react";

export const UserEditPage = observer(() => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const { id } = useParams();
  const { editUserData, editUser, getUser, setEditUserData } = userStore;

  const handleEdit = async () => {
    try {
      setIsLoading(true);
      await editUser(Number(id));
      toast.success("Пользователь успешно обновлен");
      navigate("/user");
    } catch (error) {
      toast.error("Ошибка при обновлении пользователя");
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    (async () => {
      if (id) {
        const data = await getUser(Number(id));

        setEditUserData(
          data?.name || "",
          data?.email || "",
          data?.password || "",
          data?.is_admin || false
        );
      }
    })();
  }, [id]);

  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-start">
        <TextField
          fullWidth
          label="Имя"
          value={editUserData.name || ""}
          required
          onChange={(e) =>
            setEditUserData(
              e.target.value,
              editUserData.email || "",
              editUserData.password || "",
              editUserData.is_admin || false
            )
          }
        />
        <TextField
          fullWidth
          label="Email"
          value={editUserData.email || ""}
          required
          onChange={(e) =>
            setEditUserData(
              editUserData.name || "",
              e.target.value,
              editUserData.password || "",
              editUserData.is_admin || false
            )
          }
        />

        <TextField
          fullWidth
          label="Пароль"
          value={editUserData.password || ""}
          required
          onChange={(e) =>
            setEditUserData(
              editUserData.name || "",
              editUserData.email || "",
              e.target.value,
              editUserData.is_admin || false
            )
          }
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={editUserData.is_admin || false}
              onChange={(e) =>
                setEditUserData(
                  editUserData.name || "",
                  editUserData.email || "",
                  editUserData.password || "",
                  e.target.checked
                )
              }
            />
          }
          label="Администратор"
        />

        <Button
          variant="contained"
          className="w-min flex gap-2 items-center self-end"
          startIcon={<Save size={20} />}
          onClick={handleEdit}
          disabled={isLoading || !editUserData.name || !editUserData.email}
        >
          {isLoading ? (
            <Loader2 size={20} className="animate-spin" />
          ) : (
            "Обновить"
          )}
        </Button>
      </div>
    </Paper>
  );
});
