import EditOutlined from "@mui/icons-material/EditOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import SaveOutlined from "@mui/icons-material/SaveOutlined";
import SettingsOutlined from "@mui/icons-material/SettingsOutlined";
import CircularProgress from "@mui/material/CircularProgress";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs";
import TextField from "@mui/material/TextField";
import { useMemo } from "react";
import { cpRelationLabels, useCPConfigPage } from "@/features/cp-config/hooks/useCPConfigPage.js";
import styles from "@/features/cp-config/cp-config.module.css";
import { AdminListBody, AdminListPage } from "@/shared/ui/AdminListLayout.jsx";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { TimeText } from "@/shared/ui/TimeText.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";

const tabLabels = {
    relationships: "用户关系列表",
    applications: "CP申请列表",
};

export function CPConfigPage() {
    const page = useCPConfigPage();
    const relations = page.config.relations || [];
    const relationshipColumns = useMemo(
        () => cpRelationshipColumns(page.relationships.serverTimeMs),
        [page.relationships.serverTimeMs],
    );
    const applicationColumns = useMemo(() => cpApplicationColumns(), []);
    const isApplicationsTab = page.activeTab === "applications";
    const activePage = isApplicationsTab ? page.applications : page.relationships;
    const activeLoading = isApplicationsTab ? page.applicationsLoading : page.relationshipsLoading;
    const activeError = isApplicationsTab ? page.applicationsError : page.relationshipsError;

    return (
        <AdminListPage>
            <div className={styles.summaryPanel}>
                <div className={styles.summaryItems}>
                    <SummaryItem label="关系类型">{relations.length || 3}</SummaryItem>
                    <SummaryItem label="启用类型">{page.activeRelationCount}</SummaryItem>
                    <SummaryItem label="兄弟上限">{relationMax(relations, "brother")}</SummaryItem>
                    <SummaryItem label="姐妹上限">{relationMax(relations, "sister")}</SummaryItem>
                    <SummaryItem label="CP解除费">{relationBreakupCost(relations, "cp")}</SummaryItem>
                </div>
                <div className={styles.summaryActions}>
                    <Button
                        disabled={page.loading || activeLoading}
                        startIcon={<RefreshOutlined fontSize="small" />}
                        onClick={page.reload}
                    >
                        刷新
                    </Button>
                    <Button
                        disabled={page.loading}
                        startIcon={
                            page.abilities.canUpdate ? (
                                <EditOutlined fontSize="small" />
                            ) : (
                                <SettingsOutlined fontSize="small" />
                            )
                        }
                        variant="primary"
                        onClick={page.openDrawer}
                    >
                        配置
                    </Button>
                </div>
            </div>
            <div className={styles.tabsBar}>
                <Tabs value={page.activeTab} onChange={(_, value) => page.setActiveTab(value)}>
                    <Tab className={styles.tab} label={tabLabels.relationships} value="relationships" />
                    <Tab className={styles.tab} label={tabLabels.applications} value="applications" />
                </Tabs>
            </div>
            <DataState error={activeError} loading={activeLoading} onRetry={page.reloadActiveTab}>
                <AdminListBody>
                    <DataTable
                        columns={isApplicationsTab ? applicationColumns : relationshipColumns}
                        emptyLabel="当前无数据"
                        items={activePage.items}
                        minWidth={isApplicationsTab ? "1280px" : "1440px"}
                        pagination={{
                            page: activePage.page,
                            pageSize: activePage.pageSize,
                            total: activePage.total,
                            onPageChange: isApplicationsTab ? page.loadApplications : page.loadRelationships,
                        }}
                        rowKey={(item) =>
                            isApplicationsTab
                                ? item.applicationId
                                : item.relationshipId || `${item.userA?.userId}-${item.userB?.userId}`
                        }
                    />
                </AdminListBody>
            </DataState>
            <CPConfigDialog page={page} />
        </AdminListPage>
    );
}

