import EditOutlined from "@mui/icons-material/EditOutlined";
import GppBadOutlined from "@mui/icons-material/GppBadOutlined";
import TrendingUpOutlined from "@mui/icons-material/TrendingUpOutlined";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import MenuItem from "@mui/material/MenuItem";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useCallback, useMemo, useState } from "react";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { banUser, grantUserVip, listUsers, updateUser, updateUserLevels } from "../api/business.js";
import { useExternalAuth } from "../auth/ExternalAuthProvider.jsx";
import { UserBanDialog, UserEditDialog, UserLevelDialog } from "../components/UserDialogs.jsx";
import { hasExternalCapability } from "../config/capabilities.js";
import { useExternalI18n } from "../i18n/ExternalI18nProvider.jsx";
import { translateExternalError } from "../i18n/errors.js";
import { ExternalPage, ExternalPageState, PagePagination, ResponsiveDataList, StatusChip } from "../shared/PageComponents.jsx";
import { usePagedResource } from "../shared/usePagedResource.js";

export default function UsersPage() {
  const { session } = useExternalAuth();
  const { showToast } = useToast();
  const { t } = useExternalI18n();
  const [filters, setFilters] = useState({ keyword: "", status: "" });
  const [query, setQuery] = useState({ keyword: "", page: 1, status: "" });
  const [dialog, setDialog] = useState({ type: "", user: null });
  const [submitting, setSubmitting] = useState(false);
  const load = useCallback(() => listUsers({ keyword: query.keyword, page: query.page, page_size: 20, status: query.status }), [query]);
  const { data, error, loading, reload } = usePagedResource(load);
  const canEdit = hasExternalCapability(session, "user:update");
  const canBan = hasExternalCapability(session, "user:ban");
  const canGrantLevel = hasExternalCapability(session, "user-level:grant");

  const closeDialog = () => setDialog({ type: "", user: null });
  const execute = async (request, successKey) => {
    setSubmitting(true);
    try {
      await request();
      showToast(t(successKey), "success");
      closeDialog();
      reload();
    } catch (requestError) {
      showToast(translateExternalError(requestError, t, "users.operationFailed"), "error");
    } finally {
      setSubmitting(false);
    }
  };

  const columns = useMemo(() => [
    { key: "user", label: t("common.user"), render: (user) => <Stack direction="row" spacing={1} sx={{ alignItems: "center" }}><Avatar src={user.avatar}>{(user.username || "-").slice(0, 1)}</Avatar><Box><Typography fontWeight={650}>{user.username || "-"}</Typography><Typography color="text.secondary" variant="caption">ID {user.id}</Typography></Box></Stack> },
    { key: "prettyId", label: t("users.prettyId"), render: (user) => user.prettyId || "-" },
    { key: "country", label: t("users.countryGender"), render: (user) => `${user.country || "-"} / ${translatedGender(user.gender, t)}` },
    { key: "level", label: t("users.level"), render: (user) => t("users.levelSummary", { wealth: user.wealthLevel, charm: user.charmLevel, vip: user.vipLevel }) },
    { key: "status", label: t("common.status"), render: (user) => <StatusChip status={user.banned ? "banned" : user.status} /> },
    { key: "actions", label: t("common.actions"), render: (user) => <Stack direction="row" sx={{ flexWrap: "wrap", gap: 0.5 }}>{canEdit ? <Button onClick={() => setDialog({ type: "edit", user })} startIcon={<EditOutlined />}>{t("users.edit")}</Button> : null}{canGrantLevel ? <Button onClick={() => setDialog({ type: "level", user })} startIcon={<TrendingUpOutlined />}>{t("users.grantLevel")}</Button> : null}{canBan && !user.banned ? <Button color="error" onClick={() => setDialog({ type: "ban", user })} startIcon={<GppBadOutlined />}>{t("users.ban")}</Button> : null}</Stack> }
  ], [canBan, canEdit, canGrantLevel, t]);

  return (
    <ExternalPage title={t("users.title")}>
      <Stack className="external-filter-bar" component="form" direction={{ xs: "column", sm: "row" }} spacing={1.5} onSubmit={(event) => { event.preventDefault(); setQuery({ ...filters, page: 1 }); }}>
        <TextField label={t("users.search")} value={filters.keyword} onChange={(event) => setFilters({ ...filters, keyword: event.target.value })} />
        <TextField label={t("common.status")} select value={filters.status} onChange={(event) => setFilters({ ...filters, status: event.target.value })}><MenuItem value="">{t("common.allStatuses")}</MenuItem><MenuItem value="active">{t("common.normal")}</MenuItem><MenuItem value="banned">{t("common.banned")}</MenuItem></TextField>
        <Button type="submit" variant="contained">{t("common.query")}</Button>
      </Stack>
      <ExternalPageState error={error} loading={loading} onRetry={reload} />
      {!loading && !error ? <><ResponsiveDataList columns={columns} items={data.items} rowKey={(item) => item.id} /><PagePagination {...data} onChange={(page) => setQuery({ ...query, page })} /></> : null}
      <UserEditDialog loading={submitting} open={dialog.type === "edit"} user={dialog.user} onClose={closeDialog} onSubmit={(form) => execute(() => updateUser(dialog.user.id, form), "users.updated")} />
      <UserBanDialog loading={submitting} open={dialog.type === "ban"} user={dialog.user} onClose={closeDialog} onSubmit={(form) => execute(() => banUser(dialog.user.id, { expires_at_ms: Number(form.days) === 0 ? 0 : Date.now() + Number(form.days) * 86400000, reason: form.reason.trim() }), "users.banned")} />
      <UserLevelDialog loading={submitting} open={dialog.type === "level"} user={dialog.user} onClose={closeDialog} onSubmit={(form) => execute(() => form.track === "vip"
        ? grantUserVip(dialog.user.id, { commandId: createLevelCommandId(), durationMs: Number(form.days) * 86400000, level: Number(form.level), reason: form.reason.trim() })
        : updateUserLevels(dialog.user.id, { adjustments: [{ duration_days: Number(form.days), level: Number(form.level), track: form.track }], reason: form.reason.trim() }), "users.levelGranted")} />
    </ExternalPage>
  );
}

function translatedGender(gender, t) {
  const key = { female: "users.genderFemale", male: "users.genderMale", unknown: "users.genderUnknown" }[String(gender || "").toLowerCase()];
  return key ? t(key) : "-";
}

function createLevelCommandId() {
  return `external-level-grant-${globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}`}`;
}
