import { formatMillis } from "@/shared/utils/time.js";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { agencyStatusFilters } from "@/features/host-org/constants.js";
import { HostOrgEntity, HostOrgPerson, hostOrgRegionName } from "@/features/host-org/components/HostOrgIdentity.jsx";
import { HostOrgTable } from "@/features/host-org/components/HostOrgTable.jsx";
import { useHostManagersPage } from "@/features/host-org/hooks/useHostManagersPage.js";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import styles from "@/features/host-org/host-org.module.css";

const managerColumns = [
    {
        key: "ownerUserId",
        label: "经理",
        render: (item) => <ManagerUser item={item} />,
        width: "minmax(220px, 1.25fr)",
    },
    {
        key: "agency",
        label: "Agency",
        render: (item) => <HostOrgEntity id={item.agencyId} name={item.name} prefix="Agency " />,
        width: "minmax(190px, 1fr)",
    },
    {
        key: "parentBdUserId",
        label: "上级 BD",
        render: (item) => <ParentBD item={item} />,
        width: "minmax(220px, 1.2fr)",
    },
    {
        key: "regionId",
        label: "区域",
        render: (item, _index, context) => hostOrgRegionName(item, context?.regionOptions),
        width: "minmax(130px, 0.75fr)",
    },
    {
        key: "status",
        label: "状态",
        render: (item, _index, context) => <ManagerStatusSwitch item={item} page={context?.page} />,
        width: "minmax(90px, 0.7fr)",
    },
    {
        key: "joinEnabled",
        label: "入会",
        render: (item) => (
            <span className={item.joinEnabled ? styles.positive : styles.negative}>
                {item.joinEnabled ? "允许" : "禁止"}
            </span>
        ),
        width: "minmax(80px, 0.6fr)",
    },
    { key: "maxHosts", label: "最大主播数", width: "minmax(100px, 0.7fr)" },
    {
        key: "updatedAtMs",
        label: "更新时间",
        render: (item) => formatMillis(item.updatedAtMs),
        width: "minmax(170px, 1fr)",
    },
];

export function HostManagersPage() {
    const page = useHostManagersPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const columns = managerColumns.map((column) => {
        if (column.key === "ownerUserId") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索经理、Agency、用户",
                    value: page.query,
                    onChange: page.changeQuery,
                }),
            };
        }
        if (column.key === "parentBdUserId") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索上级 BD 用户 ID",
                    value: page.parentBdUserId,
                    onChange: page.changeParentBdUserId,
                }),
            };
        }
        if (column.key === "status") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: agencyStatusFilters,
                    placeholder: "搜索状态",
                    value: page.status,
                    onChange: page.changeStatus,
                }),
            };
        }
        return column;
    });

    return (
        <section className={styles.root}>
            <div className={styles.contentPanel}>
                <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                    <div className={styles.listBlock}>
                        <HostOrgTable
                            columns={columns}
                            context={{ page, regionOptions: page.regionOptions }}
                            items={items}
                            minWidth="1250px"
                            pagination={
                                total > 0
                                    ? {
                                          page: page.page,
                                          pageSize: page.data.pageSize || 50,
                                          total,
                                          onPageChange: page.setPage,
                                      }
                                    : undefined
                            }
                            rowKey={(item) => `manager-${item.ownerUserId || item.agencyId}`}
                        />
                    </div>
                </DataState>
            </div>
        </section>
    );
}

function ManagerUser({ item }) {
    return (
        <HostOrgPerson
            avatar={item.ownerAvatar}
            displayUserId={item.ownerDisplayUserId}
            fallbackId={item.ownerUserId}
            username={item.ownerUsername}
        />
    );
}

function ParentBD({ item }) {
    if (!item.parentBdUserId) {
        return "-";
    }
    return (
        <HostOrgPerson
            avatar={item.parentBdAvatar}
            displayUserId={item.parentBdDisplayUserId}
            fallbackId={item.parentBdUserId}
            username={item.parentBdUsername || "BD"}
        />
    );
}

function ManagerStatusSwitch({ item, page }) {
    const active = item.status === "active";
    return (
        <AdminSwitch
            checked={active}
            disabled={!active || !page?.abilities.canStatus || page.loadingAction === `manager-status-${item.agencyId}`}
            inputProps={{ "aria-label": active ? "停用经理" : "经理已停用" }}
            onChange={(event) => {
                if (!event.target.checked) {
                    page.closeManagerAgency(item);
                }
            }}
        />
    );
}
