"use client";

import { Anchor, Badge, Code, Group, Image, List, Stack, Text, ThemeIcon } from "@mantine/core";
import {
  IconAlertTriangle,
  IconCircleCheck,
  IconCircleX,
  IconClock,
  IconExternalLink,
  IconLoader,
} from "@tabler/icons-react";
import { fileNameOf } from "./htmlUtils";
import type { CheckResult, CheckStatus } from "./types";

// Pipeline stage states extend the result statuses with run-lifecycle states.
export type StageStatus = CheckStatus | "pending" | "running";

export const STATUS_META: Record<
  StageStatus,
  { color: string; label: string; icon: typeof IconCircleCheck }
> = {
  pending: { color: "gray", label: "Pending", icon: IconClock },
  running: { color: "blue", label: "Running", icon: IconLoader },
  pass: { color: "green", label: "Pass", icon: IconCircleCheck },
  warning: { color: "yellow", label: "Warning", icon: IconAlertTriangle },
  fail: { color: "red", label: "Fail", icon: IconCircleX },
};

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <Stack gap={4} mt="xs">
      <Text size="xs" fw={600} c="dimmed" tt="uppercase">
        {title}
      </Text>
      {children}
    </Stack>
  );
}

// The detail body of a check result (messages + variables + links + images),
// rendered inside a pipeline stage. No outer card / header — the stage owns those.
export function ResultDetail({ result }: { result: CheckResult }) {
  return (
    <Stack gap={4}>
      {result.messages.length > 0 && (
        <List size="sm" spacing={2}>
          {result.messages.map((m, i) => (
            <List.Item key={i}>
              <Text size="sm" c="dimmed">
                {m}
              </Text>
            </List.Item>
          ))}
        </List>
      )}

      {result.variables && result.variables.length > 0 && (
        <Section title="Variables">
          <Group gap={6}>
            {result.variables.map((v) => (
              <Badge
                key={v.token}
                variant="light"
                color={v.kind === "conditional" ? "grape" : "blue"}
                styles={{ root: { textTransform: "none", fontFamily: "monospace" } }}
              >
                {v.token}
                {v.count > 1 ? ` ×${v.count}` : ""}
              </Badge>
            ))}
          </Group>
        </Section>
      )}

      {result.links && result.links.length > 0 && (
        <Section title="Links">
          <Stack gap={4}>
            {result.links.map((l, i) => {
              const openable = l.present && !l.isMergeTag && /^https?:\/\//i.test(l.href);
              return (
                <Group key={`${l.href}-${i}`} gap="xs" wrap="nowrap" align="center">
                  <ThemeIcon
                    size="xs"
                    radius="xl"
                    variant="light"
                    color={l.present ? "green" : "red"}
                  >
                    {l.present ? <IconCircleCheck size={12} /> : <IconCircleX size={12} />}
                  </ThemeIcon>
                  <Text size="xs" fw={500} style={{ whiteSpace: "nowrap" }}>
                    {l.label}
                  </Text>
                  {l.href ? (
                    <Code style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1, minWidth: 0 }}>
                      {l.href}
                    </Code>
                  ) : (
                    <Text size="xs" c="dimmed" style={{ flex: 1 }}>
                      (missing)
                    </Text>
                  )}
                  {l.isMergeTag && (
                    <Badge size="xs" variant="light" color="grape" styles={{ root: { textTransform: "none" } }}>
                      merge tag
                    </Badge>
                  )}
                  {openable && (
                    <Anchor href={l.href} target="_blank" rel="noopener noreferrer">
                      <Group gap={2} wrap="nowrap">
                        <IconExternalLink size={14} />
                        <Text size="xs">Open</Text>
                      </Group>
                    </Anchor>
                  )}
                </Group>
              );
            })}
          </Stack>
        </Section>
      )}

      {result.images && result.images.length > 0 && (
        <Section title={`Images (${result.images.length})`}>
          <Stack gap={6}>
            {result.images.map((img, i) => (
              <Group key={`${img.src}-${i}`} gap="xs" wrap="nowrap" align="center">
                <Image
                  src={img.src}
                  h={36}
                  w={36}
                  fit="contain"
                  radius="sm"
                  alt={img.alt}
                  style={{ border: img.broken ? "1px solid var(--mantine-color-red-4)" : undefined, flexShrink: 0 }}
                />
                <Text
                  size="xs"
                  style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1, minWidth: 0 }}
                >
                  {fileNameOf(img.src)}
                </Text>
                <Group gap={4} wrap="nowrap">
                  {img.broken && (
                    <Badge size="xs" variant="light" color="red">broken</Badge>
                  )}
                  {img.hasSpaces && (
                    <Badge size="xs" variant="light" color="orange">spaces</Badge>
                  )}
                  <Badge size="xs" variant="light" color={img.ok ? "green" : "yellow"}>
                    {img.ext || "no ext"}
                  </Badge>
                  {/^https?:\/\//i.test(img.src) && (
                    <Anchor href={img.src} target="_blank" rel="noopener noreferrer" style={{ lineHeight: 1 }}>
                      <Group gap={2} wrap="nowrap">
                        <IconExternalLink size={13} />
                        <Text size="xs">Open</Text>
                      </Group>
                    </Anchor>
                  )}
                </Group>
              </Group>
            ))}
          </Stack>
        </Section>
      )}
    </Stack>
  );
}
