import Add from "@mui/icons-material/Add";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import TextField from "@mui/material/TextField";
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 } 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: "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 createDisabled = !page.abilities.canCreate;
    const items = page.data.items || [];
    const total = page.data.total || 0;
    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、Owner、用户",
                    value: page.query,
                    onChange: page.changeQuery,
                }),
            };
        }
        if (column.key === "parentBdUserId") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索上级 BD 用户 ID",
                    value: page.parentBdUserId,
                    onChange: page.changeParentBdUserId,
                }),
            };
        }
        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={{ page, regionOptions: page.regionOptions }}
                            items={items}
                            minWidth="1340px"
                            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>
        </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 AgencyStatusSwitch({ item, page }) {
    const active = item.status === "active";
    return (
        <AdminSwitch
            checked={active}
            disabled={!active || !page?.abilities.canStatus || page.loadingAction === `agency-status-${item.agencyId}`}
            inputProps={{ "aria-label": active ? "关闭 Agency" : "Agency 已关闭" }}
            onChange={(event) => {
                if (!event.target.checked) {
                    page.closeAgencyFromList(item);
                }
            }}
        />
    );
}

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.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;
}
