import Add from "@mui/icons-material/Add";
import SyncAltOutlined from "@mui/icons-material/SyncAltOutlined";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { formatMillis } from "@/shared/utils/time.js";
import { DataState } from "@/shared/ui/DataState.jsx";
import { PaginationBar } from "@/shared/ui/PaginationBar.jsx";
import { bdStatusFilters } from "@/features/host-org/constants.js";
import { HostOrgActionModal } from "@/features/host-org/components/HostOrgActionModal.jsx";
import { HostOrgPerson, hostOrgRegionName } from "@/features/host-org/components/HostOrgIdentity.jsx";
import { HostOrgStatus } from "@/features/host-org/components/HostOrgStatus.jsx";
import { HostOrgTable } from "@/features/host-org/components/HostOrgTable.jsx";
import { HostOrgToolbar } from "@/features/host-org/components/HostOrgToolbar.jsx";
import { useHostBdsPage } from "@/features/host-org/hooks/useHostBdsPage.js";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import styles from "@/features/host-org/host-org.module.css";

const bdColumns = [
    {
        key: "user",
        label: "用户",
        render: (item) => <BDUser item={item} />,
        width: "minmax(220px, 1.25fr)",
    },
    { key: "role", label: "角色", width: "minmax(100px, 0.65fr)" },
    {
        key: "parentLeaderUserId",
        label: "上级 Leader",
        render: (item) => <ParentLeader item={item} />,
        width: "minmax(220px, 1.25fr)",
    },
    {
        key: "regionId",
        label: "区域",
        render: (item, _index, context) => hostOrgRegionName(item, context?.regionOptions),
        width: "minmax(130px, 0.75fr)",
    },
    {
        key: "status",
        label: "状态",
        render: (item) => <HostOrgStatus value={item.status} />,
        width: "minmax(90px, 0.7fr)",
    },
    {
        key: "createdByUserId",
        label: "创建人",
        render: (item) => <Creator item={item} />,
        width: "minmax(180px, 1fr)",
    },
    {
        key: "createdAtMs",
        label: "创建时间",
        render: (item) => formatMillis(item.createdAtMs),
        width: "minmax(170px, 1fr)",
    },
    {
        key: "updatedAtMs",
        label: "更新时间",
        render: (item) => formatMillis(item.updatedAtMs),
        width: "minmax(170px, 1fr)",
    },
];

