import Add from "@mui/icons-material/Add";
import ReceiptLongOutlined from "@mui/icons-material/ReceiptLongOutlined";
import StorefrontOutlined from "@mui/icons-material/StorefrontOutlined";
import Checkbox from "@mui/material/Checkbox";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import {
    AdminActionIconButton,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
} from "@/shared/ui/AdminListLayout.jsx";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { createOptionsColumnFilter, createTextColumnFilter, createUserIdentityColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";
import {
    resourcePriceTypeLabels,
    resourceShopDurationOptions,
    resourceShopTypeFilters,
    resourceStatusFilters,
    resourceTypeLabels,
} from "@/features/resources/constants.js";
import {
    canUnselectResourceShopDraftGroup,
    canUnselectResourceShopDraftSpec,
    useResourceShopPage,
} from "@/features/resources/hooks/useResourcePages.js";
import styles from "@/features/resources/resources.module.css";

const shopColumns = [
    {
        key: "resource",
        label: "售卖资源",
        width: "minmax(270px, 1.4fr)",
        render: (item) => <ResourceIdentity resource={item.resource} />,
    },
    {
        key: "type",
        label: "类型",
        width: "minmax(120px, 0.65fr)",
        render: (item) => resourceTypeLabels[item.resource?.resourceType] || item.resource?.resourceType || "-",
    },
    {
        key: "sale",
        label: "售卖规格",
        width: "minmax(150px, 0.8fr)",
        render: (item) => <SaleSpec item={item} />,
    },
    {
        key: "effective",
        label: "生效时间",
        width: "minmax(220px, 1fr)",
        render: (item) => <EffectiveTime item={item} />,
    },
    {
        key: "sort",
        label: "排序",
        width: "minmax(80px, 0.4fr)",
        render: (item) => item.sortOrder ?? 0,
    },
    {
        key: "status",
        label: "状态",
        width: "minmax(92px, 0.5fr)",
    },
    {
        key: "time",
        label: "更新时间",
        width: "minmax(170px, 0.8fr)",
        render: (item) => formatMillis(item.updatedAtMs || item.createdAtMs),
    },
];

const purchaseColumns = [
    {
        key: "user",
        label: "用户信息",
        width: "minmax(210px, 1fr)",
        render: (item) => <PurchaseUser order={item} />,
    },
    {
        key: "resourceType",
        label: "道具类型",
        width: "minmax(120px, 0.55fr)",
        render: (item) => resourceTypeLabels[item.resource?.resourceType] || item.resource?.resourceType || "-",
    },
    {
        key: "resource",
        label: "购买素材",
        width: "minmax(260px, 1.1fr)",
        render: (item) => <ResourceIdentity resource={item.resource} />,
    },
    {
        key: "price",
        label: "购买价格",
        width: "minmax(130px, 0.55fr)",
        render: (item) => coinPriceLabel(item.priceCoin),
    },
    {
        key: "time",
        label: "购买时间",
        width: "minmax(170px, 0.7fr)",
        render: (item) => formatMillis(item.createdAtMs),
    },
];

export function ResourceShopPage() {
    const page = useResourceShopPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const columns = shopColumns.map((column) => {
        if (column.key === "resource") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索资源名称、资源编码",
                    value: page.query,
                    onChange: page.changeQuery,
                }),
            };
        }
        if (column.key === "type") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: resourceShopTypeFilters,
                    placeholder: "搜索类型",
                    value: page.resourceType,
                    onChange: page.changeResourceType,
                }),
            };
        }
        if (column.key === "status") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: resourceStatusFilters,
                    placeholder: "搜索状态",
                    value: page.status,
                    onChange: page.changeStatus,
                }),
                render: (item) => <ResourceShopStatusSwitch item={item} page={page} />,
            };
        }
        return column;
    });

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    <>
                        {page.abilities.canViewShop ? (
                            <AdminActionIconButton label="售卖记录" onClick={page.openPurchaseDrawer}>
                                <ReceiptLongOutlined fontSize="small" />
                            </AdminActionIconButton>
                        ) : null}
                        {page.abilities.canUpdateShop ? (
                            <AdminActionIconButton label="添加售卖资源" primary onClick={page.openShopDrawer}>
                                <Add fontSize="small" />
                            </AdminActionIconButton>
                        ) : null}
                    </>
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={items}
                        minWidth="1120px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.data.pageSize || 50,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        rowKey={(item) => item.shopItemId}
                    />
                </AdminListBody>
            </DataState>
            <ResourceShopDrawer page={page} />
            <ResourceShopPurchaseDrawer page={page} />
        </AdminListPage>
    );
}

