import { useState } from "react";
import Add from "@mui/icons-material/Add";
import CloudUploadOutlined from "@mui/icons-material/CloudUploadOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
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,
} from "@/shared/ui/AdminListLayout.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";
import { HostAgencyPolicyDrawer } from "@/features/host-agency-policy/components/HostAgencyPolicyDrawer.jsx";
import { useHostAgencyPolicyPage } from "@/features/host-agency-policy/hooks/useHostAgencyPolicyPage.js";
import { TeamSalaryPolicyPanel } from "@/features/host-agency-policy/pages/TeamSalaryPolicyPanel.jsx";
import { residualRateLabel } from "@/features/host-agency-policy/residualRate.js";
import styles from "@/features/host-agency-policy/host-agency-policy.module.css";

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

const settlementModeOptions = [
    ["", "全部结算"],
    ["daily", "日结"],
    ["half_month", "半月结算"],
];

const settlementTriggerOptions = [
    ["", "全部触发"],
    ["automatic", "自动结算"],
    ["manual", "手动结算"],
];

const columnsBase = [
    {
        key: "policy",
        label: "政策",
        width: "minmax(260px, 1.2fr)",
        // DataTable 的 render 签名是 (item, rowIndex, context)，这里显式保留 rowIndex 占位，避免把行号误当上下文。
        render: (item, _rowIndex, context) => <PolicyIdentity item={item} regionLabels={context.regionLabels} />,
    },
    {
        key: "settlement",
        label: "结算与比例",
        width: "minmax(190px, 0.9fr)",
        render: (item) => <SettlementSummary item={item} />,
    },
    {
        key: "levels",
        label: "等级",
        width: "minmax(180px, 0.8fr)",
        render: (item) => <LevelSummary item={item} />,
    },
    {
        key: "effective",
        label: "生效时间",
        width: "minmax(220px, 1fr)",
        render: (item) => <EffectiveTime item={item} />,
    },
    {
        key: "publish",
        label: "发布",
        width: "minmax(180px, 0.8fr)",
        render: (item) => <PublishSummary item={item} />,
    },
    {
        key: "status",
        label: "状态",
        width: "minmax(110px, 0.5fr)",
    },
    {
        key: "updatedAt",
        label: "更新时间",
        width: "minmax(170px, 0.75fr)",
        render: (item) => formatMillis(item.updatedAtMs || item.createdAtMs),
    },
    {
        key: "actions",
        label: "操作",
        width: "156px",
        resizable: false,
    },
];

export function HostAgencyPolicyPage() {
    const [activeTab, setActiveTab] = useState("host");
    return (
        <AdminListPage>
            <div className={styles.policyTabsBar}>
                <Tabs value={activeTab} onChange={(_, value) => setActiveTab(value)}>
                    <Tab className={styles.policyTab} label="Host 政策" value="host" />
                    <Tab className={styles.policyTab} label="BD 政策" value="bd" />
                    <Tab className={styles.policyTab} label="Admin 政策" value="admin" />
                </Tabs>
            </div>
            {activeTab === "host" ? <HostPolicyPanel /> : <TeamSalaryPolicyPanel policyType={activeTab} />}
        </AdminListPage>
    );
}

function HostPolicyPanel() {
    const page = useHostAgencyPolicyPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    // 列表筛选仍是单区域筛选，因为当前阶段后端政策模型只绑定一个 region_id。
    const regionFilterOptions = [["", "全部区域"], ...page.regionOptions.map((region) => [region.value, region.label])];
    const columns = columnsBase.map((column) => {
        // 过滤控件挂在列定义里，保持 DataTable 的列宽、筛选和渲染配置集中声明。
        if (column.key === "policy") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索政策名称",
                    value: page.query,
                    onChange: page.changeQuery,
                }),
            };
        }
        if (column.key === "settlement") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    // 同一列同时承载节奏和触发方式；列头筛选默认筛结算节奏，页面工具栏提供触发方式筛选。
                    options: settlementModeOptions,
                    placeholder: "搜索结算",
                    value: page.settlementMode,
                    onChange: page.changeSettlementMode,
                }),
            };
        }
        if (column.key === "status") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: statusOptions,
                    placeholder: "搜索状态",
                    value: page.status,
                    onChange: page.changeStatus,
                }),
                render: (item) => <PolicyStatusSwitch item={item} page={page} />,
            };
        }
        if (column.key === "actions") {
            return {
                ...column,
                render: (item) => <PolicyActions item={item} page={page} />,
            };
        }
        return column;
    });

    return (
        <>
            <AdminListToolbar
                actions={
                    page.abilities.canCreate ? (
                        <AdminActionIconButton label="新增工资政策" primary onClick={page.openCreate}>
                            <Add fontSize="small" />
                        </AdminActionIconButton>
                    ) : null
                }
                filters={
                    <div className={styles.toolbarFilters}>
                        <AdminFilterSelect
                            label="区域"
                            options={regionFilterOptions}
                            value={page.regionId}
                            onChange={page.changeRegionId}
                        />
                        <AdminFilterSelect
                            label="触发方式"
                            options={settlementTriggerOptions}
                            value={page.settlementTriggerMode}
                            onChange={page.changeSettlementTriggerMode}
                        />
                        <AdminFilterResetButton
                            disabled={
                                !page.query &&
                                !page.regionId &&
                                !page.status &&
                                !page.settlementMode &&
                                !page.settlementTriggerMode
                            }
                            onClick={page.resetFilters}
                        />
                    </div>
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        context={{ regionLabels: page.regionLabels }}
                        items={items}
                        minWidth="1420px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.data.pageSize || 50,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        rowKey={(item) => item.id}
                    />
                </AdminListBody>
            </DataState>
            <HostAgencyPolicyDrawer page={page} />
        </>
    );
}

