import Add from "@mui/icons-material/Add";
import ImageOutlined from "@mui/icons-material/ImageOutlined";
import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import {
    AdminFormDialog,
    AdminFormFieldGrid,
    AdminFormSection,
    AdminFormSwitchField,
} from "@/shared/ui/AdminFormDialog.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 { MultiValueAutocomplete } from "@/shared/ui/MultiValueAutocomplete.jsx";
import { UploadField } from "@/shared/ui/UploadField.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";
import { emojiPackPricingLabels, resourceStatusFilters } from "@/features/resources/constants.js";
import { useEmojiPackListPage } from "@/features/resources/hooks/useResourcePages.js";
import styles from "@/features/resources/resources.module.css";

const columns = [
    {
        key: "emoji",
        label: "表情包",
        width: "minmax(260px, 1.4fr)",
        render: (item) => <EmojiPackIdentity item={item} />,
    },
    {
        key: "animation",
        label: "动效图",
        width: "minmax(220px, 1.2fr)",
        render: (item) => item.animationUrl || "-",
    },
    {
        key: "category",
        label: "分类 / 类型",
        width: "minmax(150px, 0.75fr)",
        render: (item) => <EmojiPackTags item={item} />,
    },
    {
        key: "regions",
        label: "区域",
        width: "minmax(180px, 0.9fr)",
    },
    {
        key: "status",
        label: "状态",
        width: "minmax(90px, 0.45fr)",
    },
    {
        key: "time",
        label: "更新时间",
        width: "minmax(170px, 0.8fr)",
        render: (item) => formatMillis(item.updatedAtMs || item.createdAtMs),
    },
];

export function EmojiPackListPage() {
    const page = useEmojiPackListPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const regionOptions = [{ label: "全部区域", value: "0" }, ...page.regionOptions];
    const regionLabelById = buildRegionLabelMap(regionOptions);
    const createDisabled = !page.abilities.canCreateEmojiPack || !page.abilities.canUpload;
    const tableColumns = columns.map((column) =>
        column.key === "emoji"
            ? {
                  ...column,
                  filter: createTextColumnFilter({
                      placeholder: "搜索表情包名称",
                      value: page.query,
                      onChange: page.changeQuery,
                  }),
              }
            : column.key === "status"
              ? {
                    ...column,
                    filter: createOptionsColumnFilter({
                        options: resourceStatusFilters,
                        placeholder: "搜索状态",
                        value: page.status,
                        onChange: page.changeStatus,
                    }),
                    render: (item) => <EmojiPackStatusSwitch item={item} page={page} />,
                }
              : column.key === "regions"
                ? {
                      ...column,
                      render: (item) => <RegionTags regionIds={item.regionIds} regionLabelById={regionLabelById} />,
                  }
                : column,
    );

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    page.abilities.canCreateEmojiPack ? (
                        <AdminActionIconButton label="添加表情包" primary onClick={page.openCreateEmojiPack}>
                            <Add fontSize="small" />
                        </AdminActionIconButton>
                    ) : null
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <DataTable
                        columns={tableColumns}
                        items={items}
                        minWidth="1120px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.data.pageSize || 50,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        rowKey={(item) => item.resourceId}
                    />
                </AdminListBody>
            </DataState>
            <EmojiPackFormDialog
                categoryOptions={mergeCategoryOptions(page.categoryOptions, page.form.category)}
                disabled={createDisabled}
                form={page.form}
                loadingCategories={page.categoryOptionsLoading}
                loading={page.loadingAction === "emoji-pack-create"}
                open={page.activeAction === "create"}
                regionLabelById={regionLabelById}
                regionOptions={regionOptions.map((option) => option.value)}
                setForm={page.setForm}
                uploadDisabled={!page.abilities.canUpload}
                onClose={page.closeAction}
                onSubmit={page.submitEmojiPack}
            />
        </AdminListPage>
    );
}

