import EditOutlined from "@mui/icons-material/EditOutlined";
import LinkOutlined from "@mui/icons-material/LinkOutlined";
import TextField from "@mui/material/TextField";
import { formatMillis } from "@/shared/utils/time.js";
import { AdminFormDialog } from "@/shared/ui/AdminFormDialog.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import {
  AdminActionIconButton,
  AdminListBody,
  AdminListPage,
  AdminRowActions
} from "@/shared/ui/AdminListLayout.jsx";
import { useH5ConfigPage } from "@/features/app-config/hooks/useH5ConfigPage.js";
import styles from "@/features/app-config/app-config.module.css";

const baseColumns = [
  {
    key: "label",
    label: "配置项",
    width: "minmax(180px, 0.8fr)"
  },
  {
    key: "key",
    label: "Key",
    width: "minmax(200px, 0.9fr)"
  },
  {
    key: "url",
    label: "H5链接",
    render: (item) => <span className={styles.linkText}>{item.url || "-"}</span>,
    width: "minmax(360px, 1.8fr)"
  },
  {
    key: "updatedAtMs",
    label: "更新时间",
    render: (item) => formatMillis(item.updatedAtMs),
    width: "minmax(170px, 0.8fr)"
  }
];

export function H5ConfigPage() {
  const page = useH5ConfigPage();
  const items = page.data.items || [];
  const columns = page.abilities.canUpdate
    ? [
        ...baseColumns,
        {
          key: "actions",
          label: "操作",
          render: (item) => <H5LinkActions item={item} page={page} />,
          width: "minmax(88px, 0.4fr)"
        }
      ]
    : baseColumns;

  return (
    <AdminListPage>
      <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
        <AdminListBody>
          <DataTable columns={columns} items={items} minWidth="980px" rowKey={(item) => item.key} />
          <div className="pagination-bar">
            <span>{items.length} 条</span>
          </div>
        </AdminListBody>
      </DataState>

      <AdminFormDialog
        loading={page.loadingAction === "edit"}
        open={Boolean(page.editingItem)}
        size="compact"
        submitDisabled={!page.abilities.canUpdate || page.loadingAction === "edit"}
        title="编辑H5链接"
        onClose={page.closeEdit}
        onSubmit={page.submitEdit}
      >
        <TextField
          autoFocus
          disabled={!page.abilities.canUpdate}
          label={page.editingItem?.label || "H5链接"}
          value={page.form.url}
          onChange={(event) => page.setForm({ url: event.target.value })}
        />
      </AdminFormDialog>
    </AdminListPage>
  );
}

function H5LinkActions({ item, page }) {
  return (
    <AdminRowActions>
      <AdminActionIconButton label="编辑" onClick={() => page.openEdit(item)}>
        {item.url ? <LinkOutlined fontSize="small" /> : <EditOutlined fontSize="small" />}
      </AdminActionIconButton>
    </AdminRowActions>
  );
}