function CPConfigDialog({ page }) {
    const canUpdate = page.abilities.canUpdate;
    const disabled = !canUpdate || page.saving || page.loading;
    return (
        <Dialog
            className={styles.configDialog}
            maxWidth={false}
            open={page.drawerOpen}
            slotProps={{ paper: { className: styles.configDialogPaper } }}
            onClose={page.saving ? undefined : page.closeDrawer}
        >
            <form className={styles.configDialogForm} onSubmit={page.submit}>
                <DialogTitle className={styles.configDialogTitle}>
                    <div>
                        <h2>CP配置</h2>
                        <span>关系等级、关系数量和解除费用</span>
                    </div>
                    <div className={styles.configDrawerStats}>
                        <span>{(page.form.relations || []).length} 个关系</span>
                        <span>{page.activeRelationCount} 个启用</span>
                    </div>
                </DialogTitle>
                <DialogContent className={styles.configDialogContent}>
                    <section className="form-drawer__section">
                        <div className="form-drawer__section-title">关系与等级</div>
                        <div className={styles.relationEditorList}>
                            {(page.form.relations || []).map((relation) => (
                                <RelationEditor
                                    disabled={disabled}
                                    key={relation.relationType}
                                    relation={relation}
                                    resourceGroups={page.resourceGroups}
                                    updateLevel={page.updateLevel}
                                    updateRelation={page.updateRelation}
                                />
                            ))}
                        </div>
                    </section>
                </DialogContent>
                <DialogActions className={styles.configDialogActions}>
                    <Button disabled={page.saving} type="button" onClick={page.closeDrawer}>
                        {canUpdate ? "取消" : "关闭"}
                    </Button>
                    {canUpdate ? (
                        <Button
                            disabled={disabled}
                            startIcon={
                                page.saving ? (
                                    <CircularProgress color="inherit" size={16} />
                                ) : (
                                    <SaveOutlined fontSize="small" />
                                )
                            }
                            type="submit"
                            variant="primary"
                        >
                            保存
                        </Button>
                    ) : null}
                </DialogActions>
            </form>
        </Dialog>
    );
}

function RelationEditor({ disabled, relation, resourceGroups, updateLevel, updateRelation }) {
    const relationType = relation.relationType;
    const maxCountDisabled = disabled || relationType === "cp";
    const activeLevelCount = (relation.levels || []).filter((level) => level.status === "active").length;

    return (
        <div className={styles.relationEditor}>
            <div className={styles.relationEditorHeader}>
                <div className={styles.relationTitleGroup}>
                    <span className={styles.relationTitle}>
                        {relation.displayName || cpRelationLabels[relationType]}
                    </span>
                    <span className={styles.relationSubtitle}>
                        {relationType} / {activeLevelCount} 个等级启用
                    </span>
                </div>
                <AdminSwitch
                    checked={relation.status === "active"}
                    checkedLabel="启用"
                    disabled={disabled}
                    label={`${cpRelationLabels[relationType]}状态`}
                    uncheckedLabel="停用"
                    onChange={(event) =>
                        updateRelation(relationType, { status: event.target.checked ? "active" : "disabled" })
                    }
                />
            </div>
            <div className={styles.relationControls}>
                <TextField
                    disabled={maxCountDisabled}
                    inputProps={{ min: 1, step: 1 }}
                    label="数量上限"
                    type="number"
                    value={relationType === "cp" ? "1" : relation.maxCountPerUser}
                    onChange={(event) => updateRelation(relationType, { maxCountPerUser: event.target.value })}
                />
                <TextField
                    disabled={disabled}
                    inputProps={{ min: 1, step: 1 }}
                    label="申请过期小时"
                    type="number"
                    value={relation.applicationExpireHours}
                    onChange={(event) => updateRelation(relationType, { applicationExpireHours: event.target.value })}
                />
                <TextField
                    disabled={disabled}
                    inputProps={{ min: 0, step: 1 }}
                    label="解除费用金币"
                    type="number"
                    value={relation.breakupCostCoins}
                    onChange={(event) => updateRelation(relationType, { breakupCostCoins: event.target.value })}
                />
            </div>
            <div className={styles.levelEditorList}>
                {(relation.levels || []).map((level) => (
                    <LevelEditor
                        disabled={disabled}
                        key={`${relationType}-${level.level}`}
                        level={level}
                        relationType={relationType}
                        resourceGroups={resourceGroups}
                        updateLevel={updateLevel}
                    />
                ))}
            </div>
        </div>
    );
}

