/**
 * 通用 UI 组件（纸面风格）
 *
 * 复用 @edu/ui-components 中的基础组件，扩展 admin 专用组件
 */
import { type ReactNode, type ButtonHTMLAttributes } from "react";

/** 纸面卡片 */
export function PaperCard({
  children,
  className = "",
  style,
}: {
  children: ReactNode;
  className?: string;
  style?: React.CSSProperties;
}): ReactNode {
  return (
    <div
      className={`bg-white border rounded-lg ${className}`}
      style={{
        borderColor: "var(--color-rule)",
        background: "var(--bg-paper)",
        ...style,
      }}
    >
      {children}
    </div>
  );
}

/** 页面标题 */
export function PageHeader({
  title,
  description,
  actions,
}: {
  title: string;
  description?: string;
  actions?: ReactNode;
}): ReactNode {
  return (
    <div
      className="flex items-start justify-between mb-6 pb-4"
      style={{ borderBottom: "1px solid var(--color-rule)" }}
    >
      <div>
        <h1
          style={{
            fontFamily: "var(--font-serif)",
            fontSize: 24,
            color: "var(--color-ink)",
            margin: 0,
          }}
        >
          {title}
        </h1>
        {description && (
          <p
            style={{
              color: "var(--color-ink-muted)",
              fontSize: 13,
              marginTop: 4,
            }}
          >
            {description}
          </p>
        )}
      </div>
      {actions && <div className="flex gap-2">{actions}</div>}
    </div>
  );
}

/** 按钮 */
type ButtonVariant = "primary" | "secondary" | "ghost" | "danger";

interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: ButtonVariant;
}

const buttonStyles: Record<ButtonVariant, Record<string, string>> = {
  primary: {
    background: "var(--color-accent)",
    color: "var(--bg-paper)",
    border: "1px solid var(--color-accent)",
  },
  secondary: {
    background: "var(--bg-paper)",
    color: "var(--color-ink)",
    border: "1px solid var(--color-rule)",
  },
  ghost: {
    background: "transparent",
    color: "var(--color-ink-muted)",
    border: "1px solid transparent",
  },
  danger: {
    background: "var(--color-danger)",
    color: "var(--bg-paper)",
    border: "1px solid var(--color-danger)",
  },
};

export function Button({
  variant = "secondary",
  children,
  style,
  ...props
}: ButtonProps): ReactNode {
  return (
    <button
      {...props}
      style={{
        ...buttonStyles[variant],
        padding: "6px 14px",
        fontSize: 13,
        borderRadius: 4,
        cursor: props.disabled ? "not-allowed" : "pointer",
        opacity: props.disabled ? 0.5 : 1,
        ...style,
      }}
    >
      {children}
    </button>
  );
}

/** 输入框 */
export function Input({
  style,
  ...props
}: React.InputHTMLAttributes<HTMLInputElement>): ReactNode {
  return (
    <input
      {...props}
      style={{
        padding: "6px 10px",
        border: "1px solid var(--color-rule)",
        borderRadius: 4,
        background: "var(--bg-paper)",
        color: "var(--color-ink)",
        fontSize: 13,
        ...style,
      }}
    />
  );
}

/** 选择框 */
export function Select({
  style,
  children,
  ...props
}: React.SelectHTMLAttributes<HTMLSelectElement>): ReactNode {
  return (
    <select
      {...props}
      style={{
        padding: "6px 10px",
        border: "1px solid var(--color-rule)",
        borderRadius: 4,
        background: "var(--bg-paper)",
        color: "var(--color-ink)",
        fontSize: 13,
        ...style,
      }}
    >
      {children}
    </select>
  );
}

