import AddOutlined from "@mui/icons-material/AddOutlined";
import CloudUploadOutlined from "@mui/icons-material/CloudUploadOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import {
    AdminActionIconButton,
    AdminFilterResetButton,
    AdminFilterSelect,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminSearchBox,
} from "@/shared/ui/AdminListLayout.jsx";
import { formatMillis } from "@/shared/utils/time.js";
import { PolicyInstanceDrawer } from "@/features/policy-config/components/PolicyInstanceDrawer.jsx";
import { PolicyRuleEditorDrawer } from "@/features/policy-config/components/PolicyRuleEditorDrawer.jsx";
import { usePolicyConfigPage } from "@/features/policy-config/hooks/usePolicyConfigPage.js";
import styles from "@/features/policy-config/policy-config.module.css";

const statusOptions = [
    ["", "全部状态"],
    ["active", "启用"],
    ["disabled", "停用"],
];

const templateColumns = [
    {
        key: "template",
        label: "模板",
        width: "minmax(320px, 1.2fr)",
        render: (item) => <TemplateIdentity item={item} />,
    },
    {
        key: "runtime",
        label: "核心运行字段",
        width: "minmax(240px, 0.9fr)",
        render: (item) => <TemplateRuntimeSummary item={item} />,
    },
    {
        key: "bd",
        label: "团队政策",
        width: "minmax(220px, 0.8fr)",
        render: (item) => <TeamPolicySummary item={item} />,
    },
    {
        key: "status",
        label: "状态",
        width: "120px",
        render: (item) => statusLabel(item.status),
    },
    {
        key: "updatedAt",
        label: "更新时间",
        width: "180px",
        render: (item) => formatMillis(item.updatedAtMs || item.createdAtMs),
    },
    {
        key: "actions",
        label: "操作",
        width: "96px",
        resizable: false,
    },
];

const instanceColumns = [
    {
        key: "instance",
        label: "实例",
        width: "minmax(300px, 1.1fr)",
        render: (item) => <InstanceIdentity item={item} />,
    },
    {
        key: "scope",
        label: "范围与时间",
        width: "minmax(260px, 0.9fr)",
        render: (item, _index, context) => <InstanceScope item={item} regionLabelMap={context.regionLabelMap} />,
    },
    {
        key: "publish",
        label: "发布",
        width: "minmax(220px, 0.85fr)",
        render: (item) => <PublishSummary item={item} />,
    },
    {
        key: "status",
        label: "状态",
        width: "120px",
    },
    {
        key: "updatedAt",
        label: "更新时间",
        width: "180px",
        render: (item) => formatMillis(item.updatedAtMs || item.createdAtMs),
    },
    {
        key: "actions",
        label: "操作",
        width: "144px",
        resizable: false,
    },
];

export function PolicyConfigPage() {
    const page = usePolicyConfigPage();
    return (
        <AdminListPage>
            <div className={styles.tabsBar}>
                <Tabs value={page.activeTab} onChange={(_, value) => page.setActiveTab(value)}>
                    <Tab className={styles.tab} label="模板规则" value="templates" />
                    <Tab className={styles.tab} label="App 实例" value="instances" />
                </Tabs>
            </div>
            {page.activeTab === "templates" ? <TemplatePanel page={page} /> : <InstancePanel page={page} />}
            <PolicyRuleEditorDrawer page={page} />
            <PolicyInstanceDrawer page={page} />
        </AdminListPage>
    );
}