function PolicyIdentity({ item, regionLabels }) {
    // regionLabels 来自区域配置接口，后端政策列表只返回 region_id，避免列表接口重复拼区域名称。
    const labels = regionLabels || {};
    return (
        <div className={styles.stack}>
            <span className={styles.name}>{item.name}</span>
            <span className={styles.meta}>{labels[item.regionId] || `区域 ${item.regionId}`}</span>
        </div>
    );
}

function SettlementSummary({ item }) {
    return (
        <div className={styles.stack}>
            <span>{settlementLabel(item.settlementMode)}</span>
            <span className={styles.meta}>{settlementTriggerLabel(item.settlementTriggerMode)}</span>
            <span className={styles.meta}>入账钻石按礼物钻石配置</span>
            <span className={styles.meta}>{residualRateLabel(item.residualDiamondToUsdRate)}</span>
        </div>
    );
}

function LevelSummary({ item }) {
    const first = item.levels?.[0];
    const last = item.levels?.[item.levels.length - 1];
    // 等级摘要展示门槛范围和最高累计主播工资，帮助运营快速识别政策梯度是否录错。
    return (
        <div className={styles.stack}>
            <span>{item.levels?.length || 0} 个等级</span>
            <span className={styles.meta}>
                {first && last
                    ? `${formatNumber(first.requiredDiamonds)} - ${formatNumber(last.requiredDiamonds)}`
                    : "-"}
            </span>
            <span className={styles.meta}>{last ? `最高工资 $${last.hostSalaryUsd}` : ""}</span>
        </div>
    );
}

function EffectiveTime({ item }) {
    return (
        <div className={styles.stack}>
            <span>{item.effectiveFromMs ? formatMillis(item.effectiveFromMs) : "立即生效"}</span>
            <span className={styles.meta}>{item.effectiveToMs ? formatMillis(item.effectiveToMs) : "长期有效"}</span>
        </div>
    );
}

function PublishSummary({ item }) {
    const status = item.publishStatus || "draft";
    // publish_error 只在失败态显示，避免成功发布后的旧错误文案干扰运营判断。
    return (
        <div className={styles.stack}>
            <span className={`status-badge status-badge--${publishTone(status)}`}>{publishLabel(status)}</span>
            <span className={styles.meta}>{item.publishedAtMs ? formatMillis(item.publishedAtMs) : "未发布"}</span>
            {status === "failed" && item.publishError ? <span className={styles.meta}>{item.publishError}</span> : null}
        </div>
    );
}

function PolicyStatusSwitch({ item, page }) {
    const disabled = !page.abilities.canUpdate || page.loadingAction === `policy-status-${item.id}`;
    // 行内启停最终仍走 update 接口，后端会重新执行同区域时间段冲突校验。
    return (
        <AdminSwitch
            checked={item.status === "active"}
            checkedLabel="启用"
            disabled={disabled}
            label="切换政策状态"
            uncheckedLabel="停用"
            onChange={(event) => page.togglePolicyStatus(item, event.target.checked)}
        />
    );
}

function PolicyActions({ item, page }) {
    return (
        <div className={styles.rowActions}>
            <AdminActionIconButton
                disabled={!page.abilities.canPublish || page.loadingAction === `policy-publish-${item.id}`}
                label="发布工资政策"
                onClick={() => page.publishPolicy(item)}
            >
                <CloudUploadOutlined fontSize="small" />
            </AdminActionIconButton>
            <AdminActionIconButton
                disabled={!page.abilities.canUpdate}
                label="编辑工资政策"
                onClick={() => page.openEdit(item)}
            >
                <EditOutlined fontSize="small" />
            </AdminActionIconButton>
            <AdminActionIconButton
                disabled={!page.abilities.canDelete || page.loadingAction === `policy-delete-${item.id}`}
                label="删除工资政策"
                onClick={() => page.removePolicy(item)}
            >
                <DeleteOutlineOutlined fontSize="small" />
            </AdminActionIconButton>
        </div>
    );
}

function settlementLabel(value) {
    return settlementModeOptions.find(([mode]) => mode === value)?.[1] || value || "-";
}

function settlementTriggerLabel(value) {
    return settlementTriggerOptions.find(([mode]) => mode === value)?.[1] || value || "-";
}

function publishLabel(value) {
    return (
        {
            draft: "草稿",
            failed: "发布失败",
            published: "已发布",
        }[value] ||
        value ||
        "-"
    );
}

function publishTone(value) {
    return (
        {
            draft: "warning",
            failed: "danger",
            published: "running",
        }[value] || "stopped"
    );
}

function formatNumber(value) {
    return new Intl.NumberFormat("zh-CN").format(Number(value || 0));
}