/** 标签（状态徽章） */
export function Badge({ status }: { status: string }): ReactNode {
  const colorMap: Record<string, string> = {
    active: "var(--color-success)",
    disabled: "var(--color-ink-muted)",
    locked: "var(--color-danger)",
    healthy: "var(--color-success)",
    degraded: "var(--color-warning)",
    down: "var(--color-danger)",
    draft: "var(--color-warning)",
    published: "var(--color-success)",
    archived: "var(--color-ink-muted)",
    unused: "var(--color-accent)",
    used: "var(--color-success)",
    expired: "var(--color-danger)",
    pinned: "var(--color-accent)",
  };
  const labelMap: Record<string, string> = {
    active: "启用",
    disabled: "禁用",
    locked: "锁定",
    healthy: "健康",
    degraded: "降级",
    down: "异常",
    draft: "草稿",
    published: "已发布",
    archived: "已归档",
    unused: "未使用",
    used: "已使用",
    expired: "已过期",
    pinned: "置顶",
  };
  const color = colorMap[status] ?? "var(--color-ink-muted)";
  return (
    <span
      style={{
        display: "inline-block",
        padding: "2px 8px",
        fontSize: 11,
        borderRadius: 10,
        background: `${color}20`,
        color,
        border: `1px solid ${color}40`,
      }}
    >
      {labelMap[status] ?? status}
    </span>
  );
}

/** 表格 */
export function Table({
  headers,
  children,
}: {
  headers: string[];
  children: ReactNode;
}): ReactNode {
  return (
    <div className="overflow-x-auto">
      <table
        className="w-full"
        style={{ borderCollapse: "collapse", fontSize: 13 }}
      >
        <thead>
          <tr style={{ borderBottom: "2px solid var(--color-rule)" }}>
            {headers.map((h, i) => (
              <th
                key={h}
                style={{
                  textAlign: "left",
                  padding: "10px 12px",
                  color: "var(--color-ink-muted)",
                  fontWeight: 500,
                  fontSize: 12,
                  textTransform: "uppercase",
                  letterSpacing: "0.05em",
                  whiteSpace: i === 0 ? "nowrap" : "normal",
                }}
              >
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>{children}</tbody>
      </table>
    </div>
  );
}

/** 表格行 */
export function TableRow({ children }: { children: ReactNode }): ReactNode {
  return (
    <tr style={{ borderBottom: "1px solid var(--color-rule)" }}>{children}</tr>
  );
}

/** 表格单元格 */
export function TableCell({
  children,
  style,
  rowSpan,
}: {
  children: ReactNode;
  style?: React.CSSProperties;
  rowSpan?: number;
}): ReactNode {
  return (
    <td
      style={{ padding: "10px 12px", color: "var(--color-ink)", ...style }}
      rowSpan={rowSpan}
    >
      {children}
    </td>
  );
}

/** 空状态 */
export function EmptyState({ message }: { message: string }): ReactNode {
  return (
    <div
      style={{
        textAlign: "center",
        padding: "48px 16px",
        color: "var(--color-ink-muted)",
      }}
    >
      <p style={{ fontSize: 14 }}>{message}</p>
    </div>
  );
}

/** 加载状态 */
export function LoadingState(): ReactNode {
  return (
    <div
      style={{
        textAlign: "center",
        padding: "48px 16px",
        color: "var(--color-ink-muted)",
      }}
    >
      <p style={{ fontSize: 14 }}>加载中...</p>
    </div>
  );
}

/** 错误状态 */
export function ErrorState({
  message,
  onRetry,
}: {
  message: string;
  onRetry?: () => void;
}): ReactNode {
  return (
    <div
      style={{
        textAlign: "center",
        padding: "48px 16px",
        color: "var(--color-danger)",
      }}
    >
      <p style={{ fontSize: 14, marginBottom: 8 }}>{message}</p>
      {onRetry && (
        <Button variant="secondary" onClick={onRetry}>
          重试
        </Button>
      )}
    </div>
  );
}

/** 分页 */
export function Pagination({
  page,
  pageSize,
  total,
  hasNext,
  onPageChange,
}: {
  page: number;
  pageSize: number;
  total: number;
  hasNext: boolean;
  onPageChange: (page: number) => void;
}): ReactNode {
  const totalPages = Math.ceil(total / pageSize);
  return (
    <div
      className="flex items-center justify-between mt-4"
      style={{ fontSize: 12, color: "var(--color-ink-muted)" }}
    >
      <span>
        共 {total} 条，第 {page}/{totalPages || 1} 页
      </span>
      <div className="flex gap-2">
        <Button
          variant="secondary"
          disabled={page <= 1}
          onClick={() => onPageChange(page - 1)}
        >
          上一页
        </Button>
        <Button
          variant="secondary"
          disabled={!hasNext}
          onClick={() => onPageChange(page + 1)}
        >
          下一页
        </Button>
      </div>
    </div>
  );
}
