import Add from "@mui/icons-material/Add";
import EditOutlined from "@mui/icons-material/EditOutlined";
import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { formatMillis } from "@/shared/utils/time.js";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { IconButton } from "@/shared/ui/IconButton.jsx";
import { managerStatusFilters } 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 { HostOrgTable } from "@/features/host-org/components/HostOrgTable.jsx";
import { HostOrgToolbar } from "@/features/host-org/components/HostOrgToolbar.jsx";
import { useHostManagersPage } from "@/features/host-org/hooks/useHostManagersPage.js";
import { createOptionsColumnFilter, createUserIdentityColumnFilter } from "@/shared/ui/tableFilters.js";
import styles from "@/features/host-org/host-org.module.css";

const managerPermissionOptions = [
    { key: "canGrantAvatarFrame", label: "头像框" },
    { key: "canGrantVehicle", label: "Car" },
    { key: "canGrantBadge", label: "徽章" },
    { key: "canUpdateUserLevel", label: "升级等级" },
    { key: "canAddBdLeader", label: "BD Leader" },
    { key: "canAddAdmin", label: "Admin" },
    { key: "canAddSuperadmin", label: "Superadmin" },
    { key: "canBlockUser", label: "Block User" },
    { key: "canTransferUserCountry", label: "转移国家" },
];

const managerColumns = [
    {
        key: "userId",
        label: "经理",
        render: (item) => <ManagerUser item={item} />,
        width: "minmax(220px, 1.25fr)",
    },
    {
        key: "regionId",
        label: "区域",
        render: (item, _index, context) => hostOrgRegionName(item, context?.regionOptions),
        width: "minmax(130px, 0.75fr)",
    },
    {
        key: "contact",
        label: "联系方式",
        render: (item) => item.contact || "-",
        width: "minmax(150px, 0.85fr)",
    },
    {
        key: "permissions",
        label: "权限详情",
        render: (item) => <ManagerPermissions item={item} />,
        width: "minmax(270px, 1.35fr)",
    },
    {
        key: "status",
        label: "状态",
        render: (item, _index, context) => <ManagerStatusSwitch item={item} page={context?.page} />,
        width: "minmax(90px, 0.7fr)",
    },
    {
        key: "bdLeaderCount",
        label: "BD Leader/Admin",
        render: (item) => item.bdLeaderCount || 0,
        width: "minmax(140px, 0.8fr)",
    },
    {
        key: "lastInvitedAtMs",
        label: "最近邀请",
        render: (item) => formatMillis(item.lastInvitedAtMs),
        width: "minmax(170px, 1fr)",
    },
    {
        key: "updatedAtMs",
        label: "更新时间",
        render: (item) => formatMillis(item.updatedAtMs),
        width: "minmax(170px, 1fr)",
    },
    {
        key: "actions",
        label: "操作",
        render: (item, _index, context) => <ManagerActions item={item} page={context?.page} />,
        resizable: false,
        width: "88px",
    },
];

export function HostManagersPage() {
    const page = useHostManagersPage();
    const isEditing = page.activeAction === "manager-edit";
    const formDisabled = isEditing ? !page.abilities.canUpdate : !page.abilities.canCreate;
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const toolbarActions = [
        page.abilities.canCreate
            ? { icon: <Add fontSize="small" />, label: "添加经理", onClick: page.openManagerForm, variant: "primary" }
            : null,
    ].filter(Boolean);
    const columns = managerColumns.map((column) => {
        if (column.key === "userId") {
            return {
                ...column,
                filter: createUserIdentityColumnFilter({
                    value: page.userFilter,
                    onChange: page.changeUserFilter,
                }),
            };
        }
        if (column.key === "status") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: managerStatusFilters,
                    placeholder: "搜索状态",
                    value: page.status,
                    onChange: page.changeStatus,
                }),
            };
        }
        return column;
    });

    return (
        <section className={styles.root}>
            <div className={styles.contentPanel}>
                <HostOrgToolbar leadingActions={toolbarActions} />
                <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="1640px"
                            pagination={
                                total > 0
                                    ? {
                                          page: page.page,
                                          pageSize: page.data.pageSize || 50,
                                          total,
                                          onPageChange: page.setPage,
                                      }
                                    : undefined
                            }
                            rowKey={(item) => `manager-${item.userId}`}
                        />
                    </div>
                </DataState>
            </div>
            <HostOrgActionModal
                disabled={formDisabled}
                loading={["manager-create", "manager-update"].includes(page.loadingAction)}
                open={page.activeAction === "manager" || page.activeAction === "manager-edit"}
                sectionTitle="经理信息"
                onClose={page.closeAction}
                onSubmit={page.submitManager}
                title={isEditing ? "编辑经理权限" : "添加经理"}
            >
                <TextField
                    disabled={formDisabled || isEditing}
                    label="用户短 ID"
                    required
                    type="number"
                    value={page.managerForm.targetUserId}
                    onChange={(event) => page.setManagerForm({ ...page.managerForm, targetUserId: event.target.value })}
                />
                <TextField
                    disabled={formDisabled}
                    label="联系方式"
                    value={page.managerForm.contact}
                    onChange={(event) => page.setManagerForm({ ...page.managerForm, contact: event.target.value })}
                />
                <PermissionSwitchGrid disabled={formDisabled} form={page.managerForm} onChange={page.setManagerForm} />
            </HostOrgActionModal>
        </section>
    );
}

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

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

function ManagerPermissions({ item }) {
    return (
        <div className={styles.permissionList}>
            {managerPermissionOptions.map((permission) => {
                const enabled = item?.[permission.key] !== false;
                return (
                    <span
                        className={
                            enabled ? styles.permissionPill : `${styles.permissionPill} ${styles.permissionPillOff}`
                        }
                        key={permission.key}
                    >
                        {permission.label}
                        <span>{enabled ? "开" : "关"}</span>
                    </span>
                );
            })}
        </div>
    );
}

function ManagerActions({ item, page }) {
    const disabled = !page?.abilities?.canUpdate;
    return (
        <div className={styles.rowActions}>
            <Tooltip title={disabled ? "无编辑权限" : "编辑权限"}>
                <span>
                    <IconButton disabled={disabled} label="编辑权限" onClick={() => page.openManagerEdit(item)}>
                        <EditOutlined fontSize="small" />
                    </IconButton>
                </span>
            </Tooltip>
        </div>
    );
}

function PermissionSwitchGrid({ disabled, form, onChange }) {
    return (
        <div className={styles.permissionGrid}>
            {managerPermissionOptions.map((permission) => (
                <label className={styles.permissionSwitch} key={permission.key}>
                    <span>{permission.label}</span>
                    <AdminSwitch
                        checked={form?.[permission.key] !== false}
                        checkedLabel="开"
                        disabled={disabled}
                        label={permission.label}
                        uncheckedLabel="关"
                        onChange={(event) => onChange({ ...form, [permission.key]: event.target.checked })}
                    />
                </label>
            ))}
        </div>
    );
}
