import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import IconButton from "@mui/material/IconButton";
import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { Button } from "@/shared/ui/Button.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import { UploadField } from "@/shared/ui/UploadField.jsx";
import styles from "@/features/activity-templates/activity-templates.module.css";
import { createRankReward, mediaTypeFromURL } from "@/features/activity-templates/model.js";
import { EditorSection } from "@/features/activity-templates/components/BasicAndContentSections.jsx";

export function RankingSettingsSection({ disabled, form, resourceGroups, updateField }) {
    return (
        <EditorSection title="榜单奖励">
            <RankBoardEditor
                boardLabel="日榜"
                disabled={disabled}
                leaderboardSize={form.dailyLeaderboardSize}
                resourceGroups={resourceGroups}
                rewards={form.dailyRankRewards}
                onLeaderboardSizeChange={(value) => updateField("dailyLeaderboardSize", value)}
                onRewardsChange={(value) => updateField("dailyRankRewards", value)}
            />
            <RankBoardEditor
                boardLabel="总榜"
                disabled={disabled}
                leaderboardSize={form.totalLeaderboardSize}
                resourceGroups={resourceGroups}
                rewards={form.totalRankRewards}
                onLeaderboardSizeChange={(value) => updateField("totalLeaderboardSize", value)}
                onRewardsChange={(value) => updateField("totalRankRewards", value)}
            />
        </EditorSection>
    );
}

export function AssetsSettingsSection({ disabled, form, updateField }) {
    const updateAsset = (index, url) => {
        updateField(
            "assets",
            form.assets.map((asset, assetIndex) =>
                assetIndex === index ? { ...asset, mediaType: mediaTypeFromURL(url), url } : asset,
            ),
        );
    };

    return (
        <EditorSection title="页面素材">
            <div className={styles.assetGrid}>
                {form.assets.map((asset, index) => (
                    <div className={styles.assetSlot} key={`${asset.assetKey}-${asset.locale}-${index}`}>
                        <UploadField
                            density="compact"
                            disabled={disabled}
                            hideType={false}
                            kind="image"
                            label={asset.label}
                            showSourceActions
                            value={asset.url}
                            onChange={(url) => updateAsset(index, url)}
                        />
                        <div className={styles.assetMeta}>
                            <code>{asset.assetKey}</code>
                            <span>{asset.locale === "*" ? "共享" : asset.locale.toUpperCase()}</span>
                        </div>
                    </div>
                ))}
            </div>
        </EditorSection>
    );
}

function RankBoardEditor({
    boardLabel,
    disabled,
    leaderboardSize,
    onLeaderboardSizeChange,
    onRewardsChange,
    resourceGroups,
    rewards,
}) {
    const updateReward = (index, patch) => {
        onRewardsChange(
            rewards.map((reward, rewardIndex) => (rewardIndex === index ? { ...reward, ...patch } : reward)),
        );
    };
    const addReward = () => {
        const lastRank = rewards.reduce((max, reward) => Math.max(max, Number(reward.rankTo || 0)), 0) + 1;
        if (lastRank > Number(leaderboardSize || 0)) return;
        onRewardsChange([...rewards, createRankReward(lastRank)]);
    };
    const removeReward = (index) => onRewardsChange(rewards.filter((_, rewardIndex) => rewardIndex !== index));

    return (
        <section className={styles.rankBoard}>
            <header className={styles.rankBoardHeader}>
                <div>
                    <strong>{boardLabel}</strong>
                    <span>{boardLabel === "日榜" ? "每日 00:00 UTC 结算" : "活动结束结算"}</span>
                </div>
                <div className={styles.rankBoardActions}>
                    <TextField
                        className={styles.leaderboardSizeField}
                        disabled={disabled}
                        label="上榜人数"
                        size="small"
                        slotProps={{ htmlInput: { min: 3, max: 1000 } }}
                        type="number"
                        value={leaderboardSize}
                        onChange={(event) => onLeaderboardSizeChange(event.target.value)}
                    />
                    <Button disabled={disabled} startIcon={<AddOutlined fontSize="small" />} onClick={addReward}>
                        添加区间
                    </Button>
                </div>
            </header>
            <div className={styles.rankRewardTable}>
                <div className={styles.rankRewardHead}>
                    <span>起始名次</span>
                    <span>结束名次</span>
                    <span>奖励资源组</span>
                    <span>操作</span>
                </div>
                {rewards.map((reward, index) => (
                    <div className={styles.rankRewardRow} key={`${reward.rankFrom}-${reward.rankTo}-${index}`}>
                        <TextField
                            disabled={disabled}
                            size="small"
                            slotProps={{ htmlInput: { min: 1 } }}
                            type="number"
                            value={reward.rankFrom}
                            onChange={(event) => updateReward(index, { rankFrom: event.target.value })}
                        />
                        <TextField
                            disabled={disabled}
                            size="small"
                            slotProps={{ htmlInput: { min: 1 } }}
                            type="number"
                            value={reward.rankTo}
                            onChange={(event) => updateReward(index, { rankTo: event.target.value })}
                        />
                        <ResourceGroupSelectField
                            disabled={disabled}
                            drawerTitle={`选择${boardLabel}第 ${reward.rankFrom}-${reward.rankTo} 名奖励`}
                            groups={resourceGroups}
                            label="奖励资源组"
                            value={reward.resourceGroupId}
                            onChange={(value) => updateReward(index, { resourceGroupId: value })}
                        />
                        <Tooltip arrow title="删除区间">
                            <span>
                                <IconButton
                                    aria-label="删除区间"
                                    disabled={disabled}
                                    size="small"
                                    onClick={() => removeReward(index)}
                                >
                                    <DeleteOutlineOutlined fontSize="small" />
                                </IconButton>
                            </span>
                        </Tooltip>
                    </div>
                ))}
                {!rewards.length ? <div className={styles.editorEmpty}>当前无数据</div> : null}
            </div>
        </section>
    );
}