export function HostBdsPage() {
    const page = useHostBdsPage({ profileType: "bd" });
    const createDisabled = !page.abilities.canCreate;
    const updateDisabled = !page.abilities.canUpdate;
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const toolbarActions = [
        page.abilities.canUpdate
            ? { icon: <SyncAltOutlined fontSize="small" />, label: "BD 状态", onClick: page.openBDStatusForm }
            : null,
        page.abilities.canCreate
            ? { icon: <Add fontSize="small" />, label: "创建 BD", onClick: page.openBDForm, variant: "primary" }
            : null,
    ].filter(Boolean);
    const columns = bdColumns.map((column) => {
        if (column.key === "user") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索用户 ID、展示 ID、用户名",
                    value: page.query,
                    onChange: page.changeQuery,
                }),
            };
        }
        if (column.key === "parentLeaderUserId") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索 Leader 用户 ID",
                    value: page.parentLeaderUserId,
                    onChange: page.changeParentLeaderUserId,
                }),
            };
        }
        if (column.key === "status") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: bdStatusFilters,
                    placeholder: "搜索状态",
                    value: page.status,
                    onChange: page.changeStatus,
                }),
            };
        }
        return column;
    });

    return (
        <section className={styles.root}>
            <div className={styles.contentPanel}>
                <HostOrgToolbar
                    actions={toolbarActions}
                    filters={{
                        extraFilters: [
                            {
                                label: "上级 Leader 用户 ID",
                                name: "parentLeaderUserId",
                                onChange: page.changeParentLeaderUserId,
                                value: page.parentLeaderUserId,
                            },
                        ],
                        loadingRegions: page.loadingRegions,
                        query: page.query,
                        regionId: page.regionId,
                        regionOptions: page.regionOptions,
                        searchPlaceholder: "搜索用户 ID、展示 ID、用户名...",
                        status: page.status,
                        statusOptions: bdStatusFilters,
                        onQueryChange: page.changeQuery,
                        onRegionIdChange: page.changeRegionId,
                        onReset: page.resetFilters,
                        onStatusChange: page.changeStatus,
                    }}
                />

                <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                    <div className={styles.listBlock}>
                        <HostOrgTable
                            columns={columns}
                            context={{ regionOptions: page.regionOptions }}
                            items={items}
                            minWidth="1260px"
                            rowKey={(item) => `bd-${item.userId}`}
                        />
                        {total > 0 ? (
                            <PaginationBar
                                page={page.page}
                                pageSize={page.data.pageSize || 10}
                                total={total}
                                onPageChange={page.setPage}
                            />
                        ) : null}
                    </div>
                </DataState>
            </div>

            <HostOrgActionModal
                disabled={createDisabled}
                loading={page.loadingAction === "bd"}
                open={page.activeAction === "bd"}
                onClose={page.closeAction}
                onSubmit={page.submitBD}
                title="创建 BD"
            >
                <TextField
                    disabled={createDisabled}
                    label="用户短 ID"
                    required
                    type="number"
                    value={page.bdForm.targetUserId}
                    onChange={(event) => page.setBDForm({ ...page.bdForm, targetUserId: event.target.value })}
                />
                <TextField
                    disabled={createDisabled}
                    label="上级 Leader 短 ID"
                    required
                    type="number"
                    value={page.bdForm.parentLeaderUserId}
                    onChange={(event) => page.setBDForm({ ...page.bdForm, parentLeaderUserId: event.target.value })}
                />
                <TextField
                    disabled={createDisabled}
                    label="原因"
                    multiline
                    minRows={2}
                    value={page.bdForm.reason}
                    onChange={(event) => page.setBDForm({ ...page.bdForm, reason: event.target.value })}
                />
            </HostOrgActionModal>

            <HostOrgActionModal
                disabled={updateDisabled}
                loading={page.loadingAction === "bd-status"}
                open={page.activeAction === "bd-status"}
                onClose={page.closeAction}
                onSubmit={page.submitBDStatus}
                title="BD 状态"
            >
                <TextField
                    disabled={updateDisabled}
                    label="用户 ID"
                    required
                    type="number"
                    value={page.bdStatusForm.targetUserId}
                    onChange={(event) =>
                        page.setBDStatusForm({ ...page.bdStatusForm, targetUserId: event.target.value })
                    }
                />
                <TextField
                    disabled={updateDisabled}
                    label="状态"
                    required
                    select
                    value={page.bdStatusForm.status}
                    onChange={(event) => page.setBDStatusForm({ ...page.bdStatusForm, status: event.target.value })}
                >
                    <MenuItem value="active">启用</MenuItem>
                    <MenuItem value="disabled">停用</MenuItem>
                </TextField>
                <TextField
                    disabled={updateDisabled}
                    label="原因"
                    multiline
                    minRows={2}
                    value={page.bdStatusForm.reason}
                    onChange={(event) => page.setBDStatusForm({ ...page.bdStatusForm, reason: event.target.value })}
                />
            </HostOrgActionModal>
        </section>
    );
}

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

function ParentLeader({ item }) {
    if (!item.parentLeaderUserId) {
        return "-";
    }
    return (
        <HostOrgPerson
            avatar={item.parentLeaderAvatar}
            displayUserId={item.parentLeaderDisplayUserId}
            fallbackId={item.parentLeaderUserId}
            username={item.parentLeaderUsername || "Leader"}
        />
    );
}

function Creator({ item }) {
    if (!item.createdByUserId && !item.createdByDisplayUserId && !item.createdByUsername) {
        return "-";
    }
    return (
        <HostOrgPerson
            avatar={item.createdByAvatar}
            displayUserId={item.createdByDisplayUserId}
            fallbackId={item.createdByUserId}
            username={item.createdByUsername || "创建人"}
        />
    );
}
