import AddOutlined from "@mui/icons-material/AddOutlined";
import ArrowDownwardOutlined from "@mui/icons-material/ArrowDownwardOutlined";
import ArrowUpwardOutlined from "@mui/icons-material/ArrowUpwardOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import IconButton from "@mui/material/IconButton";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { GiftPreviewSelectField } from "@/features/resources/components/GiftSelectDrawer.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import styles from "@/features/activity-templates/activity-templates.module.css";
import { TASK_TYPE_OPTIONS } from "@/features/activity-templates/constants.js";
import { createNextActivityTask, giftDtoFromForm, giftFormValue } from "@/features/activity-templates/model.js";
import { EditorSection } from "@/features/activity-templates/components/BasicAndContentSections.jsx";

export function GiftSettingsSection({ disabled, form, gifts, giftsLoading, updateField }) {
    const updateGift = (index, nextGift) => {
        updateField(
            "gifts",
            form.gifts.map((gift, giftIndex) => (giftIndex === index ? nextGift : gift)),
        );
    };
    const removeGift = (index) =>
        updateField(
            "gifts",
            form.gifts.filter((_, giftIndex) => giftIndex !== index),
        );
    const moveGift = (index, offset) => updateField("gifts", moveItem(form.gifts, index, index + offset));
    const addGift = () => {
        if (form.gifts.length >= 20) return;
        updateField("gifts", [...form.gifts, { coinPrice: "", giftId: "", iconUrl: "", name: "", priceVersion: "" }]);
    };

    return (
        <EditorSection
            actions={
                <Button
                    disabled={disabled || form.gifts.length >= 20}
                    startIcon={<AddOutlined fontSize="small" />}
                    onClick={addGift}
                >
                    添加礼物
                </Button>
            }
            title="活动礼物"
        >
            <div className={styles.editorCountLine}>已配置 {form.gifts.length} / 20</div>
            <div className={styles.sortableList}>
                {form.gifts.map((gift, index) => (
                    <div className={styles.giftEditorRow} key={`${gift.giftId || "new"}-${index}`}>
                        <span className={styles.rowOrder}>{index + 1}</span>
                        <GiftPreviewSelectField
                            className={styles.giftPicker}
                            disabled={disabled}
                            drawerTitle={`选择第 ${index + 1} 个活动礼物`}
                            fallbackGift={giftDtoFromForm(gift)}
                            gifts={gifts}
                            label="活动礼物"
                            loading={giftsLoading}
                            value={gift.giftId}
                            onChange={(_, selectedGift) => updateGift(index, giftFormValue(selectedGift))}
                        />
                        <div className={styles.rowMoveActions}>
                            <RowIconButton
                                disabled={disabled || index === 0}
                                label="上移"
                                onClick={() => moveGift(index, -1)}
                            >
                                <ArrowUpwardOutlined fontSize="small" />
                            </RowIconButton>
                            <RowIconButton
                                disabled={disabled || index === form.gifts.length - 1}
                                label="下移"
                                onClick={() => moveGift(index, 1)}
                            >
                                <ArrowDownwardOutlined fontSize="small" />
                            </RowIconButton>
                            <RowIconButton disabled={disabled} label="删除" onClick={() => removeGift(index)}>
                                <DeleteOutlineOutlined fontSize="small" />
                            </RowIconButton>
                        </div>
                    </div>
                ))}
                {!form.gifts.length ? <div className={styles.editorEmpty}>当前无数据</div> : null}
            </div>
        </EditorSection>
    );
}