function LevelEditor({ disabled, level, relationType, resourceGroups, updateLevel }) {
    const selectedGroup = resourceGroups.find((group) => String(group.groupId) === String(level.rewardResourceGroupId));

    return (
        <div className={styles.levelEditor}>
            <div className={styles.levelEditorHeader}>
                <div className={styles.levelTitleGroup}>
                    <span className={styles.levelTitle}>{level.level}级</span>
                    <span className={styles.levelMeta}>
                        {resourceGroupLabel(selectedGroup, level.rewardResourceGroupId)}
                    </span>
                </div>
                <AdminSwitch
                    checked={level.status === "active"}
                    checkedLabel="启用"
                    disabled={disabled}
                    label={`${cpRelationLabels[relationType]}${level.level}级状态`}
                    uncheckedLabel="停用"
                    onChange={(event) =>
                        updateLevel(relationType, level.level, {
                            status: event.target.checked ? "active" : "disabled",
                        })
                    }
                />
            </div>
            <div className={styles.levelFields}>
                <TextField
                    disabled={disabled}
                    inputProps={{ min: 0, step: 1 }}
                    label="亲密值"
                    type="number"
                    value={level.intimacyThreshold}
                    onChange={(event) =>
                        updateLevel(relationType, level.level, { intimacyThreshold: event.target.value })
                    }
                />
                <ResourceGroupSelectField
                    allowEmpty
                    disabled={disabled}
                    drawerTitle={`${cpRelationLabels[relationType]} ${level.level}级奖励资源组`}
                    emptyLabel="不配置奖励"
                    groups={resourceGroups}
                    label="奖励资源组"
                    placeholder="点击选择奖励资源组"
                    value={level.rewardResourceGroupId}
                    onChange={(value) => updateLevel(relationType, level.level, { rewardResourceGroupId: value })}
                />
                <TextField
                    disabled={disabled}
                    label="等级图标URL"
                    value={level.levelIconUrl}
                    onChange={(event) => updateLevel(relationType, level.level, { levelIconUrl: event.target.value })}
                />
            </div>
        </div>
    );
}

function cpRelationshipColumns(serverTimeMs) {
    return [
        {
            key: "userA",
            label: "用户A",
            width: "minmax(210px, 0.9fr)",
            render: (item) => <CPUserCell user={item.userA} />,
        },
        {
            key: "userB",
            label: "用户B",
            width: "minmax(210px, 0.9fr)",
            render: (item) => <CPUserCell user={item.userB} />,
        },
        {
            key: "relationType",
            label: "类型",
            width: "minmax(110px, 0.4fr)",
            render: (item) => <RelationTypeBadge relationType={item.relationType} />,
        },
        {
            key: "days",
            label: "天数",
            width: "minmax(90px, 0.35fr)",
            render: (item) => formatRelationDays(item, serverTimeMs),
        },
        {
            key: "level",
            label: "等级",
            width: "minmax(90px, 0.35fr)",
            render: (item) => (item.level ? `${formatNumber(item.level)}级` : "-"),
        },
        {
            key: "intimacy",
            label: "经验值",
            width: "minmax(130px, 0.5fr)",
            render: (item) => formatNumber(item.intimacyValue),
        },
        {
            key: "gift",
            label: "关系礼物/价值",
            width: "minmax(240px, 0.95fr)",
            render: (item) => <GiftCell gift={item.gift} />,
        },
        {
            key: "formedAt",
            label: "组成时间",
            width: "minmax(170px, 0.7fr)",
            render: (item) => <NullableTime value={item.formedAtMs} />,
        },
        {
            key: "status",
            label: "状态",
            width: "minmax(110px, 0.4fr)",
            render: (item) => <StatusBadge status={item.status} />,
        },
    ];
}

