import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useMemo } from "react";
import { useAppVersionsPage } from "@/features/app-config/hooks/useAppVersionsPage.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,
  AdminListBody,
  AdminListPage,
  AdminListToolbar,
  AdminRowActions
} from "@/shared/ui/AdminListLayout.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";

const platformOptions = [
  ["", "全部平台"],
  ["android", "Android"],
  ["ios", "iOS"]
];

export function AppVersionManagementPage() {
  const page = useAppVersionsPage();
  const items = page.data.items || [];
  const columns = useMemo(() => versionColumns(page), [page]);
  const saving = page.loadingAction === "create" || page.loadingAction === "edit";
  const canSubmit = page.editingItem ? page.abilities.canUpdateVersion : page.abilities.canCreateVersion;

  return (
    <AdminListPage>
      <AdminListToolbar
        actions={
          page.abilities.canCreateVersion ? (
            <Button startIcon={<AddOutlined fontSize="small" />} variant="primary" onClick={page.openCreate}>
              新增版本
            </Button>
          ) : null
        }
      />
      <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
        <AdminListBody>
          <DataTable
            columns={columns}
            items={items}
            minWidth="1080px"
            pagination={{
              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)}
        size="narrow"
        submitDisabled={!canSubmit || saving}
        title={page.editingItem ? "编辑版本" : "新增版本"}
        onClose={page.closeDialog}
        onSubmit={page.submitVersion}
      >
        <AdminFormSection title="版本信息">
          <AdminFormFieldGrid>
            <TextField
              disabled={!canSubmit}
              label="平台"
              required
              select
              value={page.form.platform}
              onChange={(event) => page.setForm({ platform: event.target.value })}
            >
              <MenuItem value="android">Android</MenuItem>
              <MenuItem value="ios">iOS</MenuItem>
            </TextField>
            <TextField
              disabled={!canSubmit}
              label="版本号"
              required
              value={page.form.version}
              onChange={(event) => page.setForm({ version: event.target.value })}
            />
            <TextField
              disabled={!canSubmit}
              inputProps={{ min: 1, step: 1 }}
              label="编译版本号"
              required
              type="number"
              value={page.form.buildNumber}
              onChange={(event) => page.setForm({ buildNumber: event.target.value })}
            />
            <AdminFormSwitchField
              checked={Boolean(page.form.forceUpdate)}
              checkedLabel="强更"
              disabled={!canSubmit}
              label="强更"
              uncheckedLabel="普通"
              onChange={(checked) => page.setForm({ forceUpdate: checked })}
            />
          </AdminFormFieldGrid>
        </AdminFormSection>
        <AdminFormSection title="下载信息">
          <TextField
            disabled={!canSubmit}
            label="下载链接"
            required
            value={page.form.downloadUrl}
            onChange={(event) => page.setForm({ downloadUrl: event.target.value })}
          />
          <TextField
            disabled={!canSubmit}
            label="更新描述"
            multiline
            minRows={3}
            value={page.form.description}
            onChange={(event) => page.setForm({ description: event.target.value })}
          />
        </AdminFormSection>
      </AdminFormDialog>
    </AdminListPage>
  );
}

function versionColumns(page) {
  const columns = [
    {
      key: "version",
      label: "版本",
      render: (item) => <Stack primary={item.version} secondary={`Build ${item.buildNumber}`} />,
      filter: createTextColumnFilter({
        placeholder: "搜索版本、链接、描述",
        value: page.keyword,
        onChange: page.setKeyword
      }),
      width: "minmax(190px, 0.9fr)"
    },
    {
      key: "platform",
      label: "平台",
      render: (item) => platformLabel(item.platform),
      filter: createOptionsColumnFilter({
        options: platformOptions,
        placeholder: "搜索平台",
        value: page.platform,
        onChange: page.setPlatform
      }),
      width: "minmax(120px, 0.5fr)"
    },
    {
      key: "forceUpdate",
      label: "强更",
      render: (item) => <ForceBadge enabled={item.forceUpdate} />,
      width: "minmax(110px, 0.45fr)"
    },
    {
      key: "downloadUrl",
      label: "下载链接",
      render: (item) => <span className={styles.linkText}>{item.downloadUrl}</span>,
      width: "minmax(280px, 1.25fr)"
    },
    {
      key: "description",
      label: "更新描述",
      render: (item) => item.description || "-",
      width: "minmax(220px, 1fr)"
    },
    {
      key: "updatedAtMs",
      label: "更新时间",
      render: (item) => formatMillis(item.updatedAtMs),
      width: "minmax(160px, 0.7fr)"
    }
  ];

  if (!page.abilities.canUpdateVersion && !page.abilities.canDeleteVersion) {
    return columns;
  }

  return [
    ...columns,
    {
      key: "actions",
      label: "操作",
      render: (item) => <VersionActions item={item} page={page} />,
      width: "minmax(96px, 0.42fr)"
    }
  ];
}

function VersionActions({ item, page }) {
  const deleting = page.loadingAction === `delete:${item.id}`;
  return (
    <AdminRowActions>
      {page.abilities.canUpdateVersion ? (
        <AdminActionIconButton disabled={Boolean(page.loadingAction)} label="编辑" onClick={() => page.openEdit(item)}>
          <EditOutlined fontSize="small" />
        </AdminActionIconButton>
      ) : null}
      {page.abilities.canDeleteVersion ? (
        <AdminActionIconButton disabled={deleting || Boolean(page.loadingAction)} label="删除" onClick={() => page.removeVersion(item)}>
          <DeleteOutlineOutlined fontSize="small" />
        </AdminActionIconButton>
      ) : null}
    </AdminRowActions>
  );
}

function Stack({ primary, secondary }) {
  return (
    <div className="cell-stack">
      <span>{primary || "-"}</span>
      <span className="muted">{secondary || "-"}</span>
    </div>
  );
}

function ForceBadge({ enabled }) {
  const tone = enabled ? "warning" : "stopped";
  return (
    <span className={`status-badge status-badge--${tone}`}>
      <span className="status-point" />
      {enabled ? "强更" : "普通"}
    </span>
  );
}

function platformLabel(value) {
  if (value === "android") {
    return "Android";
  }
  if (value === "ios") {
    return "iOS";
  }
  return value || "-";
}
