import Inventory2Outlined from "@mui/icons-material/Inventory2Outlined";
import CloseOutlined from "@mui/icons-material/CloseOutlined";
import SearchOutlined from "@mui/icons-material/SearchOutlined";
import IconButton from "@mui/material/IconButton";
import InputAdornment from "@mui/material/InputAdornment";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useMemo, useState } from "react";
import { resourcePriceTypeLabels, resourceTypeLabels } from "@/features/resources/constants.js";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import styles from "@/features/resources/components/ResourceSelectDrawer.module.css";

const drawerZIndex = 1600;
export const categoryMenuZIndex = drawerZIndex + 1;

export function ResourceSelectField({
    disabled = false,
    drawerTitle = "选择资源",
    label = "资源",
    loading = false,
    onChange = () => {},
    placeholder = "请选择资源",
    required = true,
    resources = [],
    value,
}) {
    const [open, setOpen] = useState(false);
    const [query, setQuery] = useState("");
    const [resourceType, setResourceType] = useState("");
    const normalizedValue = String(value || "");
    const selectedResource = resources.find((resource) => String(resource.resourceId) === normalizedValue);
    const displayValue = selectedResource
        ? resourceName(selectedResource)
        : normalizedValue
          ? `资源 #${normalizedValue}`
          : "";
    const resourceTypeOptions = useMemo(() => {
        const seen = new Set();
        return resources
            .map((resource) => resource.resourceType)
            .filter(Boolean)
            .filter((type) => {
                if (seen.has(type)) {
                    return false;
                }
                seen.add(type);
                return true;
            })
            .map((type) => [type, resourceTypeLabels[type] || type])
            .sort(([, labelA], [, labelB]) => labelA.localeCompare(labelB, "zh-Hans-CN"));
    }, [resources]);
    const filteredResources = useMemo(() => {
        const keyword = query.trim().toLowerCase();
        return resources.filter((resource) => {
            if (resourceType && resource.resourceType !== resourceType) {
                return false;
            }
            if (!keyword) {
                return true;
            }
            const haystack = [resource.name, resource.resourceCode, resource.resourceId, resource.resourceType]
                .filter(Boolean)
                .join(" ")
                .toLowerCase();
            return haystack.includes(keyword);
        });
    }, [query, resourceType, resources]);

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

    const selectResource = (resource) => {
        onChange(String(resource.resourceId), resource);
        setOpen(false);
    };

    const clearResource = (event) => {
        event.preventDefault();
        event.stopPropagation();
        onChange("", null);
    };

    return (
        <>
            <TextField
                fullWidth
                className={styles.field}
                disabled={disabled || loading}
                label={label}
                placeholder={loading ? "资源加载中" : placeholder}
                required={required}
                slotProps={{
                    htmlInput: { "aria-haspopup": "dialog", readOnly: true, role: "button" },
                    input:
                        selectedResource && !required
                            ? {
                                  endAdornment: (
                                      <IconButton aria-label="清除资源" edge="end" size="small" onClick={clearResource}>
                                          <CloseOutlined fontSize="small" />
                                      </IconButton>
                                  ),
                              }
                            : undefined,
                }}
                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: drawerZIndex } }}
                open={open}
                title={drawerTitle}
                width="wide"
                onClose={() => setOpen(false)}
            >
                <div className={styles.filters}>
                    <TextField
                        className={styles.search}
                        placeholder="搜索资源名称、编码"
                        slotProps={{
                            input: {
                                startAdornment: (
                                    <InputAdornment position="start">
                                        <SearchOutlined fontSize="small" />
                                    </InputAdornment>
                                ),
                            },
                        }}
                        value={query}
                        onChange={(event) => setQuery(event.target.value)}
                    />
                    <TextField
                        select
                        className={styles.typeFilter}
                        label="分类"
                        slotProps={{
                            select: {
                                MenuProps: {
                                    slotProps: {
                                        root: {
                                            "data-testid": "resource-category-menu-root",
                                            style: { zIndex: categoryMenuZIndex },
                                        },
                                    },
                                },
                            },
                        }}
                        value={resourceType}
                        onChange={(event) => setResourceType(event.target.value)}
                    >
                        <MenuItem value="">全部分类</MenuItem>
                        {resourceTypeOptions.map(([type, label]) => (
                            <MenuItem key={type} value={type}>
                                {label}
                            </MenuItem>
                        ))}
                    </TextField>
                </div>
                <div className={styles.grid}>
                    {filteredResources.map((resource) => {
                        const selected = String(resource.resourceId) === normalizedValue;
                        return (
                            <button
                                className={[styles.card, selected ? styles.cardSelected : ""].filter(Boolean).join(" ")}
                                key={resource.resourceId}
                                type="button"
                                onClick={() => selectResource(resource)}
                            >
                                <ResourceThumb resource={resource} />
                                <span className={styles.name}>{resourceName(resource)}</span>
                                <span className={styles.meta}>
                                    {resource.resourceCode || `ID ${resource.resourceId}`}
                                </span>
                                <span className={styles.tags}>
                                    <span className={styles.tag}>
                                        {resourceTypeLabels[resource.resourceType] || resource.resourceType || "资源"}
                                    </span>
                                    <span className={styles.tag}>{resourcePriceLabel(resource)}</span>
                                </span>
                            </button>
                        );
                    })}
                    {!filteredResources.length ? <div className={styles.empty}>当前无可选资源</div> : null}
                </div>
            </SideDrawer>
        </>
    );
}

function ResourceThumb({ resource }) {
    const imageUrl = imageURL(resource.previewUrl || resource.assetUrl || resource.animationUrl);
    return (
        <span className={styles.thumb}>
            {imageUrl ? <img alt="" src={imageUrl} /> : <Inventory2Outlined fontSize="small" />}
        </span>
    );
}

function resourceName(resource) {
    return resource?.name || resource?.resourceCode || `资源 #${resource?.resourceId || "-"}`;
}

function resourcePriceLabel(resource) {
    const priceType = resource?.priceType;
    if (priceType === "coin") {
        return `金币 ${formatNumber(resource.coinPrice)}`;
    }
    if (priceType === "free") {
        return resourcePriceTypeLabels.free;
    }
    return "未配置价格";
}

function imageURL(value) {
    const url = String(value || "").trim();
    return /\.(avif|gif|jpe?g|png|webp)(\?|#|$)/i.test(url) ? url : "";
}

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