import TextField from "@mui/material/TextField";
import Pagination from "@mui/material/Pagination";
import { useState } from "react";
import { AdminFormDialog, AdminFormSwitchField } from "@/shared/ui/AdminFormDialog.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import { ResourceSelectField } from "@/features/resources/components/ResourceSelectDrawer.jsx";
import {
    levelAvatarFrameResourcesForTrack,
    levelBadgeResourcesForTrack,
    levelShortBadgeResourcesForTrack,
    withSelectedResource,
} from "@/features/level-config/resourceFilters.js";
import styles from "@/features/level-config/components/LevelConfigBatchDialog.module.css";

export function LevelConfigBatchDialog({ page }) {
    if (page.activeAction === "rule-batch-edit") {
        return <RuleBatchDialog page={page} />;
    }
    if (page.activeAction === "tier-batch-edit") {
        return <TierBatchDialog page={page} />;
    }
    return null;
}

function RuleBatchDialog({ page }) {
    const pageSize = 20;
    const [editorPage, setEditorPage] = useState(1);
    const pageCount = Math.max(1, Math.ceil(page.batchForms.length / pageSize));
    const startIndex = (editorPage - 1) * pageSize;
    const visibleForms = page.batchForms.slice(startIndex, startIndex + pageSize);

    return (
        <AdminFormDialog
            disabled={!page.abilities.canUpdate}
            loading={page.loadingAction === "rule-batch-edit"}
            open
            size="full"
            submitDisabled={!page.batchDirty || !page.abilities.canUpdate || page.loadingAction === "rule-batch-edit"}
            submitLabel="保存全部修改"
            title="批量编辑每级升级数值"
            onClose={page.closeAction}
            onSubmit={page.submitRuleBatch}
        >
            <div className={styles.list}>
                <div className={styles.pager}>
                    <span>
                        当前 {startIndex + 1}-{Math.min(startIndex + pageSize, page.batchForms.length)}，共{" "}
                        {page.batchForms.length} 级
                    </span>
                    <Pagination
                        count={pageCount}
                        page={editorPage}
                        shape="rounded"
                        onChange={(_, nextPage) => setEditorPage(nextPage)}
                    />
                </div>
                {visibleForms.map((form, visibleIndex) => {
                    const index = startIndex + visibleIndex;
                    return (
                        <section className={styles.row} key={`${form.track}-${form.level}`}>
                            <div className={styles.identity}>
                                <strong>Lv.{form.level}</strong>
                                <span>{form.name}</span>
                            </div>
                            <div className={styles.ruleFields}>
                                <TextField
                                    disabled={!page.abilities.canUpdate}
                                    inputProps={{ min: 0 }}
                                    label="升级数值"
                                    type="number"
                                    value={form.requiredValue}
                                    onChange={changeBatchField(page, index, "requiredValue")}
                                />
                                <TextField
                                    disabled={!page.abilities.canUpdate}
                                    label="展示名称"
                                    value={form.name}
                                    onChange={changeBatchField(page, index, "name")}
                                />
                                <ResourceSelectField
                                    disabled={!page.abilities.canUpdate}
                                    drawerTitle={`选择 Lv.${form.level} 长徽章`}
                                    label="长徽章"
                                    required={false}
                                    resources={withSelectedResource(
                                        levelBadgeResourcesForTrack(page.badgeResources, form.track),
                                        form.longBadgeResourceId,
                                    )}
                                    value={form.longBadgeResourceId}
                                    onChange={(value) => page.updateBatchForm(index, "longBadgeResourceId", value)}
                                />
                                <ResourceSelectField
                                    disabled={!page.abilities.canUpdate}
                                    drawerTitle={`选择 Lv.${form.level} 头像框`}
                                    label="头像框"
                                    required={false}
                                    resources={withSelectedResource(
                                        levelAvatarFrameResourcesForTrack(page.avatarFrameResources, form.track),
                                        form.avatarFrameResourceId,
                                    )}
                                    value={form.avatarFrameResourceId}
                                    onChange={(value) => page.updateBatchForm(index, "avatarFrameResourceId", value)}
                                />
                                <ResourceSelectField
                                    disabled={!page.abilities.canUpdate}
                                    drawerTitle={`选择 Lv.${form.level} 短徽章`}
                                    label="短徽章"
                                    required={false}
                                    resources={withSelectedResource(
                                        levelShortBadgeResourcesForTrack(page.badgeResources, form.track),
                                        form.shortBadgeResourceId,
                                    )}
                                    value={form.shortBadgeResourceId}
                                    onChange={(value) => page.updateBatchForm(index, "shortBadgeResourceId", value)}
                                />
                                <ResourceGroupSelectField
                                    allowEmpty
                                    disabled={!page.abilities.canUpdate}
                                    drawerTitle={`选择 Lv.${form.level} 升级礼物`}
                                    groups={page.resourceGroups}
                                    label="升级礼物"
                                    value={form.rewardResourceGroupId}
                                    onChange={(value) => page.updateBatchForm(index, "rewardResourceGroupId", value)}
                                />
                                <TextField
                                    disabled={!page.abilities.canUpdate}
                                    label="排序"
                                    type="number"
                                    value={form.sortOrder}
                                    onChange={changeBatchField(page, index, "sortOrder")}
                                />
                                <AdminFormSwitchField
                                    checked={form.status === "active"}
                                    checkedLabel="启用"
                                    disabled={!page.abilities.canUpdate}
                                    uncheckedLabel="停用"
                                    onChange={(checked) =>
                                        page.updateBatchForm(index, "status", checked ? "active" : "disabled")
                                    }
                                />
                            </div>
                        </section>
                    );
                })}
            </div>
        </AdminFormDialog>
    );
}

