import {
  Button,
  Paper,
  TextField,
  Checkbox,
  Typography,
  Box,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Radio,
  RadioGroup,
  Divider,
} 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,
  selectedCityStore,
} from "@shared";
import { useState, useEffect } from "react";
import { ImageUploadCard } from "@widgets";

const ROLE_RESOURCES = [
  { key: "snapshot", label: "Экспорт" },
  { key: "devices", label: "Устройства" },
  { key: "vehicles", label: "Транспорт" },
  { key: "users", label: "Пользователи" },
  { key: "sights", label: "Достопримечательности" },
  { key: "stations", label: "Остановки" },
  { key: "routes", label: "Маршруты" },
  { key: "countries", label: "Страны" },
  { key: "cities", label: "Города" },
  { key: "carriers", label: "Перевозчики" },
] as const;

type PermissionLevel = "none" | "ro" | "rw";

function getPermissionLevel(roles: string[], resource: string): PermissionLevel {
  if (roles.includes(`${resource}_rw`)) return "rw";
  if (roles.includes(`${resource}_ro`)) return "ro";
  return "none";
}

function applyPermissionChange(
  roles: string[],
  resource: string,
  level: PermissionLevel,
): string[] {
  const filtered = roles.filter(
    (r) => r !== `${resource}_ro` && r !== `${resource}_rw`,
  );
  if (level === "ro") return [...filtered, `${resource}_ro`];
  if (level === "rw") return [...filtered, `${resource}_rw`];
  return filtered;
}

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

  const [localRoles, setLocalRoles] = useState<string[]>(
    createUserData.roles ?? ["articles_ro", "articles_rw", "media_ro", "media_rw"]
  );

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

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

  useEffect(() => {
    const allRw = ROLE_RESOURCES.every(({ key }) => localRoles.includes(`${key}_rw`));
    const isAdmin = allRw && !localRoles.includes("devices_maintenance_rw");
    if (isAdmin !== createUserData.is_admin) {
      setCreateUserData(
        createUserData.name || "",
        createUserData.email || "",
        createUserData.password || "",
        isAdmin,
        createUserData.icon
      );
    }
  }, [localRoles]);

  const handleCreate = async () => {
    try {
      setIsLoading(true);
      // Убеждаемся, что роли в сторе обновлены перед созданием
      userStore.createUserData.roles = localRoles;
      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 p-6 flex flex-col gap-8">
      <button className="flex items-center gap-2 self-start" onClick={() => navigate(-1)}>
        <ArrowLeft size={20} />
        Назад
      </button>

      <section className="flex flex-col gap-6">
        <Typography variant="h6">Основные данные</Typography>

        <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
          type="password"
          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]">
          <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>
      </section>

      <Divider />

      <section className="flex flex-col gap-4">
        <Typography variant="h6">Права доступа</Typography>

        <Box sx={{ display: "flex", gap: 1 }}>
          <Button
            variant="outlined"
            size="small"
            onClick={() => {
              setCreateUserData(
                createUserData.name || "",
                createUserData.email || "",
                createUserData.password || "",
                true,
                createUserData.icon
              );
              const next: string[] = [];
              for (const { key } of ROLE_RESOURCES) {
                next.push(`${key}_rw`);
              }
              next.push("snapshot_create");
              setLocalRoles(next);
            }}
          >
            Полный доступ (admin)
          </Button>
          <Button
            variant="outlined"
            size="small"
            onClick={() => {
              setCreateUserData(
                createUserData.name || "",
                createUserData.email || "",
                createUserData.password || "",
                false,
                createUserData.icon
              );
              setLocalRoles(["devices_ro", "vehicles_ro", "devices_maintenance_rw"]);
            }}
          >
            Администратор ТО
          </Button>
        </Box>

        <Box sx={{ border: "1px solid", borderColor: "divider", borderRadius: 1 }}>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ bgcolor: "action.hover" }}>
                <TableCell sx={{ fontWeight: 600, width: 220 }}>Ресурс</TableCell>
                <TableCell align="center" sx={{ fontWeight: 600 }}>Нет доступа</TableCell>
                <TableCell align="center" sx={{ fontWeight: 600 }}>Чтение</TableCell>
                <TableCell align="center" sx={{ fontWeight: 600 }}>Чтение/Запись</TableCell>
                <TableCell align="center" sx={{ fontWeight: 600 }}>
                  Доп. права
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {ROLE_RESOURCES.map(({ key, label }) => {
                const level = getPermissionLevel(localRoles, key);
                const isSnapshotResource = key === "snapshot";

                const handleChange = (val: string) => {
                  setLocalRoles((prev) => {
                    let updated = applyPermissionChange(prev, key, val as PermissionLevel);

                    if (key === "devices") {
                      updated = applyPermissionChange(
                        updated,
                        "vehicles",
                        val as PermissionLevel,
                      );
                    }

                    return updated;
                  });
                };

                const isDevicesResource = key === "devices";

                const handleSnapshotCreateChange = (checked: boolean) => {
                  if (!isSnapshotResource) {
                    return;
                  }
                  setLocalRoles((prev) => {
                    const withoutSnapshotCreate = prev.filter(
                      (role) => role !== "snapshot_create"
                    );
                    return checked
                      ? [...withoutSnapshotCreate, "snapshot_create"]
                      : withoutSnapshotCreate;
                  });
                };

                const handleMaintenanceChange = (checked: boolean) => {
                  setLocalRoles((prev) => {
                    const without = prev.filter((r) => r !== "devices_maintenance_rw");
                    return checked ? [...without, "devices_maintenance_rw"] : without;
                  });
                };

                return (
                  <TableRow key={key} hover>
                    <TableCell>{label}</TableCell>
                    <TableCell align="center" padding="checkbox">
                      <RadioGroup
                        row
                        value={level}
                        onChange={(e) => handleChange(e.target.value)}
                        sx={{ justifyContent: "center", flexWrap: "nowrap" }}
                      >
                        <Radio value="none" size="small" />
                      </RadioGroup>
                    </TableCell>
                    <TableCell align="center" padding="checkbox">
                      {isSnapshotResource ? (
                        <Typography variant="body2" color="text.secondary">
                          -
                        </Typography>
                      ) : (
                        <RadioGroup
                          row
                          value={level}
                          onChange={(e) => handleChange(e.target.value)}
                          sx={{ justifyContent: "center", flexWrap: "nowrap" }}
                        >
                          <Radio value="ro" size="small" />
                        </RadioGroup>
                      )}
                    </TableCell>
                    <TableCell align="center" padding="checkbox">
                      <RadioGroup
                        row
                        value={level}
                        onChange={(e) => handleChange(e.target.value)}
                        sx={{ justifyContent: "center", flexWrap: "nowrap" }}
                      >
                        <Radio value="rw" size="small" />
                      </RadioGroup>
                    </TableCell>
                    <TableCell align="center" padding="checkbox">
                      {isSnapshotResource ? (
                        <Checkbox
                          checked={localRoles.includes("snapshot_create")}
                          onChange={(e) =>
                            handleSnapshotCreateChange(e.target.checked)
                          }
                          size="small"
                          title="Разрешает создавать новые снапшоты"
                        />
                      ) : isDevicesResource ? (
                        <Box sx={{ display: "flex", gap: 0.5, justifyContent: "center" }}>
                          <Checkbox
                            checked={localRoles.includes("devices_maintenance_rw")}
                            onChange={(e) => handleMaintenanceChange(e.target.checked)}
                            size="small"
                            title="Техническое обслуживание (ТО)"
                          />
                        </Box>
                      ) : (
                        <Typography variant="body2" color="text.secondary">
                          -
                        </Typography>
                      )}
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </Box>
      </section>

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

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