function cpApplicationColumns() {
    return [
        {
            key: "requester",
            label: "申请方",
            width: "minmax(210px, 0.9fr)",
            render: (item) => <CPUserCell user={item.requester} />,
        },
        {
            key: "target",
            label: "接收方",
            width: "minmax(210px, 0.9fr)",
            render: (item) => <CPUserCell user={item.target} />,
        },
        {
            key: "relationType",
            label: "申请类型",
            width: "minmax(120px, 0.45fr)",
            render: (item) => <RelationTypeBadge relationType={item.relationType} />,
        },
        {
            key: "gift",
            label: "申请礼物/价值",
            width: "minmax(240px, 1fr)",
            render: (item) => <GiftCell gift={item.gift} />,
        },
        {
            key: "status",
            label: "状态",
            width: "minmax(110px, 0.45fr)",
            render: (item) => <StatusBadge status={item.status} />,
        },
        {
            key: "createdAt",
            label: "申请时间",
            width: "minmax(170px, 0.7fr)",
            render: (item) => <NullableTime value={item.createdAtMs} />,
        },
        {
            key: "decidedAt",
            label: "处理时间",
            width: "minmax(170px, 0.7fr)",
            render: (item) => <NullableTime value={item.decidedAtMs} />,
        },
    ];
}

function CPUserCell({ user }) {
    if (!user?.userId && !user?.displayUserId && !user?.username) {
        return "-";
    }
    return <AdminUserIdentity openInAppUserDetail rows={[user.displayUserId, user.userId]} user={user} />;
}

function GiftCell({ gift }) {
    if (!gift?.giftId && !gift?.giftName && !gift?.giftValue) {
        return "-";
    }
    const name = gift.giftName || gift.giftId || "-";
    const meta = [gift.giftCount ? `x${formatNumber(gift.giftCount)}` : "", gift.giftId].filter(Boolean).join(" · ");
    return (
        <div className={styles.giftCell}>
            {gift.giftIconUrl ? <img alt="" className={styles.giftIcon} src={gift.giftIconUrl} /> : null}
            <div className={styles.stack}>
                <span className={styles.name}>{name}</span>
                <span className={styles.meta}>{meta || "礼物"}</span>
                <span className={styles.amount}>{formatNumber(gift.giftValue)} 价值</span>
            </div>
        </div>
    );
}

function RelationTypeBadge({ relationType }) {
    return (
        <span className={[styles.relationBadge, styles[`relationBadge_${relationType}`]].filter(Boolean).join(" ")}>
            {cpRelationLabels[relationType] || relationType || "-"}
        </span>
    );
}

function StatusBadge({ status }) {
    const normalized = String(status || "").toLowerCase();
    return (
        <span className={[styles.statusBadge, statusClassName(normalized)].filter(Boolean).join(" ")}>
            {statusLabel(normalized)}
        </span>
    );
}

function NullableTime({ value }) {
    return value ? <TimeText value={value} /> : "-";
}

function SummaryItem({ children, label }) {
    return (
        <div className={styles.summaryItem}>
            <span className={styles.summaryLabel}>{label}</span>
            <span className={styles.summaryValue}>{children}</span>
        </div>
    );
}

function relationMax(relations, relationType) {
    const relation = relations.find((item) => item.relationType === relationType);
    return relation ? formatNumber(relation.maxCountPerUser) : "-";
}

function relationBreakupCost(relations, relationType) {
    const relation = relations.find((item) => item.relationType === relationType);
    return relation ? `${formatNumber(relation.breakupCostCoins)} 金币` : "-";
}

function resourceGroupLabel(group, value) {
    if (group) {
        return group.name || group.groupCode || `资源组 #${group.groupId}`;
    }
    return value ? `资源组 #${value}` : "未配置奖励";
}

function formatRelationDays(item, serverTimeMs) {
    if (item.durationDays) {
        return `${formatNumber(item.durationDays)} 天`;
    }
    if (!item.formedAtMs) {
        return "-";
    }
    const endMs = item.endedAtMs || serverTimeMs || Date.now();
    const days = Math.max(1, Math.floor((Number(endMs) - Number(item.formedAtMs)) / 86400000) + 1);
    return `${formatNumber(days)} 天`;
}

function statusLabel(status) {
    const labels = {
        accepted: "已同意",
        active: "启用",
        blocked: "已阻断",
        disabled: "停用",
        ended: "已解除",
        expired: "已过期",
        pending: "待处理",
        rejected: "已拒绝",
    };
    return labels[status] || status || "-";
}

function statusClassName(status) {
    if (status === "active" || status === "accepted") {
        return styles.statusActive;
    }
    if (status === "pending") {
        return styles.statusPending;
    }
    if (status === "rejected" || status === "expired") {
        return styles.statusDanger;
    }
    return styles.statusDisabled;
}

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