function TemplatePanel({ page }) {
    const items = page.templates.data.items || [];
    const total = page.templates.data.total || 0;
    const columns = templateColumns.map((column) =>
        column.key === "actions"
            ? { ...column, render: (item) => <TemplateActions item={item} page={page} /> }
            : column,
    );
    return (
        <>
            <AdminListToolbar
                actions={
                    page.abilities.canSaveTemplate ? (
                        <AdminActionIconButton
                            label="新增收益政策模板"
                            primary
                            onClick={() => page.openTemplateEditor(null)}
                        >
                            <AddOutlined fontSize="small" />
                        </AdminActionIconButton>
                    ) : null
                }
                filters={
                    <div className={styles.toolbarFilters}>
                        <AdminSearchBox
                            label="模板"
                            placeholder="搜索模板名称或编码"
                            value={page.templateFilters.keyword}
                            onChange={page.changeTemplateKeyword}
                        />
                        <AdminFilterSelect
                            label="状态"
                            options={statusOptions}
                            value={page.templateFilters.status}
                            onChange={page.changeTemplateStatus}
                        />
                        <AdminFilterResetButton
                            disabled={!page.templateFilters.keyword && !page.templateFilters.status}
                            onClick={page.resetTemplateFilters}
                        />
                    </div>
                }
            />
            <DataState error={page.templates.error} loading={page.templates.loading} onRetry={page.templates.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={items}
                        minWidth="1240px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.templatePage,
                                      pageSize: page.templates.data.pageSize || 50,
                                      total,
                                      onPageChange: page.setTemplatePage,
                                  }
                                : undefined
                        }
                        rowKey={(item) => `${item.templateCode}:${item.templateVersion}`}
                    />
                </AdminListBody>
            </DataState>
        </>
    );
}

function InstancePanel({ page }) {
    const items = page.instances.data.items || [];
    const total = page.instances.data.total || 0;
    const columns = instanceColumns.map((column) => {
        if (column.key === "status") {
            return { ...column, render: (item) => <InstanceStatusSwitch item={item} page={page} /> };
        }
        if (column.key === "actions") {
            return { ...column, render: (item) => <InstanceActions item={item} page={page} /> };
        }
        return column;
    });
    return (
        <>
            <AdminListToolbar
                actions={
                    page.abilities.canCreateInstance ? (
                        <AdminActionIconButton
                            label="创建策略实例"
                            primary
                            onClick={() => page.openInstanceCreator(null)}
                        >
                            <AddOutlined fontSize="small" />
                        </AdminActionIconButton>
                    ) : null
                }
                filters={
                    <div className={styles.toolbarFilters}>
                        <AdminSearchBox
                            label="实例"
                            placeholder="搜索实例或模板编码"
                            value={page.instanceFilters.keyword}
                            onChange={page.changeInstanceKeyword}
                        />
                        <AdminFilterSelect
                            label="状态"
                            options={statusOptions}
                            value={page.instanceFilters.status}
                            onChange={page.changeInstanceStatus}
                        />
                        <AdminFilterResetButton
                            disabled={!page.instanceFilters.keyword && !page.instanceFilters.status}
                            onClick={page.resetInstanceFilters}
                        />
                    </div>
                }
            />
            <DataState error={page.instances.error} loading={page.instances.loading} onRetry={page.instances.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        context={{ regionLabelMap: page.regionLabelMap }}
                        items={items}
                        minWidth="1260px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.instancePage,
                                      pageSize: page.instances.data.pageSize || 50,
                                      total,
                                      onPageChange: page.setInstancePage,
                                  }
                                : undefined
                        }
                        rowKey={(item) => item.instanceId}
                    />
                </AdminListBody>
            </DataState>
        </>
    );
}

function TemplateIdentity({ item }) {
    return (
        <div className={styles.stack}>
            <span className={styles.name}>{item.name}</span>
            <span className={styles.meta}>{item.templateCode}</span>
            <span className={styles.meta}>版本 {item.templateVersion}</span>
        </div>
    );
}

function TemplateRuntimeSummary({ item }) {
    const rule = item.ruleJson || {};
    const host = rule.host || {};
    const agency = rule.agency || {};
    const tasks = rule.tasks || {};
    return (
        <div className={styles.stack}>
            <span>{formatNumber(rule.points_per_usd)} POINT/USD</span>
            <span className={styles.meta}>主播 {formatNumber(host.point_ratio_percent)}% 入 POINT</span>
            <span className={styles.meta}>Agency {formatNumber(agency.point_ratio_percent || 0)}% 分成</span>
            <span className={styles.meta}>提现手续费 {formatNumber(host.withdraw_fee_bps)} bps</span>
            <span className={styles.meta}>任务资产 {tasks.reward_asset_type || "-"}</span>
        </div>
    );
}

