import { Table, Group, ActionIcon, Button, Code } from "@mantine/core";
import { IconChevronUp, IconChevronDown, IconInfoCircle } from "@tabler/icons-react";
import { useState } from "react";

export function AlertTable({
  alerts,
  paginatedAlerts,
  page,
  setPage,
  pageSize,
  sortedAlerts,
  sortConfig,
  handleSort,
  getRowColor,
  getSeverityColor,
  getStateBadge,
  formatRelativeTime,
}) {
  const totalPages = Math.ceil(sortedAlerts.length / pageSize);
  const [expandedRow, setExpandedRow] = useState(null);

  const toggleExpand = (index) => {
    setExpandedRow(expandedRow === index ? null : index);
  };

  return (
    <>
      <Table striped highlightOnHover>
        <Table.Thead>
          <Table.Tr>
            {[
              { key: "alertname", label: "名称" },
              { key: "instance", label: "节点" },
              { key: "severity", label: "严重性" },
              { key: "state", label: "状态" },
              { key: "startsAt", label: "开始时间" },
              { key: "endsAt", label: "结束时间" },
              { key: "updatedAt", label: "更新时间" },
              { key: "summary", label: "描述" },
            ].map((col) => (
              <Table.Th key={col.key}>
                <Group spacing={4}>
                  {col.label}
                  {["severity", "startsAt", "instance"].includes(col.key) && (
                    <ActionIcon size="xs" onClick={() => handleSort(col.key)}>
                      {sortConfig.key === col.key && sortConfig.direction === "asc" ? (
                        <IconChevronUp size={14} />
                      ) : (
                        <IconChevronDown size={14} />
                      )}
                    </ActionIcon>
                  )}
                </Group>
              </Table.Th>
            ))}
            <Table.Th>更多信息</Table.Th>
          </Table.Tr>
        </Table.Thead>

        <Table.Tbody>
          {paginatedAlerts.map((alert, i) => (
            <>
              <Table.Tr key={i} style={{ backgroundColor: getRowColor(alert) }}>
                <Table.Td>{alert.labels?.alertname || "-"}</Table.Td>
                <Table.Td>{alert.labels?.instance || "-"}</Table.Td>
                <Table.Td style={{ color: getSeverityColor(alert.labels?.severity) }}>
                  {alert.labels?.severity || "info"}
                </Table.Td>
                <Table.Td>{getStateBadge(alert.status?.state)}</Table.Td>
                <Table.Td title={alert.startsAt || "-"}>{formatRelativeTime(alert.startsAt)}</Table.Td>
                <Table.Td title={alert.endsAt || "-"}>
                  {alert.endsAt ? new Date(alert.endsAt).toLocaleString() : "-"}
                </Table.Td>
                <Table.Td title={alert.updatedAt || "-"}>{formatRelativeTime(alert.updatedAt)}</Table.Td>
                <Table.Td>{alert.annotations?.summary || "-"}</Table.Td>
                <Table.Td>
                  <ActionIcon
                    onClick={() => toggleExpand(i)}
                    variant="subtle"
                    color="blue"
                    title="显示/隐藏更多信息"
                  >
                    <IconInfoCircle size={18} />
                  </ActionIcon>
                </Table.Td>
              </Table.Tr>

              {expandedRow === i && (
                <Table.Tr key={`details-${i}`} style={{ backgroundColor: "#f9fafb" }}>
                  <Table.Td colSpan={9}>
                    <div style={{ fontSize: "0.85rem", lineHeight: 1.5 }}>
                      {Object.entries(alert.labels || {}).map(([k, v]) => (
                        <div key={k}>
                          <Code color="blue">{k}</Code> ：{v}
                        </div>
                      ))}
                    </div>
                  </Table.Td>
                </Table.Tr>
              )}
            </>
          ))}
        </Table.Tbody>
      </Table>

      {/* 分页控件 */}
      <Group position="apart" mt="sm">
        <Button
          disabled={page === 1}
          onClick={() => setPage((p) => Math.max(1, p - 1))}
          variant="outline"
          size="xs"
        >
          上一页
        </Button>
        <span>
          {page} / {totalPages}
        </span>
        <Button
          disabled={page >= totalPages}
          onClick={() => setPage((p) => p + 1)}
          variant="outline"
          size="xs"
        >
          下一页
        </Button>
      </Group>
    </>
  );
}
