import CategoryOutlined from "@mui/icons-material/CategoryOutlined";
import Inventory2Outlined from "@mui/icons-material/Inventory2Outlined";
import MonetizationOnOutlined from "@mui/icons-material/MonetizationOnOutlined";
import TextField from "@mui/material/TextField";
import { useState } from "react";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import styles from "@/shared/ui/ResourceGroupSelectDrawer.module.css";

export function ResourceGroupSelectField({
    allowEmpty = false,
    disabled = false,
    drawerTitle = "选择资源组",
    emptyLabel = "不配置",
    groups = [],
    label = "资源组",
    onChange = () => {},
    placeholder = "请选择资源组",
    value,
}) {
    const [open, setOpen] = useState(false);
    const normalizedValue = String(value || "");
    const selectedGroup = groups.find((group) => String(group.groupId) === normalizedValue);
    const displayValue = selectedGroup
        ? resourceGroupName(selectedGroup)
        : normalizedValue
          ? `资源组 #${normalizedValue}`
          : "";

    const openDrawer = () => {
        if (!disabled) {
            setOpen(true);
        }
    };

    const selectGroup = (nextValue, group = null) => {
        onChange(nextValue, group);
        setOpen(false);
    };

    return (
        <>
            <TextField
                fullWidth
                className={styles.field}
                disabled={disabled}
                label={label}
                placeholder={placeholder}
                slotProps={{ htmlInput: { "aria-haspopup": "dialog", readOnly: true, role: "button" } }}
                value={displayValue}
                onClick={openDrawer}
                onKeyDown={(event) => {
                    if (event.key === "Enter" || event.key === " ") {
                        event.preventDefault();
                        openDrawer();
                    }
                }}
            />
            <SideDrawer
                className={styles.drawer}
                contentClassName={styles.drawerBody}
                drawerProps={{ sx: { zIndex: 1600 } }}
                open={open}
                title={drawerTitle}
                width="wide"
                onClose={() => setOpen(false)}
            >
                <div className={styles.groupGrid}>
                    {allowEmpty ? (
                        <button
                            className={[
                                styles.groupCard,
                                styles.emptyCard,
                                normalizedValue ? "" : styles.groupCardSelected,
                            ]
                                .filter(Boolean)
                                .join(" ")}
                            type="button"
                            onClick={() => selectGroup("")}
                        >
                            <span className={styles.groupIcon}>
                                <CategoryOutlined fontSize="small" />
                            </span>
                            <span className={styles.groupName}>{emptyLabel}</span>
                        </button>
                    ) : null}
                    {groups.map((group) => {
                        const groupValue = String(group.groupId);
                        const selected = groupValue === normalizedValue;
                        return (
                            <button
                                className={[styles.groupCard, selected ? styles.groupCardSelected : ""]
                                    .filter(Boolean)
                                    .join(" ")}
                                key={group.groupId}
                                type="button"
                                onClick={() => selectGroup(groupValue, group)}
                            >
                                <GroupIcon group={group} />
                                <span className={styles.groupName}>{resourceGroupName(group)}</span>
                                <span className={styles.groupMeta}>{group.groupCode || `ID ${group.groupId}`}</span>
                                <GroupItems group={group} />
                            </button>
                        );
                    })}
                    {!groups.length && !allowEmpty ? <div className={styles.emptyState}>当前无数据</div> : null}
                </div>
            </SideDrawer>
        </>
    );
}

function GroupIcon({ group }) {
    const item = firstGroupItem(group);
    const imageUrl = item?.resource?.previewUrl || item?.resource?.assetUrl || item?.resource?.animationUrl;

    if (imageUrl) {
        return (
            <span className={styles.groupIcon}>
                <img alt="" src={imageUrl} />
            </span>
        );
    }

    if (item?.itemType === "wallet_asset" && item.walletAssetType === "COIN") {
        return (
            <span className={styles.groupIcon}>
                <MonetizationOnOutlined fontSize="small" />
            </span>
        );
    }

    if (item?.itemType === "resource") {
        return (
            <span className={styles.groupIcon}>
                <Inventory2Outlined fontSize="small" />
            </span>
        );
    }

    return (
        <span className={styles.groupIcon}>
            <CategoryOutlined fontSize="small" />
        </span>
    );
}

function GroupItems({ group }) {
    const items = (group.items || []).slice(0, 3);
    if (!items.length) {
        return <span className={styles.groupMeta}>无资源条目</span>;
    }

    return (
        <span className={styles.groupItems}>
            {items.map((item, index) => (
                <span className={styles.groupItem} key={item.groupItemId || `${item.itemType}-${index}`}>
                    {groupItemLabel(item)}
                </span>
            ))}
            {(group.items || []).length > items.length ? (
                <span className={styles.groupItem}>+{(group.items || []).length - items.length}</span>
            ) : null}
        </span>
    );
}

function firstGroupItem(group) {
    return (
        (group.items || []).find((item) => item?.resource?.previewUrl || item?.resource?.assetUrl) || group.items?.[0]
    );
}

function groupItemLabel(item) {
    if (item.itemType === "wallet_asset") {
        const label =
            item.walletAssetType === "COIN" ? "金币" : "钱包资产";
        return `${label} ${formatNumber(item.walletAssetAmount)}`;
    }

    return item.resource?.name || item.resource?.resourceCode || `资源 ${item.resourceId || "-"}`;
}

function resourceGroupName(group) {
    return group.name || group.groupCode || `资源组 #${group.groupId}`;
}

function formatNumber(value) {
    return Number(value || 0).toLocaleString("zh-CN");
}