function EmojiPackFormDialog({
    categoryOptions,
    disabled,
    form,
    loadingCategories,
    loading,
    onClose,
    onSubmit,
    open,
    regionLabelById,
    regionOptions,
    setForm,
    uploadDisabled,
}) {
    return (
        <AdminFormDialog
            loading={loading}
            open={open}
            size="large"
            submitDisabled={disabled || loading}
            title="添加表情包"
            onClose={onClose}
            onSubmit={onSubmit}
        >
            <AdminFormSection title="基础信息">
                <AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
                    <TextField
                        disabled={disabled}
                        label="名称"
                        required
                        value={form.name}
                        onChange={(event) => setForm({ ...form, name: event.target.value })}
                    />
                    <Autocomplete
                        freeSolo
                        disabled={disabled}
                        loading={loadingCategories}
                        options={categoryOptions}
                        value={form.category}
                        onChange={(_, value) => setForm({ ...form, category: normalizeCategoryInput(value) })}
                        onInputChange={(_, value) => setForm({ ...form, category: normalizeCategoryInput(value) })}
                        renderInput={(params) => <TextField {...params} label="分类" required />}
                    />
                    <TextField
                        disabled={disabled}
                        label="排序"
                        type="number"
                        value={form.sortOrder}
                        onChange={(event) => setForm({ ...form, sortOrder: event.target.value })}
                    />
                    <MultiValueAutocomplete
                        disabled={disabled}
                        label="区域"
                        labels={regionLabelById}
                        options={regionOptions}
                        value={form.regionIds}
                        onChange={(regionIds) => setForm({ ...form, regionIds: normalizeSelectedRegions(regionIds) })}
                    />
                    <AdminFormSwitchField
                        checked={form.pricingType === "free"}
                        checkedLabel="免费"
                        disabled={disabled}
                        label="付费类型"
                        uncheckedLabel="付费"
                        onChange={(checked) => setForm({ ...form, pricingType: checked ? "free" : "paid" })}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="素材">
                <AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
                    <UploadField
                        disabled={disabled || uploadDisabled}
                        label="封面图"
                        value={form.coverUrl}
                        onChange={(coverUrl) => setForm({ ...form, coverUrl })}
                    />
                    <UploadField
                        disabled={disabled || uploadDisabled}
                        label="动效图"
                        value={form.animationUrl}
                        onChange={(animationUrl) => setForm({ ...form, animationUrl })}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
        </AdminFormDialog>
    );
}

function EmojiPackTags({ item }) {
    const pricingType = item.pricingType || "free";
    return (
        <div className="admin-tag-list">
            <span className="admin-tag">{item.category || "默认"}</span>
            <span className="admin-tag">{emojiPackPricingLabels[pricingType] || pricingType}</span>
        </div>
    );
}

function EmojiPackStatusSwitch({ item, page }) {
    const checked = item.status === "active";
    return (
        <AdminSwitch
            checked={checked}
            disabled={!page.abilities.canUpdate || page.loadingAction === `emoji-pack-status-${item.resourceId}`}
            inputProps={{ "aria-label": checked ? "禁用表情包" : "启用表情包" }}
            onChange={(event) => page.toggleEmojiPack(item, event.target.checked)}
        />
    );
}

function EmojiPackIdentity({ item }) {
    const preview = imageURL(item.coverUrl);
    return (
        <div className={styles.identity}>
            <span className={styles.thumb}>
                {preview ? <img src={preview} alt="" /> : <ImageOutlined fontSize="small" />}
            </span>
            <div className={styles.identityText}>
                <span className={styles.name}>{item.name || "-"}</span>
                <span className={styles.meta}>{item.resourceCode || item.resourceId}</span>
            </div>
        </div>
    );
}

function RegionTags({ regionIds = [], regionLabelById }) {
    const values = regionIds.length ? regionIds.map(String) : ["0"];
    return (
        <div className="admin-tag-list">
            {values.map((value) => (
                <span className="admin-tag" key={value}>
                    {regionLabelById[value] || value}
                </span>
            ))}
        </div>
    );
}

function normalizeSelectedRegions(regionIds) {
    const values = (regionIds || []).map(String);
    if (!values.length || values.includes("0")) {
        return ["0"];
    }
    return values;
}

function normalizeCategoryInput(value) {
    return String(value || "").trimStart();
}

function mergeCategoryOptions(options = [], value = "默认") {
    const merged = new Set(["默认"]);
    options.forEach((option) => {
        const category = String(option || "").trim();
        if (category) {
            merged.add(category);
        }
    });
    const category = String(value || "").trim();
    if (category) {
        merged.add(category);
    }
    return Array.from(merged).sort((left, right) => left.localeCompare(right, "zh-Hans-CN"));
}

function buildRegionLabelMap(regionOptions) {
    return Object.fromEntries(regionOptions.map((option) => [String(option.value), option.label]));
}

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