function TierBatchDialog({ page }) {
    return (
        <AdminFormDialog
            disabled={!page.abilities.canUpdate}
            loading={page.loadingAction === "tier-batch-edit"}
            open
            size="full"
            submitDisabled={!page.batchDirty || !page.abilities.canUpdate || page.loadingAction === "tier-batch-edit"}
            submitLabel="保存全部修改"
            title="批量编辑等级层展示与礼物"
            onClose={page.closeAction}
            onSubmit={page.submitTierBatch}
        >
            <div className={styles.list}>
                {page.batchForms.map((form, index) => (
                    <section className={styles.row} key={form.tierId}>
                        <div className={styles.identity}>
                            <strong>
                                {form.minLevel}-{form.maxLevel}
                            </strong>
                            <span>{form.name}</span>
                        </div>
                        <div className={styles.tierFields}>
                            <TextField
                                disabled={!page.abilities.canUpdate}
                                label="起始等级"
                                type="number"
                                value={form.minLevel}
                                onChange={changeBatchField(page, index, "minLevel")}
                            />
                            <TextField
                                disabled={!page.abilities.canUpdate}
                                label="结束等级"
                                type="number"
                                value={form.maxLevel}
                                onChange={changeBatchField(page, index, "maxLevel")}
                            />
                            <TextField
                                disabled={!page.abilities.canUpdate}
                                label="等级层名称"
                                value={form.name}
                                onChange={changeBatchField(page, index, "name")}
                            />
                            <ResourceSelectField
                                disabled={!page.abilities.canUpdate}
                                drawerTitle={`选择 ${form.minLevel}-${form.maxLevel} 头像框`}
                                label="头像框"
                                required={false}
                                resources={withSelectedResource(
                                    levelAvatarFrameResourcesForTrack(page.avatarFrameResources, form.track),
                                    form.displayAvatarFrameResourceId,
                                )}
                                value={form.displayAvatarFrameResourceId}
                                onChange={(value) => page.updateBatchForm(index, "displayAvatarFrameResourceId", value)}
                            />
                            <ResourceSelectField
                                disabled={!page.abilities.canUpdate}
                                drawerTitle={`选择 ${form.minLevel}-${form.maxLevel} 徽章`}
                                label="徽章"
                                required={false}
                                resources={withSelectedResource(
                                    levelBadgeResourcesForTrack(page.badgeResources, form.track),
                                    form.displayBadgeResourceId,
                                )}
                                value={form.displayBadgeResourceId}
                                onChange={(value) => page.updateBatchForm(index, "displayBadgeResourceId", value)}
                            />
                            <ResourceGroupSelectField
                                allowEmpty
                                disabled={!page.abilities.canUpdate}
                                drawerTitle={`选择 ${form.minLevel}-${form.maxLevel} 升级礼物`}
                                groups={page.resourceGroups}
                                label="升级礼物"
                                value={form.rewardResourceGroupId}
                                onChange={(value) => page.updateBatchForm(index, "rewardResourceGroupId", value)}
                            />
                            <AdminFormSwitchField
                                checked={form.status === "active"}
                                checkedLabel="启用"
                                disabled={!page.abilities.canUpdate}
                                uncheckedLabel="停用"
                                onChange={(checked) =>
                                    page.updateBatchForm(index, "status", checked ? "active" : "disabled")
                                }
                            />
                        </div>
                    </section>
                ))}
            </div>
        </AdminFormDialog>
    );
}

function changeBatchField(page, index, key) {
    return (event) => page.updateBatchForm(index, key, event.target.value);
}
