import CardGiftcardOutlined from "@mui/icons-material/CardGiftcardOutlined";
import SearchOutlined from "@mui/icons-material/SearchOutlined";
import InputAdornment from "@mui/material/InputAdornment";
import TextField from "@mui/material/TextField";
import { useMemo, useState } from "react";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import styles from "@/features/resources/components/ResourceSelectDrawer.module.css";

const drawerZIndex = 1600;

export function GiftSelectField({
    disabled = false,
    drawerTitle = "选择礼物",
    fallbackGift = null,
    gifts = [],
    label = "礼物",
    loading = false,
    onChange = () => {},
    placeholder = "请选择礼物",
    required = true,
    value,
}) {
    const picker = useGiftPicker({ fallbackGift, gifts, loading, onChange, value });
    const displayValue = picker.selectedGift
        ? giftName(picker.selectedGift)
        : picker.normalizedValue
          ? `礼物 #${picker.normalizedValue}`
          : "";

    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" } }}
                value={displayValue}
                onClick={picker.openDrawer}
                onKeyDown={(event) => {
                    if (event.key === "Enter" || event.key === " ") {
                        event.preventDefault();
                        picker.openDrawer();
                    }
                }}
            />
            <GiftSelectDrawerContent drawerTitle={drawerTitle} picker={picker} />
        </>
    );
}

export function GiftPreviewSelectField({
    badge = "",
    className = "",
    disabled = false,
    drawerTitle = "选择礼物",
    fallbackGift = null,
    gifts = [],
    label = "礼物",
    loading = false,
    onChange = () => {},
    placeholder = "请选择礼物",
    required = true,
    value,
}) {
    const picker = useGiftPicker({ fallbackGift, gifts, loading, onChange, value });
    const selectedGift = picker.selectedGift;

    return (
        <>
            <button
                aria-label={`${label} ${selectedGift ? giftName(selectedGift) : placeholder}`}
                className={[styles.previewField, className].filter(Boolean).join(" ")}
                disabled={disabled || loading}
                type="button"
                onClick={picker.openDrawer}
            >
                <span className={styles.previewTop}>
                    <span className={styles.previewLabel}>
                        {label}
                        {required ? <span className={styles.previewRequired}>*</span> : null}
                    </span>
                    {badge ? <span className={styles.previewBadge}>{badge}</span> : null}
                </span>
                <span className={styles.previewBody}>
                    <GiftThumb className={styles.previewThumb} gift={selectedGift} />
                    <span className={styles.previewCopy}>
                        <span className={styles.previewName}>
                            {selectedGift ? giftName(selectedGift) : loading ? "礼物加载中" : placeholder}
                        </span>
                        <span className={styles.previewMeta}>
                            {selectedGift
                                ? `${giftIdentity(selectedGift)} · 金币 ${formatNumber(giftCoinPrice(selectedGift))}`
                                : "点击选择礼物"}
                        </span>
                    </span>
                </span>
            </button>
            <GiftSelectDrawerContent drawerTitle={drawerTitle} picker={picker} />
        </>
    );
}

function GiftSelectDrawerContent({ drawerTitle, picker }) {
    return (
        <SideDrawer
            className={styles.drawer}
            contentClassName={styles.drawerBody}
            drawerProps={{ sx: { zIndex: drawerZIndex } }}
            open={picker.open}
            title={drawerTitle}
            width="wide"
            onClose={picker.closeDrawer}
        >
            <div className={styles.filters}>
                <TextField
                    className={styles.search}
                    placeholder="搜索礼物名称、礼物 ID、资源编码"
                    slotProps={{
                        input: {
                            startAdornment: (
                                <InputAdornment position="start">
                                    <SearchOutlined fontSize="small" />
                                </InputAdornment>
                            ),
                        },
                    }}
                    value={picker.query}
                    onChange={(event) => picker.setQuery(event.target.value)}
                />
            </div>
            <div className={styles.grid}>
                {picker.filteredGifts.map((gift) => {
                    const selected = String(gift.giftId) === picker.normalizedValue;
                    return (
                        <button
                            className={[styles.card, selected ? styles.cardSelected : ""].filter(Boolean).join(" ")}
                            key={gift.giftId}
                            type="button"
                            onClick={() => picker.selectGift(gift)}
                        >
                            <GiftThumb gift={gift} />
                            <span className={styles.name}>{giftName(gift)}</span>
                            <span className={styles.meta}>{giftIdentity(gift)}</span>
                            <span className={styles.tags}>
                                <span className={styles.tag}>{gift.giftTypeCode || "普通礼物"}</span>
                                <span className={styles.tag}>金币 {formatNumber(giftCoinPrice(gift))}</span>
                            </span>
                        </button>
                    );
                })}
                {!picker.filteredGifts.length ? <div className={styles.empty}>当前无可选礼物</div> : null}
            </div>
        </SideDrawer>
    );
}

function useGiftPicker({ fallbackGift, gifts, loading, onChange, value }) {
    const [open, setOpen] = useState(false);
    const [query, setQuery] = useState("");
    const normalizedValue = String(value || "");
    const selectedGift =
        gifts.find((gift) => String(gift.giftId) === normalizedValue) ||
        (normalizedValue && fallbackGift && String(fallbackGift.giftId || "") === normalizedValue ? fallbackGift : null);
    const filteredGifts = useMemo(() => {
        const keyword = query.trim().toLowerCase();
        if (!keyword) {
            return gifts;
        }
        return gifts.filter((gift) =>
            [
                gift.name,
                gift.giftId,
                gift.giftTypeCode,
                gift.resource?.name,
                gift.resource?.resourceCode,
                gift.resource?.resourceId,
            ]
                .filter(Boolean)
                .join(" ")
                .toLowerCase()
                .includes(keyword),
        );
    }, [gifts, query]);

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

    const closeDrawer = () => setOpen(false);

    const selectGift = (gift) => {
        onChange(String(gift.giftId), gift);
        setOpen(false);
    };

    return {
        closeDrawer,
        filteredGifts,
        normalizedValue,
        open,
        openDrawer,
        query,
        selectGift,
        selectedGift,
        setQuery,
    };
}

function GiftThumb({ className = "", gift }) {
    const imageUrl = imageURL(
        gift?.resource?.previewUrl || gift?.resource?.assetUrl || gift?.resource?.animationUrl || gift?.giftIconUrl,
    );
    const [failedUrl, setFailedUrl] = useState("");
    const displayImageUrl = imageUrl && imageUrl !== failedUrl ? imageUrl : "";
    return (
        <span className={[styles.thumb, className].filter(Boolean).join(" ")}>
            {displayImageUrl ? (
                <img alt="" src={displayImageUrl} onError={() => setFailedUrl(displayImageUrl)} />
            ) : (
                <CardGiftcardOutlined fontSize="small" />
            )}
        </span>
    );
}

function giftName(gift) {
    return gift?.name || gift?.giftName || gift?.resource?.name || gift?.giftId || "礼物";
}

function giftIdentity(gift) {
    return gift?.resource?.resourceCode || gift?.giftId || `资源 ${gift?.resourceId || "-"}`;
}

function giftCoinPrice(gift) {
    return gift?.coinPrice ?? gift?.giftPriceCoin ?? gift?.resource?.coinPrice ?? 0;
}

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");
}