function ResourceShopDrawer({ page }) {
    const saving = page.loadingAction === "resource-shop-upsert";
    const disabled = !page.abilities.canUpdateShop || saving;
    return (
        <SideDrawer
            actions={
                <>
                    <Button disabled={saving} onClick={page.closeShopDrawer}>
                        取消
                    </Button>
                    <Button
                        disabled={
                            disabled ||
                            page.resourceOptionsLoading ||
                            Boolean(page.resourceOptionsError) ||
                            page.selectedDrafts.length === 0
                        }
                        type="submit"
                        variant="primary"
                    >
                        保存
                    </Button>
                </>
            }
            as="form"
            open={page.drawerOpen}
            title="添加售卖资源"
            width="detail"
            onClose={saving ? undefined : page.closeShopDrawer}
            onSubmit={page.submitShopItems}
        >
            <div className={styles.shopDrawerTools}>
                <TextField
                    label="搜索资源"
                    size="small"
                    value={page.drawerQuery}
                    onChange={(event) => page.changeDrawerQuery(event.target.value)}
                />
                <TextField
                    label="资源类型"
                    select
                    size="small"
                    value={page.drawerResourceType}
                    onChange={(event) => page.changeDrawerResourceType(event.target.value)}
                >
                    {resourceShopTypeFilters.map(([value, label]) => (
                        <MenuItem key={value || "all"} value={value}>
                            {label}
                        </MenuItem>
                    ))}
                </TextField>
            </div>
            <DataState
                error={page.resourceOptionsError}
                loading={page.resourceOptionsLoading}
                onRetry={page.reloadShopDrawerOptions}
            >
                {page.filteredResourceOptions.length > 0 ? (
                    <div className={styles.shopSelectionList}>
                        {page.filteredResourceOptions.map((resource) => (
                            <ResourceSelectionRow
                                disabled={disabled}
                                key={resource.resourceId}
                                page={page}
                                resource={resource}
                            />
                        ))}
                    </div>
                ) : (
                    <div className={styles.shopEmpty}>暂无可售卖资源</div>
                )}
            </DataState>
        </SideDrawer>
    );
}

function ResourceShopPurchaseDrawer({ page }) {
    const data = page.purchaseData || {};
    const items = data.items || [];
    const total = data.total || 0;
    const columns = purchaseColumns.map((column) => {
        if (column.key === "user") {
            return {
                ...column,
                filter: createUserIdentityColumnFilter({
                    value: page.purchaseUserFilter,
                    onChange: page.changePurchaseUserFilter,
                }),
            };
        }
        if (column.key === "resourceType") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: resourceShopTypeFilters,
                    placeholder: "搜索道具类型",
                    value: page.purchaseResourceType,
                    onChange: page.changePurchaseResourceType,
                }),
            };
        }
        if (column.key === "resource") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索素材名称、素材编码、订单号",
                    value: page.purchaseKeyword,
                    onChange: page.changePurchaseKeyword,
                }),
            };
        }
        return column;
    });

    return (
        <SideDrawer open={page.purchaseDrawerOpen} title="售卖记录" width="wide" onClose={page.closePurchaseDrawer}>
            <DataState error={page.purchaseError} loading={page.purchaseLoading} onRetry={page.reloadPurchaseOrders}>
                <DataTable
                    columns={columns}
                    items={items}
                    minWidth="980px"
                    pagination={
                        total > 0
                            ? {
                                  page: page.purchasePage,
                                  pageSize: data.pageSize || 50,
                                  total,
                                  onPageChange: page.setPurchasePage,
                              }
                            : undefined
                    }
                    rowKey={(item) => item.orderId}
                />
            </DataState>
        </SideDrawer>
    );
}

function ResourceSelectionRow({ disabled, page, resource }) {
    const resourceId = String(resource.resourceId);
    const selected = page.selectedResourceIds.has(resourceId);
    const draftGroup = selected ? page.draftByResourceId[resourceId] : null;
    const canUnselectGroup = !draftGroup || canUnselectResourceShopDraftGroup(draftGroup);
    return (
        <div className={styles.shopSelectionRow}>
            <Checkbox
                checked={selected}
                disabled={disabled || !canUnselectGroup}
                inputProps={{
                    "aria-label":
                        !canUnselectGroup
                            ? "资源已有售卖规格，请在列表启停"
                            : selected
                              ? "取消选择资源"
                              : "选择资源",
                }}
                onChange={() => page.toggleDraftResource(resource)}
            />
            <ResourceIdentity resource={resource} />
            <span className={styles.shopBasePrice}>资源价 {resourcePriceLabel(resource)}</span>
            {draftGroup ? (
                <div className={styles.shopSpecList}>
                    {resourceShopDurationOptions.map(([durationDays, label]) => (
                        <ResourceShopSpecRow
                            disabled={disabled}
                            draft={draftGroup.specsByDuration?.[durationDays]}
                            durationDays={durationDays}
                            key={durationDays}
                            label={label}
                            page={page}
                            resource={resource}
                        />
                    ))}
                </div>
            ) : null}
        </div>
    );
}

