import CheckCircleOutlineOutlined from "@mui/icons-material/CheckCircleOutlineOutlined";
import HighlightOffOutlined from "@mui/icons-material/HighlightOffOutlined";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { AdminActionIconButton, AdminRowActions } from "@/shared/ui/AdminListLayout.jsx";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { formatMillis } from "@/shared/utils/time.js";
import {
    coinSellerSubApplicationStatusFilters,
    coinSellerSubApplicationStatusLabels,
} from "@/features/host-org/constants.js";
import { HostOrgActionModal } from "@/features/host-org/components/HostOrgActionModal.jsx";
import { HostOrgStatus } from "@/features/host-org/components/HostOrgStatus.jsx";
import { HostOrgTable } from "@/features/host-org/components/HostOrgTable.jsx";
import { useHostSubCoinSellerApplicationsPage } from "@/features/host-org/hooks/useHostSubCoinSellerApplicationsPage.js";
import styles from "@/features/host-org/host-org.module.css";

const columns = [
    {
        key: "parent",
        label: "父币商",
        render: (item) => <ApplicationUserIdentity user={item.parent} />,
        width: "minmax(220px, 1.2fr)",
    },
    {
        key: "target",
        label: "申请子币商",
        render: (item) => <ApplicationUserIdentity user={item.target} />,
        width: "minmax(220px, 1.2fr)",
    },
    {
        key: "status",
        label: "状态",
        render: (item) => <HostOrgStatus value={item.status} />,
        width: "minmax(120px, 0.6fr)",
    },
    {
        key: "createdAtMs",
        label: "申请时间",
        render: (item) => formatMillis(item.createdAtMs),
        width: "minmax(170px, 0.9fr)",
    },
    {
        key: "reviewedAtMs",
        label: "审核时间",
        render: (item) => (Number(item.reviewedAtMs || 0) > 0 ? formatMillis(item.reviewedAtMs) : "-"),
        width: "minmax(170px, 0.9fr)",
    },
    {
        key: "reviewedByAdminId",
        label: "审核人",
        render: (item) => item.reviewedByAdminId || "-",
        width: "minmax(120px, 0.6fr)",
    },
    {
        key: "reviewReason",
        label: "审核备注",
        render: (item) => item.reviewReason || "-",
        width: "minmax(180px, 1fr)",
    },
    {
        key: "actions",
        label: "操作",
        render: (item, _index, context) => <ApplicationActions item={item} page={context?.page} />,
        width: "minmax(120px, 0.7fr)",
    },
];

export function HostSubCoinSellerApplicationsPage() {
    const page = useHostSubCoinSellerApplicationsPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const reviewTitle = page.reviewDecision === "approved" ? "通过子币商申请" : "拒绝子币商申请";

    return (
        <section className={styles.root}>
            <div className={styles.contentPanel}>
                <div className={styles.toolbar}>
                    <section className={styles.filters}>
                        <TextField
                            label="搜索"
                            size="small"
                            value={page.keyword}
                            onChange={(event) => page.changeKeyword(event.target.value)}
                        />
                        <TextField
                            label="状态"
                            select
                            size="small"
                            value={page.status}
                            onChange={(event) => page.changeStatus(event.target.value)}
                        >
                            {coinSellerSubApplicationStatusFilters.map(([value, label]) => (
                                <MenuItem key={value || "all"} value={value}>
                                    {label}
                                </MenuItem>
                            ))}
                        </TextField>
                        <TextField
                            label="父币商ID"
                            size="small"
                            type="number"
                            value={page.parentUserId}
                            onChange={(event) => page.changeParentUserId(event.target.value)}
                        />
                        <TextField
                            label="目标用户ID"
                            size="small"
                            type="number"
                            value={page.targetUserId}
                            onChange={(event) => page.changeTargetUserId(event.target.value)}
                        />
                        <Button variant="text" onClick={page.resetFilters}>
                            重置
                        </Button>
                    </section>
                </div>

                <DataState error={page.error} loading={page.loading}>
                    <div className={styles.listBlock}>
                        <HostOrgTable
                            columns={columns}
                            context={{ page }}
                            items={items}
                            minWidth="1280px"
                            pagination={
                                total > 0
                                    ? {
                                          page: page.page,
                                          pageSize: page.data.pageSize || 50,
                                          total,
                                          onPageChange: page.setPage,
                                      }
                                    : undefined
                            }
                            rowKey={(item) => item.applicationId}
                        />
                    </div>
                </DataState>
            </div>

            <HostOrgActionModal
                disabled={!page.abilities.canAudit}
                loading={String(page.loadingAction).startsWith("review-")}
                open={page.activeAction === "review"}
                sectionTitle="审核信息"
                submitLabel={page.reviewDecision === "approved" ? "确认通过" : "确认拒绝"}
                onClose={page.closeAction}
                onSubmit={page.submitReview}
                title={reviewTitle}
            >
                <TextField disabled label="申请状态" value={statusText(page.selectedApplication?.status)} />
                <TextField disabled label="Command ID" value={page.reviewForm.commandId} />
                <TextField
                    disabled={!page.abilities.canAudit}
                    label="审核备注"
                    multiline
                    minRows={3}
                    value={page.reviewForm.reason}
                    onChange={(event) => page.setReviewForm({ ...page.reviewForm, reason: event.target.value })}
                />
            </HostOrgActionModal>
        </section>
    );
}

function ApplicationUserIdentity({ user }) {
    return (
        <AdminUserIdentity
            avatar={user?.avatar}
            displayUserId={user?.displayUserId}
            name={user?.username}
            rows={[user?.userId, user?.regionName].filter(Boolean)}
            userId={user?.userId}
        />
    );
}

function ApplicationActions({ item, page }) {
    if (!page?.abilities.canAudit || item.status !== "pending") {
        return <span>-</span>;
    }
    const loading = page.loadingAction === `review-${item.applicationId}`;
    return (
        <AdminRowActions>
            <AdminActionIconButton
                disabled={loading}
                label="通过"
                primary
                onClick={() => page.openReview(item, "approved")}
            >
                <CheckCircleOutlineOutlined fontSize="small" />
            </AdminActionIconButton>
            <AdminActionIconButton disabled={loading} label="拒绝" onClick={() => page.openReview(item, "rejected")}>
                <HighlightOffOutlined fontSize="small" />
            </AdminActionIconButton>
        </AdminRowActions>
    );
}

function statusText(status) {
    return coinSellerSubApplicationStatusLabels[status] || status || "-";
}
