import Add from "@mui/icons-material/Add";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import PersonAddAlt1Outlined from "@mui/icons-material/PersonAddAlt1Outlined";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import TextField from "@mui/material/TextField";
import { useNavigate } from "react-router-dom";
import { formatMillis } from "@/shared/utils/time.js";
import { DataState } from "@/shared/ui/DataState.jsx";
import { agencyStatusFilters } from "@/features/host-org/constants.js";
import { HostOrgActionModal } from "@/features/host-org/components/HostOrgActionModal.jsx";
import { HostOrgEntity, HostOrgPerson, hostOrgRegionName } from "@/features/host-org/components/HostOrgIdentity.jsx";
import { HostOrgSortHeader } from "@/features/host-org/components/HostOrgSortHeader.jsx";
import { SalaryWalletAdjustButton, SalaryWalletCell } from "@/features/host-org/components/SalaryWalletControls.jsx";
import { HostOrgTable } from "@/features/host-org/components/HostOrgTable.jsx";
import { HostOrgToolbar } from "@/features/host-org/components/HostOrgToolbar.jsx";
import { useHostAgenciesPage } from "@/features/host-org/hooks/useHostAgenciesPage.js";
import { AdminActionIconButton, AdminRowActions } from "@/shared/ui/AdminListLayout.jsx";
import { createOptionsColumnFilter, createTextColumnFilter, createUserIdentityColumnFilter } from "@/shared/ui/tableFilters.js";
import styles from "@/features/host-org/host-org.module.css";

const agencyColumns = [
    {
        key: "agency",
        label: "Agency",
        render: (item) => <HostOrgEntity id={item.agencyId} name={item.name} prefix="Agency " />,
        width: "minmax(190px, 1fr)",
    },
    {
        key: "ownerUserId",
        label: "Owner",
        render: (item) => <AgencyOwner item={item} />,
        width: "minmax(220px, 1.2fr)",
    },
    {
        key: "contact",
        label: "联系方式",
        render: (item) => item.contact || "-",
        width: "minmax(150px, 0.85fr)",
    },
    {
        key: "activeHostCount",
        label: "子 Host",
        render: (item, _index, context) => <AgencyHostCount item={item} onOpen={context?.openAgencyHosts} />,
        width: "minmax(110px, 0.65fr)",
    },
    {
        key: "salaryWallet",
        label: "工资钱包",
        sortable: true,
        sortField: "salary_wallet",
        render: (item) => (
            <SalaryWalletCell
                role="agency"
                userId={item.ownerUserId}
                userLabel={agencyOwnerLabel(item)}
                wallet={item.salaryWallet}
            />
        ),
        width: "minmax(140px, 0.85fr)",
    },
    {
        key: "parentBdUserId",
        label: "上级 BD",
        render: (item) => <ParentBD item={item} />,
        width: "minmax(220px, 1.2fr)",
    },
    {
        key: "regionId",
        label: "区域",
        render: (item, _index, context) => hostOrgRegionName(item, context?.regionOptions),
        width: "minmax(130px, 0.75fr)",
    },
    {
        key: "status",
        label: "状态",
        render: (item, _index, context) => <AgencyStatusSwitch item={item} page={context?.page} />,
        width: "minmax(90px, 0.7fr)",
    },
    {
        key: "joinEnabled",
        label: "入会",
        render: (item, _index, context) => <AgencyJoinSwitch item={item} page={context?.page} />,
        width: "minmax(90px, 0.65fr)",
    },
    {
        key: "updatedAtMs",
        label: "更新时间",
        render: (item) => formatMillis(item.updatedAtMs),
        width: "minmax(170px, 1fr)",
    },
    {
        key: "actions",
        label: "操作",
        render: (item, _index, context) => <AgencyActions item={item} page={context?.page} />,
        width: "minmax(118px, 0.6fr)",
    },
];

