import LockOpenOutlined from "@mui/icons-material/LockOpenOutlined";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
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 { listBannedUsers, unbanUser } from "../api/business.js";
import { useExternalAuth } from "../auth/ExternalAuthProvider.jsx";
import { hasExternalCapability } from "../config/capabilities.js";
import { useExternalI18n } from "../i18n/ExternalI18nProvider.jsx";
import { translateExternalError } from "../i18n/errors.js";
import { ConfirmDialog } from "../shared/ConfirmDialog.jsx";
import { ExternalPage, ExternalPageState, PagePagination, ResponsiveDataList, StatusChip } from "../shared/PageComponents.jsx";
import { usePagedResource } from "../shared/usePagedResource.js";

export default function BansPage() {
  const { session } = useExternalAuth();
  const { showToast } = useToast();
  const { t } = useExternalI18n();
  const [keyword, setKeyword] = useState("");
  const [query, setQuery] = useState({ keyword: "", page: 1 });
  const [target, setTarget] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const load = useCallback(() => listBannedUsers({ keyword: query.keyword, page: query.page, page_size: 20 }), [query]);
  const { data, error, loading, reload } = usePagedResource(load);
  const canUnban = hasExternalCapability(session, "user:unban");

  const handleUnban = async () => {
    setSubmitting(true);
    try {
      await unbanUser(target.id, { reason: "external-admin manual unban" });
      showToast(t("bans.unbanned"), "success");
      setTarget(null);
      reload();
    } catch (requestError) {
      showToast(translateExternalError(requestError, t, "bans.unbanFailed"), "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: "reason", label: t("bans.reason"), render: (user) => user.reason || "-" },
    { key: "status", label: t("common.status"), render: () => <StatusChip status="banned" /> },
    { key: "actions", label: t("common.actions"), render: (user) => canUnban ? <Button onClick={() => setTarget(user)} startIcon={<LockOpenOutlined />}>{t("bans.unban")}</Button> : "-" }
  ], [canUnban, t]);

  return (
    <ExternalPage title={t("bans.title")}>
      <Stack className="external-filter-bar" component="form" direction={{ xs: "column", sm: "row" }} spacing={1.5} onSubmit={(event) => { event.preventDefault(); setQuery({ keyword, page: 1 }); }}>
        <TextField label={t("users.search")} value={keyword} onChange={(event) => setKeyword(event.target.value)} />
        <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}
      <ConfirmDialog confirmColor="primary" content={t("bans.confirmContent", { user: target?.prettyId || target?.username || "" })} loading={submitting} open={Boolean(target)} title={t("bans.confirmTitle")} onClose={() => setTarget(null)} onConfirm={handleUnban} />
    </ExternalPage>
  );
}