function ResourceShopSpecRow({ disabled, draft, durationDays, label, page, resource }) {
    const resourceId = String(resource.resourceId);
    const updateDraft = (patch) => page.updateDraftSpec(resourceId, durationDays, patch);
    return (
        <div className={styles.shopSpecRow}>
            <label className={styles.shopSpecToggle}>
                <Checkbox
                    checked={Boolean(draft)}
                    disabled={disabled || (draft && !canUnselectResourceShopDraftSpec(draft))}
                    inputProps={{
                        "aria-label": draft?.shopItemId ? `${label}售卖规格已保存，请在列表启停` : `${label}售卖规格`,
                    }}
                    onChange={() => page.toggleDraftDuration(resource, durationDays)}
                />
                <span>{label}</span>
            </label>
            {draft ? (
                <>
                    <TextField
                        disabled={disabled}
                        inputProps={{ min: 1, step: 1 }}
                        label="售卖价格"
                        required
                        size="small"
                        type="number"
                        value={draft.coinPrice}
                        onChange={(event) => updateDraft({ coinPrice: event.target.value })}
                    />
                    <TimeRangeFilter
                        className={styles.shopSpecTimeRange}
                        disabled={disabled}
                        label="生效时间"
                        value={{ endMs: draft.effectiveToMs, startMs: draft.effectiveFromMs }}
                        onChange={(range) =>
                            updateDraft({ effectiveFromMs: range.startMs, effectiveToMs: range.endMs })
                        }
                    />
                    <TextField
                        disabled={disabled}
                        inputProps={{ min: 0, step: 1 }}
                        label="排序"
                        size="small"
                        type="number"
                        value={draft.sortOrder}
                        onChange={(event) => updateDraft({ sortOrder: event.target.value })}
                    />
                </>
            ) : (
                <span className={styles.shopSpecDisabled}>未售卖</span>
            )}
        </div>
    );
}

function ResourceShopStatusSwitch({ item, page }) {
    const checked = item.status === "active";
    return (
        <AdminSwitch
            checked={checked}
            disabled={!page.abilities.canUpdateShop || page.loadingAction === `resource-shop-status-${item.shopItemId}`}
            inputProps={{ "aria-label": checked ? "禁用售卖资源" : "启用售卖资源" }}
            onChange={(event) => page.toggleShopItem(item, event.target.checked)}
        />
    );
}

function ResourceIdentity({ resource = {} }) {
    const imageUrl = resource.previewUrl || resource.assetUrl || resource.animationUrl;
    return (
        <div className={styles.identity}>
            <span className={styles.thumb}>
                {imageUrl ? <img alt="" src={imageUrl} /> : <StorefrontOutlined fontSize="small" />}
            </span>
            <span className={styles.identityText}>
                <span className={styles.name}>{resource.name || "-"}</span>
                <span className={styles.meta}>{resource.resourceCode || resource.resourceId || "-"}</span>
            </span>
        </div>
    );
}

function PurchaseUser({ order }) {
    const user = order.user || { userId: order.userId };
    if (!user?.userId && !user?.displayUserId && !user?.username) {
        return "-";
    }
    return <AdminUserIdentity openInAppUserDetail user={user} />;
}

function SaleSpec({ item }) {
    return (
        <div className={styles.stack}>
            <span>{item.durationDays || 1}天</span>
            <span className={styles.meta}>{resourcePriceLabel(item)}</span>
        </div>
    );
}

function EffectiveTime({ item }) {
    const from = item.effectiveFromMs ? formatMillis(item.effectiveFromMs) : "立即生效";
    const to = item.effectiveToMs ? formatMillis(item.effectiveToMs) : "长期";
    return (
        <div className={styles.stack}>
            <span>{from}</span>
            <span className={styles.meta}>{to}</span>
        </div>
    );
}

function resourcePriceLabel(item = {}) {
    if (item.priceType === "coin" || item.coinPrice > 0) {
        return `${item.coinPrice || 0}金币`;
    }
    return resourcePriceTypeLabels[item.priceType] || "-";
}

function coinPriceLabel(value) {
    if (value === 0 || value) {
        return `${Number(value).toLocaleString("zh-CN")}金币`;
    }
    return "-";
}
