import { Button, Paper, TextField } from "@mui/material";
import { observer } from "mobx-react-lite";
import { ArrowLeft, Loader2, Save } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import {
  userStore,
  mediaStore,
  isMediaIdEmpty,
  SelectMediaDialog,
  UploadMediaDialog,
  PreviewMediaDialog,
} from "@shared";
import { useState, useEffect } from "react";
import { ImageUploadCard } from "@widgets";

export const UserCreatePage = observer(() => {
  const navigate = useNavigate();
  const { createUserData, setCreateUserData, createUser } = userStore;
  const [isLoading, setIsLoading] = useState(false);
  const [isSelectMediaOpen, setIsSelectMediaOpen] = useState(false);
  const [isUploadMediaOpen, setIsUploadMediaOpen] = useState(false);
  const [isPreviewMediaOpen, setIsPreviewMediaOpen] = useState(false);
  const [mediaId, setMediaId] = useState("");
  const [activeMenuType, setActiveMenuType] = useState<
    "thumbnail" | "watermark_lu" | "watermark_rd" | "image" | null
  >(null);

  useEffect(() => {
    mediaStore.getMedia();
  }, []);

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

  const handleMediaSelect = (media: {
    id: string;
    filename: string;
    media_name?: string;
    media_type: number;
  }) => {
    setCreateUserData(
      createUserData.name || "",
      createUserData.email || "",
      createUserData.password || "",
      createUserData.is_admin || false,
      media.id
    );
  };

  const selectedMedia =
    createUserData.icon && !isMediaIdEmpty(createUserData.icon)
      ? mediaStore.media.find((m) => m.id === createUserData.icon)
      : null;
  const effectiveIconUrl = isMediaIdEmpty(createUserData.icon)
    ? null
    : selectedMedia?.id ?? createUserData.icon ?? null;

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

        <TextField
          fullWidth
          label="Email"
          value={createUserData.email || ""}
          required
          onChange={(e) =>
            setCreateUserData(
              createUserData.name || "",
              e.target.value,
              createUserData.password || "",
              createUserData.is_admin || false,
              createUserData.icon
            )
          }
        />

        <TextField
          fullWidth
          label="Пароль"
          value={createUserData.password || ""}
          required
          onChange={(e) =>
            setCreateUserData(
              createUserData.name || "",
              createUserData.email || "",
              e.target.value,
              createUserData.is_admin || false,
              createUserData.icon
            )
          }
        />

        <div className="w-full flex flex-col gap-4 max-w-[300px] mx-auto">
          <ImageUploadCard
            title="Аватар"
            imageKey="thumbnail"
            imageUrl={effectiveIconUrl}
            onImageClick={() => {
              setIsPreviewMediaOpen(true);
              setMediaId(effectiveIconUrl ?? "");
            }}
            onDeleteImageClick={() => {
              setCreateUserData(
                createUserData.name || "",
                createUserData.email || "",
                createUserData.password || "",
                createUserData.is_admin || false,
                ""
              );
              setActiveMenuType(null);
            }}
            onSelectFileClick={() => {
              setActiveMenuType("image");
              setIsSelectMediaOpen(true);
            }}
            setUploadMediaOpen={() => {
              setIsUploadMediaOpen(true);
              setActiveMenuType("image");
            }}
          />
        </div>

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

      <SelectMediaDialog
        open={isSelectMediaOpen}
        onClose={() => setIsSelectMediaOpen(false)}
        onSelectMedia={handleMediaSelect}
        mediaType={1}
      />

      <UploadMediaDialog
        open={isUploadMediaOpen}
        onClose={() => setIsUploadMediaOpen(false)}
        contextObjectName={createUserData.name || "Пользователь"}
        contextType="user"
        afterUpload={handleMediaSelect}
        hardcodeType={activeMenuType}
      />

      <PreviewMediaDialog
        open={isPreviewMediaOpen}
        onClose={() => setIsPreviewMediaOpen(false)}
        mediaId={mediaId}
      />
    </Paper>
  );
});