export function HostAgenciesPage() {
    const page = useHostAgenciesPage();
    const navigate = useNavigate();
    const createDisabled = !page.abilities.canCreate;
    const agencyHostForm = page.agencyHostForm || { reason: "", targetUserId: "" };
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const openAgencyHosts = (agency) => {
        if (!agency?.agencyId) {
            return;
        }
        navigate(`/host/hosts?agency_id=${encodeURIComponent(String(agency.agencyId))}`);
    };
    const toolbarActions = [
        page.abilities.canCreate
            ? { icon: <Add fontSize="small" />, label: "创建 Agency", onClick: page.openAgencyForm, variant: "primary" }
            : null,
    ].filter(Boolean);
    const columns = agencyColumns.map((column) => {
        if (column.key === "agency") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索 Agency",
                    value: page.query,
                    onChange: page.changeQuery,
                }),
            };
        }
        if (column.key === "ownerUserId") {
            return {
                ...column,
                filter: createUserIdentityColumnFilter({
                    value: page.ownerFilter,
                    onChange: page.changeOwnerFilter,
                }),
            };
        }
        if (column.key === "parentBdUserId") {
                return {
                    ...column,
                    filter: createUserIdentityColumnFilter({
                        value: page.parentBdFilter,
                        onChange: page.changeParentBdFilter,
                    }),
                };
            }
        if (column.key === "status") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: agencyStatusFilters,
                    placeholder: "搜索状态",
                    value: page.status,
                    onChange: page.changeStatus,
                }),
            };
        }
        if (column.sortable) {
            return {
                ...column,
                header: (
                    <HostOrgSortHeader
                        field={column.sortField}
                        label={column.label}
                        sortBy={page.sortBy}
                        sortDirection={page.sortDirection}
                        onToggle={page.changeSort}
                    />
                ),
            };
        }
        return column;
    });

    return (
        <section className={styles.root}>
            <div className={styles.contentPanel}>
                <HostOrgToolbar actions={toolbarActions} />

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

            <HostOrgActionModal
                disabled={createDisabled}
                loading={page.loadingAction === "agency"}
                open={page.activeAction === "agency"}
                sectionTitle="Agency 信息"
                onClose={page.closeAction}
                onSubmit={page.submitAgency}
                title="创建 Agency"
            >
                <TextField
                    disabled={createDisabled}
                    label="Agency 名称"
                    required
                    value={page.agencyForm.name}
                    onChange={(event) => page.setAgencyForm({ ...page.agencyForm, name: event.target.value })}
                />
                <TextField
                    disabled={createDisabled}
                    label="Owner 短 ID"
                    required
                    type="number"
                    value={page.agencyForm.ownerUserId}
                    onChange={(event) => page.setAgencyForm({ ...page.agencyForm, ownerUserId: event.target.value })}
                />
                <TextField
                    disabled={createDisabled}
                    label="上级 BD 短 ID"
                    type="number"
                    value={page.agencyForm.parentBdUserId}
                    onChange={(event) => page.setAgencyForm({ ...page.agencyForm, parentBdUserId: event.target.value })}
                />
                <AdminSwitch
                    checked={page.agencyForm.joinEnabled}
                    checkedLabel="允许"
                    disabled={createDisabled}
                    label="入会状态"
                    uncheckedLabel="禁止"
                    onChange={(event) => page.setAgencyForm({ ...page.agencyForm, joinEnabled: event.target.checked })}
                />
                <TextField
                    disabled={createDisabled}
                    label="原因"
                    multiline
                    minRows={2}
                    value={page.agencyForm.reason}
                    onChange={(event) => page.setAgencyForm({ ...page.agencyForm, reason: event.target.value })}
                />
            </HostOrgActionModal>

            <HostOrgActionModal
                disabled={!page.abilities.canCreate || page.activeAgency?.status !== "active"}
                loading={page.loadingAction === `agency-host-${page.activeAgency?.agencyId}`}
                open={page.activeAction === "agency-host"}
                sectionTitle="Host 信息"
                onClose={page.closeAction}
                onSubmit={page.submitAgencyHost}
                title="增加 Host"
            >
                <TextField
                    disabled={!page.abilities.canCreate}
                    label="Host 用户短 ID"
                    required
                    type="number"
                    value={agencyHostForm.targetUserId}
                    onChange={(event) =>
                        page.setAgencyHostForm?.({ ...agencyHostForm, targetUserId: event.target.value })
                    }
                />
                <TextField
                    disabled={!page.abilities.canCreate}
                    label="原因"
                    multiline
                    minRows={2}
                    value={agencyHostForm.reason}
                    onChange={(event) => page.setAgencyHostForm?.({ ...agencyHostForm, reason: event.target.value })}
                />
            </HostOrgActionModal>
        </section>
    );
}

