import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
import LinkOutlined from "@mui/icons-material/LinkOutlined";
import TextField from "@mui/material/TextField";
import { useMemo } from "react";
import { useExploreConfigPage } from "@/features/app-config/hooks/useExploreConfigPage.js";
import styles from "@/features/app-config/app-config.module.css";
import { Button } from "@/shared/ui/Button.jsx";
import {
    AdminFormDialog,
    AdminFormFieldGrid,
    AdminFormSection,
    AdminFormSwitchField,
} from "@/shared/ui/AdminFormDialog.jsx";
import {
    AdminActionIconButton,
    AdminFilterResetButton,
    AdminFilterSelect,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
    AdminSearchBox,
} from "@/shared/ui/AdminListLayout.jsx";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { formatMillis } from "@/shared/utils/time.js";

const enabledOptions = [
    ["", "全部状态"],
    ["true", "启用"],
    ["false", "关闭"],
];

export function ExploreConfigPage() {
    const page = useExploreConfigPage();
    const items = page.data.items || [];
    const columns = useMemo(() => exploreColumns(page), [page]);
    const saving = page.loadingAction === "create" || page.loadingAction === "edit";

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    page.abilities.canUpdate ? (
                        <Button startIcon={<AddOutlined fontSize="small" />} variant="primary" onClick={page.openCreate}>
                            新增 Explore tab
                        </Button>
                    ) : null
                }
                filters={
                    <>
                        <AdminSearchBox
                            placeholder="搜索 tab / H5 链接"
                            value={page.keyword}
                            onChange={page.setKeyword}
                        />
                        <AdminFilterSelect
                            label="状态"
                            options={enabledOptions}
                            value={page.enabled}
                            onChange={page.setEnabled}
                        />
                        <AdminFilterResetButton disabled={!page.keyword && !page.enabled} onClick={page.resetFilters} />
                    </>
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={items}
                        minWidth="1080px"
                        pagination={{
                            itemCount: items.length,
                            page: 1,
                            pageSize: Math.max(items.length, 1),
                            total: page.data.total ?? items.length,
                        }}
                        rowKey={(item) => item.id}
                    />
                </AdminListBody>
            </DataState>

            <AdminFormDialog
                loading={saving}
                open={Boolean(page.activeAction)}
                submitDisabled={!page.abilities.canUpdate || saving}
                title={page.editingItem ? "编辑 Explore tab" : "新增 Explore tab"}
                onClose={page.closeDialog}
                onSubmit={page.submitExploreTab}
            >
                <AdminFormSection title="tab 配置">
                    <AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
                        <TextField
                            autoFocus
                            disabled={!page.abilities.canUpdate}
                            label="tab"
                            required
                            value={page.form.tab}
                            onChange={(event) => page.setForm({ tab: event.target.value })}
                        />
                        <TextField
                            disabled={!page.abilities.canUpdate}
                            inputProps={{ step: 1 }}
                            label="排序"
                            type="number"
                            value={page.form.sortOrder}
                            onChange={(event) => page.setForm({ sortOrder: event.target.value })}
                        />
                        <TextField
                            className={styles.formWideField}
                            disabled={!page.abilities.canUpdate}
                            label="H5 链接"
                            required
                            value={page.form.h5Url}
                            onChange={(event) => page.setForm({ h5Url: event.target.value })}
                        />
                        <AdminFormSwitchField
                            checked={page.form.enabled}
                            checkedLabel="启用"
                            disabled={!page.abilities.canUpdate}
                            label="状态"
                            switchProps={{ inputProps: { "aria-label": "Explore tab 启用状态" } }}
                            uncheckedLabel="关闭"
                            onChange={(checked) => page.setForm({ enabled: checked })}
                        />
                    </AdminFormFieldGrid>
                </AdminFormSection>
            </AdminFormDialog>
        </AdminListPage>
    );
}

function exploreColumns(page) {
    const baseColumns = [
        {
            key: "tab",
            label: "tab",
            width: "minmax(180px, 0.8fr)",
        },
        {
            key: "h5Url",
            label: "H5链接",
            render: (item) => <span className={styles.linkText}>{item.h5Url || "-"}</span>,
            width: "minmax(360px, 1.6fr)",
        },
        {
            key: "enabled",
            label: "状态",
            render: (item) => <ExploreStatusSwitch item={item} page={page} />,
            width: "minmax(120px, 0.5fr)",
        },
        {
            key: "sortOrder",
            label: "排序",
            render: (item) => item.sortOrder ?? 0,
            width: "minmax(100px, 0.4fr)",
        },
        {
            key: "updatedAtMs",
            label: "更新时间",
            render: (item) => formatMillis(item.updatedAtMs),
            width: "minmax(170px, 0.7fr)",
        },
    ];

    if (!page.abilities.canUpdate) {
        return baseColumns;
    }

    return [
        ...baseColumns,
        {
            key: "actions",
            label: "操作",
            render: (item) => <ExploreRowActions item={item} page={page} />,
            width: "minmax(124px, 0.5fr)",
        },
    ];
}

function ExploreStatusSwitch({ item, page }) {
    const disabled = !page.abilities.canUpdate || page.loadingAction === `toggle:${item.id}`;
    return (
        <div className={styles.statusCell}>
            <AdminSwitch
                checked={Boolean(item.enabled)}
                checkedLabel="启用"
                disabled={disabled}
                inputProps={{ "aria-label": item.enabled ? "关闭 Explore tab" : "启用 Explore tab" }}
                uncheckedLabel="关闭"
                onChange={(event) => page.toggleExploreTab(item, event.target.checked)}
            />
        </div>
    );
}

function ExploreRowActions({ item, page }) {
    return (
        <AdminRowActions>
            <AdminActionIconButton label="编辑" onClick={() => page.openEdit(item)}>
                {item.h5Url ? <LinkOutlined fontSize="small" /> : <EditOutlined fontSize="small" />}
            </AdminActionIconButton>
            <AdminActionIconButton
                label="删除"
                disabled={page.loadingAction === `delete:${item.id}`}
                onClick={() => page.removeExploreTab(item)}
            >
                <DeleteOutlineOutlined fontSize="small" />
            </AdminActionIconButton>
        </AdminRowActions>
    );
}
