import EditOutlined from "@mui/icons-material/EditOutlined";
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 { listRooms, updateRoom } from "../api/business.js";
import { useExternalAuth } from "../auth/ExternalAuthProvider.jsx";
import { RoomEditDialog } from "../components/RoomEditDialog.jsx";
import { hasExternalCapability } from "../config/capabilities.js";
import { useExternalI18n } from "../i18n/ExternalI18nProvider.jsx";
import { externalUiError, translateExternalError } from "../i18n/errors.js";
import { ExternalPage, ExternalPageState, PagePagination, ResponsiveDataList, StatusChip } from "../shared/PageComponents.jsx";
import { usePagedResource } from "../shared/usePagedResource.js";

export default function RoomsPage() {
  const { session } = useExternalAuth();
  const { showToast } = useToast();
  const { t } = useExternalI18n();
  const [keyword, setKeyword] = useState("");
  const [query, setQuery] = useState({ keyword: "", page: 1 });
  const [room, setRoom] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const load = useCallback(() => listRooms({ keyword: query.keyword, page: query.page, page_size: 20 }), [query]);
  const { data, error, loading, reload } = usePagedResource(load);
  const canEdit = hasExternalCapability(session, "room:update");

  const columns = useMemo(() => [
    { key: "room", label: t("rooms.room"), render: (item) => <Stack direction="row" spacing={1} sx={{ alignItems: "center" }}><Avatar src={item.coverUrl} variant="rounded">R</Avatar><Box><Typography fontWeight={650}>{item.title || "-"}</Typography><Typography color="text.secondary" variant="caption">ID {item.id}</Typography></Box></Stack> },
    { key: "owner", label: t("rooms.owner"), render: (item) => item.ownerName || "-" },
    { key: "region", label: t("rooms.visibleRegion"), render: (item) => item.visibleRegionId || t("rooms.allRegions") },
    { key: "status", label: t("common.status"), render: (item) => <StatusChip status={item.status} /> },
    { key: "actions", label: t("common.actions"), render: (item) => canEdit ? <Button onClick={() => setRoom(item)} startIcon={<EditOutlined />}>{t("common.edit")}</Button> : "-" }
  ], [canEdit, t]);

  const submit = async (form) => {
    setSubmitting(true);
    try {
      const regionText = String(form.visibleRegionId || "").trim();
      const visibleRegionId = regionText ? Number(regionText) : 0;
      if (!Number.isSafeInteger(visibleRegionId) || visibleRegionId < 0) {
        throw externalUiError("errors.regionId");
      }
      await updateRoom(room.id, { ...form, visibleRegionId });
      showToast(t("rooms.updated"), "success");
      setRoom(null);
      reload();
    } catch (requestError) {
      showToast(translateExternalError(requestError, t, "rooms.updateFailed"), "error");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <ExternalPage title={t("rooms.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("rooms.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}
      <RoomEditDialog loading={submitting} open={Boolean(room)} room={room} onClose={() => setRoom(null)} onSubmit={submit} />
    </ExternalPage>
  );
}