function AgencyOwner({ item }) {
    return (
        <HostOrgPerson
            avatar={item.ownerAvatar}
            displayUserId={item.ownerDisplayUserId}
            fallbackId={item.ownerUserId}
            username={item.ownerUsername || "Owner"}
        />
    );
}

function ParentBD({ item }) {
    return (
        <HostOrgPerson
            avatar={item.parentBdAvatar}
            displayUserId={item.parentBdDisplayUserId}
            fallbackId={item.parentBdUserId}
            username={item.parentBdUsername || "BD"}
        />
    );
}

function AgencyHostCount({ item, onOpen }) {
    const count = Number(item.activeHostCount ?? item.hostCount ?? 0);
    return (
        <button
            aria-label={`查看 Agency ${item.agencyId} 的 Host 列表`}
            className={styles.hostCountButton}
            type="button"
            onClick={() => onOpen?.(item)}
        >
            {count.toLocaleString("zh-CN")}
        </button>
    );
}

function AgencyStatusSwitch({ item, page }) {
    const active = item.status === "active";
    return (
        <AdminSwitch
            checked={active}
            disabled={!page?.abilities.canStatus || page.loadingAction === `agency-status-${item.agencyId}`}
            inputProps={{ "aria-label": active ? "关闭 Agency" : "启用 Agency" }}
            onChange={(event) => page.toggleAgencyStatusFromList(item, event.target.checked)}
        />
    );
}

function AgencyJoinSwitch({ item, page }) {
    const active = item.status === "active";
    return (
        <AdminSwitch
            checked={Boolean(item.joinEnabled)}
            disabled={!active || !page?.abilities.canStatus || page.loadingAction === `agency-join-${item.agencyId}`}
            inputProps={{ "aria-label": item.joinEnabled ? "禁止入会" : "允许入会" }}
            onChange={(event) => page.toggleAgencyJoinEnabledFromList(item, event.target.checked)}
        />
    );
}

function AgencyActions({ item, page }) {
    return (
        <AdminRowActions>
            {page?.abilities.canCreate ? (
                <AdminActionIconButton
                    disabled={item.status !== "active" || page.loadingAction === `agency-host-${item.agencyId}`}
                    label="增加 Host"
                    primary
                    onClick={() => page.openAgencyHostForm(item)}
                >
                    <PersonAddAlt1Outlined fontSize="small" />
                </AdminActionIconButton>
            ) : null}
            {page?.abilities.canSalaryAdjust ? (
                <SalaryWalletAdjustButton
                    role="agency"
                    userId={item.ownerUserId}
                    userLabel={agencyOwnerLabel(item)}
                    onAdjusted={page.reload}
                />
            ) : null}
            {page?.abilities.canDelete ? (
                <AdminActionIconButton
                    disabled={page.loadingAction === `agency-delete-${item.agencyId}`}
                    label="删除 Agency"
                    sx={dangerActionSx}
                    onClick={() => page.removeAgencyFromList(item)}
                >
                    <DeleteOutlineOutlined fontSize="small" />
                </AdminActionIconButton>
            ) : null}
        </AdminRowActions>
    );
}

const dangerActionSx = {
    borderColor: "var(--danger-border)",
    color: "var(--danger)",
    "&:hover": {
        borderColor: "var(--danger-border-strong)",
        backgroundColor: "var(--danger-surface)",
    },
};

function agencyOwnerLabel(item) {
    return item.ownerDisplayUserId || item.ownerUsername || item.ownerUserId;
}