export function TaskSettingsSection({ disabled, form, resourceGroups, updateField }) {
    const updateTask = (index, patch) => {
        updateField(
            "tasks",
            form.tasks.map((task, taskIndex) => (taskIndex === index ? { ...task, ...patch } : task)),
        );
    };
    const removeTask = (index) =>
        updateField(
            "tasks",
            form.tasks.filter((_, taskIndex) => taskIndex !== index),
        );
    const moveTask = (index, offset) => updateField("tasks", moveItem(form.tasks, index, index + offset));
    const addTask = () => {
        if (form.tasks.length >= 30) return;
        updateField("tasks", [...form.tasks, createNextActivityTask(form.tasks, "gift_count")]);
    };

    return (
        <EditorSection
            actions={
                <Button
                    disabled={disabled || form.tasks.length >= 30}
                    startIcon={<AddOutlined fontSize="small" />}
                    onClick={addTask}
                >
                    添加任务
                </Button>
            }
            title="每日任务"
        >
            <div className={styles.editorCountLine}>每日 00:00 UTC 重置 · 已配置 {form.tasks.length} / 30</div>
            <div className={styles.taskTable}>
                <div className={styles.taskTableHead}>
                    <span>排序</span>
                    <span>任务键</span>
                    <span>任务类型</span>
                    <span>目标值</span>
                    <span>奖励资源组</span>
                    <span>操作</span>
                </div>
                {form.tasks.map((task, index) => (
                    <div className={styles.taskTableRow} key={`${task.taskKey}-${index}`}>
                        <span className={styles.rowOrder}>{index + 1}</span>
                        <TextField
                            disabled={disabled}
                            placeholder="gift_count_1"
                            size="small"
                            value={task.taskKey}
                            onChange={(event) => updateTask(index, { taskKey: normalizeKey(event.target.value) })}
                        />
                        <TextField
                            disabled={disabled}
                            select
                            size="small"
                            value={task.taskType}
                            onChange={(event) =>
                                updateTask(index, {
                                    targetValue: event.target.value === "daily_visit" ? "1" : task.targetValue,
                                    taskType: event.target.value,
                                })
                            }
                        >
                            {TASK_TYPE_OPTIONS.map(([value, label]) => (
                                <MenuItem
                                    disabled={
                                        value === "daily_visit" &&
                                        task.taskType !== "daily_visit" &&
                                        form.tasks.some((item) => item.taskType === "daily_visit")
                                    }
                                    key={value}
                                    value={value}
                                >
                                    {label}
                                </MenuItem>
                            ))}
                        </TextField>
                        <TextField
                            disabled={disabled || task.taskType === "daily_visit"}
                            size="small"
                            slotProps={{ htmlInput: { min: 1 } }}
                            type="number"
                            value={task.targetValue}
                            onChange={(event) => updateTask(index, { targetValue: event.target.value })}
                        />
                        <ResourceGroupSelectField
                            disabled={disabled}
                            drawerTitle={`选择任务 ${task.taskKey || index + 1} 奖励`}
                            groups={resourceGroups}
                            label="奖励资源组"
                            value={task.rewardResourceGroupId}
                            onChange={(value) => updateTask(index, { rewardResourceGroupId: value })}
                        />
                        <div className={styles.rowMoveActions}>
                            <RowIconButton
                                disabled={disabled || index === 0}
                                label="上移"
                                onClick={() => moveTask(index, -1)}
                            >
                                <ArrowUpwardOutlined fontSize="small" />
                            </RowIconButton>
                            <RowIconButton
                                disabled={disabled || index === form.tasks.length - 1}
                                label="下移"
                                onClick={() => moveTask(index, 1)}
                            >
                                <ArrowDownwardOutlined fontSize="small" />
                            </RowIconButton>
                            <RowIconButton disabled={disabled} label="删除" onClick={() => removeTask(index)}>
                                <DeleteOutlineOutlined fontSize="small" />
                            </RowIconButton>
                        </div>
                    </div>
                ))}
                {!form.tasks.length ? <div className={styles.editorEmpty}>当前无数据</div> : null}
            </div>
        </EditorSection>
    );
}

function RowIconButton({ children, disabled, label, onClick }) {
    return (
        <Tooltip arrow title={label}>
            <span>
                <IconButton aria-label={label} disabled={disabled} size="small" onClick={onClick}>
                    {children}
                </IconButton>
            </span>
        </Tooltip>
    );
}

function moveItem(items, fromIndex, toIndex) {
    if (toIndex < 0 || toIndex >= items.length) return items;
    const next = [...items];
    const [item] = next.splice(fromIndex, 1);
    next.splice(toIndex, 0, item);
    return next;
}

function normalizeKey(value) {
    return String(value || "")
        .toLowerCase()
        .replace(/[^a-z0-9_-]/g, "");
}