function TeamPolicySummary({ item }) {
    const rule = item.ruleJson || {};
    const agentLevels = Array.isArray(rule.agent?.levels) ? rule.agent.levels : [];
    const bdLevels = Array.isArray(rule.bd?.levels) ? rule.bd.levels : [];
    const coinSellerLevels = Array.isArray(rule.coin_seller?.levels) ? rule.coin_seller.levels : [];
    return (
        <div className={styles.stack}>
            <span>
                Agent {agentLevels.length} 档 · BD {bdLevels.length} 档
            </span>
            <span className={styles.meta}>币商 {coinSellerLevels.length} 档</span>
            <span className={styles.meta}>{rule.allow_self_brushing ? "允许自刷" : "不允许自刷"}</span>
        </div>
    );
}

function TemplateActions({ item, page }) {
    if (!page.abilities.canSaveTemplate) {
        return null;
    }
    return (
        <AdminActionIconButton label="编辑模板规则" onClick={() => page.openTemplateEditor(item)}>
            <EditOutlined fontSize="small" />
        </AdminActionIconButton>
    );
}

function InstanceIdentity({ item }) {
    return (
        <div className={styles.stack}>
            <span className={styles.name}>{item.instanceCode}</span>
            <span className={styles.meta}>{item.appCode || "-"}</span>
            <span className={styles.meta}>
                {item.templateCode} · {item.templateVersion}
            </span>
        </div>
    );
}

function InstanceScope({ item, regionLabelMap = {} }) {
    return (
        <div className={styles.stack}>
            <span>{regionScopeLabel(item.regionScope, regionLabelMap)}</span>
            <span className={styles.meta}>开始 {formatMillis(item.effectiveFromMs)}</span>
            <span className={styles.meta}>
                结束 {item.effectiveToMs ? formatMillis(item.effectiveToMs) : "长期有效"}
            </span>
        </div>
    );
}

function PublishSummary({ item }) {
    return (
        <div className={styles.stack}>
            <span>{publishStatusLabel(item.publishStatus)}</span>
            <span className={styles.meta}>
                {item.lastPublishedAtMs ? formatMillis(item.lastPublishedAtMs) : "未发布"}
            </span>
            {item.publishError ? <span className={styles.errorText}>{item.publishError}</span> : null}
        </div>
    );
}

function InstanceStatusSwitch({ item, page }) {
    const action = `instance-status-${item.instanceId}`;
    return (
        <AdminSwitch
            checked={item.status === "active"}
            checkedLabel="启用"
            disabled={!page.abilities.canUpdateInstance || page.loadingAction === action}
            label="策略实例状态"
            uncheckedLabel="停用"
            onChange={(event) => page.toggleInstanceStatus(item, event.target.checked)}
        />
    );
}

function InstanceActions({ item, page }) {
    const action = `instance-publish-${item.instanceId}`;
    if (!page.abilities.canPublishInstance) {
        return null;
    }
    return (
        <AdminActionIconButton
            disabled={item.status !== "active" || page.loadingAction === action}
            label="发布到运行侧"
            primary
            onClick={() => page.publishInstance(item)}
        >
            <CloudUploadOutlined fontSize="small" />
        </AdminActionIconButton>
    );
}

function statusLabel(status) {
    return status === "active" ? "启用" : "停用";
}

function publishStatusLabel(status) {
    switch (status) {
        case "published":
            return "已发布";
        case "failed":
            return "发布失败";
        default:
            return "草稿";
    }
}

function regionScopeLabel(scope, labels) {
    if (scope === "all_active_regions" || !scope) {
        return "全部启用地区";
    }
    if (String(scope).startsWith("region_id:")) {
        const regionId = String(scope).replace("region_id:", "");
        return labels[regionId] || `区域 ${regionId}`;
    }
    return scope;
}

function formatNumber(value) {
    const number = Number(value || 0);
    return Number.isFinite(number) ? number.toLocaleString("en-US") : "-";
}
