import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { formatMillis } from "@/shared/utils/time.js";
import { DataState } from "@/shared/ui/DataState.jsx";
import { hostSourceLabels, hostStatusFilters } from "@/features/host-org/constants.js";
import { HostOrgPerson, hostOrgRegionName } from "@/features/host-org/components/HostOrgIdentity.jsx";
import { HostOrgSortHeader } from "@/features/host-org/components/HostOrgSortHeader.jsx";
import { SalaryWalletAdjustButton, SalaryWalletCell } from "@/features/host-org/components/SalaryWalletControls.jsx";
import { HostOrgTable } from "@/features/host-org/components/HostOrgTable.jsx";
import { useHostHostsPage } from "@/features/host-org/hooks/useHostHostsPage.js";
import { AdminRowActions } from "@/shared/ui/AdminListLayout.jsx";
import { createOptionsColumnFilter, createTextColumnFilter, createUserIdentityColumnFilter } from "@/shared/ui/tableFilters.js";
import styles from "@/features/host-org/host-org.module.css";

const hostColumns = [
    {
        key: "user",
        label: "用户",
        render: (item) => <HostUser item={item} />,
        width: "minmax(220px, 1.25fr)",
    },
    {
        key: "status",
        label: "状态",
        render: (item) => <HostStatusSwitch item={item} />,
        width: "minmax(90px, 0.7fr)",
    },
    {
        key: "contact",
        label: "联系方式",
        render: (item) => item.contact || "-",
        width: "minmax(150px, 0.85fr)",
    },
    {
        key: "diamond",
        label: "钻石",
        sortable: true,
        sortField: "diamond",
        render: (item) => formatNumber(item.diamond),
        width: "minmax(110px, 0.7fr)",
    },
    {
        key: "salaryWallet",
        label: "工资钱包",
        sortable: true,
        sortField: "salary_wallet",
        render: (item) => (
            <SalaryWalletCell
                role="host"
                userId={item.userId}
                userLabel={hostUserLabel(item)}
                wallet={item.salaryWallet}
            />
        ),
        width: "minmax(140px, 0.85fr)",
    },
    {
        key: "regionId",
        label: "区域",
        render: (item, _index, context) => hostOrgRegionName(item, context?.regionOptions),
        width: "minmax(130px, 0.75fr)",
    },
    {
        key: "currentAgencyId",
        label: "当前 Agency",
        render: (item) => <CurrentAgencyOwner item={item} />,
        width: "minmax(220px, 1.1fr)",
    },
    {
        key: "source",
        label: "来源",
        render: (item) => hostSourceLabels[item.source] || item.source || "-",
        width: "minmax(150px, 1fr)",
    },
    {
        key: "firstBecameHostAtMs",
        label: "首次成为主播",
        render: (item) => formatMillis(item.firstBecameHostAtMs),
        width: "minmax(170px, 1fr)",
    },
    {
        key: "updatedAtMs",
        label: "更新时间",
        render: (item) => formatMillis(item.updatedAtMs),
        width: "minmax(170px, 1fr)",
    },
];

export function HostHostsPage() {
    const page = useHostHostsPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const columns = [
        ...hostColumns,
        page.abilities.canSalaryAdjust
            ? {
                  key: "actions",
                  label: "操作",
                  render: (item, _index, context) => <HostActions item={item} page={context?.page} />,
                  width: "minmax(80px, 0.45fr)",
              }
            : null,
    ]
        .filter(Boolean)
        .map((column) => {
            if (column.key === "user") {
                return {
                    ...column,
                    filter: createUserIdentityColumnFilter({
                        value: page.userFilter,
                        onChange: page.changeUserFilter,
                    }),
                };
            }
            if (column.key === "currentAgencyId") {
                return {
                    ...column,
                    filter: createTextColumnFilter({
                        placeholder: "搜索 Agency ID",
                        value: page.agencyId,
                        onChange: page.changeAgencyId,
                    }),
                };
            }
            if (column.key === "status") {
                return {
                    ...column,
                    filter: createOptionsColumnFilter({
                        options: hostStatusFilters,
                        placeholder: "搜索状态",
                        value: page.status,
                        onChange: page.changeStatus,
                    }),
                };
            }
            if (column.key === "diamond") {
                return {
                    ...column,
                    header: (
                        <HostOrgSortHeader
                            field={column.sortField}
                            label={column.label}
                            sortBy={page.sortBy}
                            sortDirection={page.sortDirection}
                            onToggle={page.changeSort}
                        />
                    ),
                };
            }
            if (column.sortable) {
                return {
                    ...column,
                    header: (
                        <HostOrgSortHeader
                            field={column.sortField}
                            label={column.label}
                            sortBy={page.sortBy}
                            sortDirection={page.sortDirection}
                            onToggle={page.changeSort}
                        />
                    ),
                };
            }
            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="1420px"
                            pagination={
                                total > 0
                                    ? {
                                          page: page.page,
                                          pageSize: page.data.pageSize || 50,
                                          total,
                                          onPageChange: page.setPage,
                                      }
                                    : undefined
                            }
                            rowKey={(item) => item.userId}
                        />
                    </div>
                </DataState>
            </div>
        </section>
    );
}

function formatNumber(value) {
    return Number(value || 0).toLocaleString("zh-CN");
}

function HostUser({ item }) {
    return (
        <HostOrgPerson
            avatar={item.avatar}
            displayUserId={item.displayUserId}
            fallbackId={item.userId}
            username={item.username}
        />
    );
}

function CurrentAgencyOwner({ item }) {
    if (
        !item.currentAgencyId &&
        !item.currentAgencyOwnerUserId &&
        !item.currentAgencyOwnerDisplayUserId &&
        !item.currentAgencyOwnerUsername
    ) {
        return "-";
    }
    return (
        <HostOrgPerson
            avatar={item.currentAgencyOwnerAvatar}
            displayUserId={item.currentAgencyOwnerDisplayUserId}
            fallbackId={item.currentAgencyOwnerUserId}
            username={item.currentAgencyOwnerUsername || item.currentAgencyName}
        />
    );
}

function HostStatusSwitch({ item }) {
    return (
        <AdminSwitch
            checked={item.status === "active"}
            disabled
            inputProps={{ "aria-label": item.status === "active" ? "主播已启用" : "主播已停用" }}
        />
    );
}

function HostActions({ item, page }) {
    return (
        <AdminRowActions>
            <SalaryWalletAdjustButton
                role="host"
                userId={item.userId}
                userLabel={hostUserLabel(item)}
                onAdjusted={page?.reload}
            />
        </AdminRowActions>
    );
}

function hostUserLabel(item) {
    return item.displayUserId || item.username || item.userId;
}
