import DownloadOutlined from "@mui/icons-material/DownloadOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import MenuItem from "@mui/material/MenuItem";
import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs";
import TextField from "@mui/material/TextField";
import { ActivityTemplateDataOverview } from "@/features/activity-templates/components/ActivityTemplateDataOverview.jsx";
import { ActivityTemplateLeaderboardPanel } from "@/features/activity-templates/components/ActivityTemplateLeaderboardPanel.jsx";
import { ActivityTemplateRewardsPanel } from "@/features/activity-templates/components/ActivityTemplateRewardsPanel.jsx";
import { ActivityTemplateTaskClaimsPanel } from "@/features/activity-templates/components/ActivityTemplateTaskClaimsPanel.jsx";
import { useActivityTemplateDataCenter } from "@/features/activity-templates/hooks/useActivityTemplateDataCenter.js";
import { Button } from "@/shared/ui/Button.jsx";
import { RegionFilterControl } from "@/shared/ui/RegionFilterControl.jsx";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import styles from "@/features/activity-templates/activity-templates.module.css";

const tabs = [
    ["overview", "活动数据"],
    ["leaderboard", "榜单"],
    ["rewards", "榜单奖励"],
    ["taskClaims", "任务领奖"],
];

export function ActivityTemplateDataDrawer({ abilities, loadingRegions, onClose, open, regionOptions, source }) {
    const dataCenter = useActivityTemplateDataCenter({ abilities, regionOptions, source });
    const activeReload =
        dataCenter.activeTab === "leaderboard"
            ? dataCenter.reloadLeaderboard
            : dataCenter.activeTab === "rewards"
              ? dataCenter.reloadRewards
              : dataCenter.activeTab === "taskClaims"
                ? dataCenter.reloadTaskClaims
              : dataCenter.reloadData;

    return (
        <SideDrawer
            className={styles.dataDrawer}
            contentClassName={styles.dataDrawerBody}
            open={open}
            title={`数据中心 · ${source?.name || "-"}`}
            onClose={onClose}
        >
            <div className={styles.dataHeader}>
                <div className={styles.dataIdentity}>
                    <strong>{source?.templateCode || source?.templateId || "-"}</strong>
                    <span>发布 v{dataCenter.versionNo || 0}</span>
                </div>
                <div className={styles.dataHeaderActions}>
                    <Button startIcon={<RefreshOutlined fontSize="small" />} onClick={activeReload}>
                        刷新
                    </Button>
                    {abilities.canExport && dataCenter.activeTab === "overview" ? (
                        <Button
                            disabled={!dataCenter.dataParams || dataCenter.loadingAction === "export"}
                            startIcon={<DownloadOutlined fontSize="small" />}
                            variant="primary"
                            onClick={dataCenter.exportData}
                        >
                            {dataCenter.loadingAction === "export" ? "导出中" : "导出 CSV"}
                        </Button>
                    ) : null}
                </div>
            </div>
            <div className={styles.dataFilterBar}>
                <TextField
                    disabled={dataCenter.versionsLoading && !dataCenter.versionItems.length}
                    label="发布版本"
                    select
                    size="small"
                    value={String(dataCenter.versionNo || "")}
                    onChange={(event) => dataCenter.changeVersion(event.target.value)}
                >
                    {dataCenter.versionItems.map((item) => (
                        <MenuItem key={item.versionNo} value={String(item.versionNo)}>
                            v{item.versionNo}
                        </MenuItem>
                    ))}
                </TextField>
                {dataCenter.activeTab === "overview" ? (
                    <>
                        <RegionFilterControl
                            emptyLabel="全部区域"
                            label="统计区域"
                            loading={loadingRegions}
                            options={dataCenter.scopedRegionOptions}
                            value={dataCenter.regionId}
                            onChange={dataCenter.setRegionId}
                        />
                        <TimeRangeFilter
                            label="统计日期"
                            value={dataCenter.timeRange}
                            withTime={false}
                            onChange={dataCenter.setTimeRange}
                        />
                    </>
                ) : null}
                {dataCenter.versionsError ? (
                    <button className={styles.inlineErrorButton} type="button" onClick={dataCenter.reloadVersions}>
                        发布版本加载失败，重试
                    </button>
                ) : null}
            </div>
            <Tabs
                className={styles.dataTabs}
                value={dataCenter.activeTab}
                onChange={(_, value) => dataCenter.setActiveTab(value)}
            >
                {tabs.map(([value, label]) => (
                    <Tab key={value} label={label} value={value} />
                ))}
            </Tabs>
            <div className={styles.dataTabContent}>
                {dataCenter.activeTab === "overview" ? (
                    <ActivityTemplateDataOverview
                        data={dataCenter.data}
                        error={dataCenter.dataError}
                        loading={dataCenter.dataLoading}
                        template={dataCenter.selectedTemplate}
                        onRetry={dataCenter.reloadData}
                    />
                ) : null}
                {dataCenter.activeTab === "leaderboard" ? (
                    <ActivityTemplateLeaderboardPanel
                        boardType={dataCenter.leaderboardBoardType}
                        data={dataCenter.leaderboard}
                        error={dataCenter.leaderboardError}
                        loading={dataCenter.leaderboardLoading}
                        page={dataCenter.leaderboardPage}
                        periodKey={dataCenter.leaderboardPeriodKey}
                        periodOptions={dataCenter.periodOptions}
                        onBoardTypeChange={dataCenter.changeLeaderboardBoardType}
                        onPageChange={dataCenter.setLeaderboardPage}
                        onPeriodChange={dataCenter.setLeaderboardPeriodKey}
                        onRetry={dataCenter.reloadLeaderboard}
                    />
                ) : null}
                {dataCenter.activeTab === "rewards" ? (
                    <ActivityTemplateRewardsPanel
                        abilities={abilities}
                        boardType={dataCenter.rewardBoardType}
                        data={dataCenter.rewards}
                        error={dataCenter.rewardsError}
                        loading={dataCenter.rewardsLoading}
                        loadingAction={dataCenter.loadingAction}
                        page={dataCenter.rewardPage}
                        periodKey={dataCenter.rewardPeriodKey}
                        periodOptions={dataCenter.periodOptions}
                        status={dataCenter.rewardStatus}
                        onBoardTypeChange={dataCenter.changeRewardBoardType}
                        onPageChange={dataCenter.setRewardPage}
                        onPeriodChange={dataCenter.setRewardPeriodKey}
                        onRetry={dataCenter.reloadRewards}
                        onRetryJob={dataCenter.retryReward}
                        onStatusChange={dataCenter.setRewardStatus}
                    />
                ) : null}
                {dataCenter.activeTab === "taskClaims" ? (
                    <ActivityTemplateTaskClaimsPanel
                        abilities={abilities}
                        data={dataCenter.taskClaims}
                        error={dataCenter.taskClaimsError}
                        loading={dataCenter.taskClaimsLoading}
                        loadingAction={dataCenter.loadingAction}
                        page={dataCenter.taskClaimPage}
                        periodOptions={dataCenter.periodOptions}
                        status={dataCenter.taskClaimStatus}
                        taskDay={dataCenter.taskClaimDay}
                        taskKey={dataCenter.taskClaimKey}
                        taskOptions={dataCenter.selectedTemplate.tasks || []}
                        userId={dataCenter.taskClaimUserId}
                        onDayChange={dataCenter.setTaskClaimDay}
                        onPageChange={dataCenter.setTaskClaimPage}
                        onRetry={dataCenter.reloadTaskClaims}
                        onRetryClaim={dataCenter.retryTaskClaim}
                        onStatusChange={dataCenter.setTaskClaimStatus}
                        onTaskKeyChange={dataCenter.setTaskClaimKey}
                        onUserIdChange={dataCenter.setTaskClaimUserId}
                    />
                ) : null}
            </div>
        </SideDrawer>
    );
}
