import MeetingRoomOutlined from "@mui/icons-material/MeetingRoomOutlined";
import PersonOutlineOutlined from "@mui/icons-material/PersonOutlineOutlined";
import { useMemo, useState } from "react";
import { listReports } from "@/features/operations/api";
import styles from "@/features/operations/operations.module.css";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import {
    AdminFilterResetButton,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
} from "@/shared/ui/AdminListLayout.jsx";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";

const pageSize = 50;

const targetTypeOptions = [
    { label: "全部目标", value: "" },
    { label: "用户", value: "user" },
    { label: "房间", value: "room" },
];

const reportTypeOptions = [
    { label: "全部类型", value: "" },
    { label: "政治", value: "politics" },
    { label: "色情", value: "pornography" },
    { label: "血腥暴力", value: "graphic_violence" },
    { label: "言语辱骂", value: "verbal_abuse" },
    { label: "欺诈", value: "fraud" },
    { label: "违法内容", value: "illegal_content" },
    { label: "未成年人", value: "minors" },
    { label: "线下交易", value: "in_person_transactions" },
    { label: "其他", value: "other" },
];

const columns = [
    {
        key: "targetType",
        label: "举报目标",
        render: (report) => <TargetTypeLabel report={report} />,
        width: "minmax(120px, 0.55fr)",
    },
    {
        key: "target",
        label: "举报信息",
        render: (report) => <TargetCell report={report} />,
        width: "minmax(300px, 1.3fr)",
    },
    {
        key: "reportType",
        label: "举报类型",
        render: (report) => reportTypeLabel(report.reportType),
        width: "minmax(150px, 0.7fr)",
    },
    {
        key: "reason",
        label: "举报理由",
        render: (report) => <span className={styles.reportReason}>{report.reason || "-"}</span>,
        width: "minmax(220px, 1fr)",
    },
    {
        key: "imageUrls",
        label: "举报图片",
        render: (report) => <EvidenceImages imageUrls={report.imageUrls} />,
        width: "minmax(180px, 0.8fr)",
    },
    {
        key: "createdAtMs",
        label: "提交时间",
        render: (report) => formatMillis(report.createdAtMs),
        width: "minmax(170px, 0.75fr)",
    },
];

export function ReportListPage() {
    const [page, setPage] = useState(1);
    const [keyword, setKeyword] = useState("");
    const [targetType, setTargetType] = useState("");
    const [reportType, setReportType] = useState("");
    const [timeRange, setTimeRange] = useState({ endMs: "", startMs: "" });

    const filters = useMemo(
        () => ({
            end_at_ms: timeRange.endMs || "",
            keyword,
            report_type: reportType,
            start_at_ms: timeRange.startMs || "",
            target_type: targetType,
        }),
        [keyword, reportType, targetType, timeRange.endMs, timeRange.startMs],
    );
    const query = usePaginatedQuery({
        errorMessage: "获取举报列表失败",
        fetcher: listReports,
        filters,
        page,
        pageSize,
        queryKey: ["reports", filters, page],
    });
    const data = query.data || { items: [], total: 0, page, pageSize };
    const items = data.items || [];
    const total = data.total || 0;

    const changeFilter = (setter) => (value) => {
        setter(value);
        setPage(1);
    };
    const changeTimeRange = (nextRange) => {
        setTimeRange(nextRange);
        setPage(1);
    };
    const resetFilters = () => {
        setKeyword("");
        setTargetType("");
        setReportType("");
        setTimeRange({ endMs: "", startMs: "" });
        setPage(1);
    };

    const tableColumns = columns.map((column) => {
        if (column.key === "target") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "长 ID / 短 ID / 昵称",
                    value: keyword,
                    onChange: changeFilter(setKeyword),
                }),
            };
        }
        if (column.key === "targetType") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: targetTypeOptions,
                    value: targetType,
                    onChange: changeFilter(setTargetType),
                }),
            };
        }
        if (column.key === "reportType") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: reportTypeOptions,
                    value: reportType,
                    onChange: changeFilter(setReportType),
                }),
            };
        }
        return column;
    });

    return (
        <AdminListPage>
            <AdminListToolbar
                filters={
                    <>
                        <TimeRangeFilter value={timeRange} onChange={changeTimeRange} />
                        <AdminFilterResetButton
                            disabled={!keyword && !targetType && !reportType && !timeRange.startMs && !timeRange.endMs}
                            onClick={resetFilters}
                        />
                    </>
                }
            />
            <DataState error={query.error} loading={query.loading} onRetry={query.reload}>
                <AdminListBody>
                    <DataTable
                        columns={tableColumns}
                        items={items}
                        minWidth="1140px"
                        pagination={
                            total > 0
                                ? {
                                      page,
                                      pageSize: data.pageSize || pageSize,
                                      total,
                                      onPageChange: setPage,
                                  }
                                : undefined
                        }
                        rowKey={(report) => report.reportId}
                    />
                </AdminListBody>
            </DataState>
        </AdminListPage>
    );
}

function TargetTypeLabel({ report }) {
    const isRoom = report.targetType === "room";
    return (
        <span className={styles.reportTargetType}>
            {isRoom ? <MeetingRoomOutlined fontSize="small" /> : <PersonOutlineOutlined fontSize="small" />}
            {isRoom ? "房间" : "用户"}
        </span>
    );
}

function TargetCell({ report }) {
    const target = report.target || {};
    if (report.targetType === "room") {
        const room = target.room || {};
        return (
            <div className={styles.identity}>
                <span className={styles.avatar}>
                    {room.coverUrl ? <img alt="" src={room.coverUrl} /> : <MeetingRoomOutlined fontSize="small" />}
                </span>
                <span className={styles.identityText}>
                    <span className={styles.primaryText}>{room.title || "-"}</span>
                    <span className={styles.meta}>{targetMeta(room.roomShortId, room.roomId || report.roomId)}</span>
                </span>
            </div>
        );
    }
    const user = target.user || {};
    return <AdminUserIdentity openInAppUserDetail user={{ ...user, userId: user.userId || report.userId }} />;
}

function EvidenceImages({ imageUrls = [] }) {
    const urls = Array.isArray(imageUrls) ? imageUrls.filter(Boolean) : [];
    if (!urls.length) {
        return "-";
    }
    return (
        <div className={styles.reportImages}>
            {urls.slice(0, 4).map((url) => (
                <a className={styles.reportImage} href={url} key={url} rel="noreferrer" target="_blank">
                    <img alt="" src={url} />
                </a>
            ))}
            {urls.length > 4 ? <span className={styles.reportImageCount}>+{urls.length - 4}</span> : null}
        </div>
    );
}

function targetMeta(shortId, longId) {
    return `短ID ${shortId || "-"} · 长ID ${longId || "-"}`;
}

function reportTypeLabel(value) {
    return reportTypeOptions.find((item) => item.value === value)?.label || value || "-";
}
