import { Anchor, Badge, Box, Group, Paper, Stack, Text } from "@mantine/core";
import { IconExternalLink } from "@tabler/icons-react";
import { useMemo } from "react";
import type { Card, CardMessage } from "../types";

interface ExtractedLink {
  url: string;
  source: "title" | "description" | "chat";
  context: string;
}

const URL_RE = /(https?:\/\/[^\s<>()"']+)/gi;

function extract(source: ExtractedLink["source"], text: string): ExtractedLink[] {
  if (!text) return [];
  const out: ExtractedLink[] = [];
  const seen = new Set<string>();
  let m: RegExpExecArray | null;
  URL_RE.lastIndex = 0;
  while ((m = URL_RE.exec(text)) !== null) {
    let url = m[1];
    // Strip common trailing punctuation that isn't part of a URL.
    url = url.replace(/[.,;:!?)\]}>]+$/, "");
    if (seen.has(url)) continue;
    seen.add(url);
    out.push({ url, source, context: text });
  }
  return out;
}

function hostname(u: string): string {
  try {
    return new URL(u).hostname;
  } catch {
    return u;
  }
}

interface Props {
  card: Card;
  messages: CardMessage[];
}

export function CardLinksPanel({ card, messages }: Props) {
  const links = useMemo<ExtractedLink[]>(() => {
    const all: ExtractedLink[] = [
      ...extract("title", card.title),
      ...extract("description", card.description),
      ...messages.flatMap((m) => extract("chat", m.body)),
    ];
    const seen = new Set<string>();
    return all.filter((l) => {
      if (seen.has(l.url)) return false;
      seen.add(l.url);
      return true;
    });
  }, [card.title, card.description, messages]);

  if (links.length === 0) {
    return (
      <Stack gap="xs" p="md" align="center" justify="center" style={{ minHeight: 200 }}>
        <Text size="sm" c="dimmed">Sin enlaces detectados</Text>
        <Text size="xs" c="dimmed" ta="center">
          Pega URLs en el titulo, descripcion o chat y apareceran aqui.
        </Text>
      </Stack>
    );
  }

  const badgeColor = (s: ExtractedLink["source"]): string => {
    if (s === "title") return "grape";
    if (s === "description") return "blue";
    return "teal";
  };

  const badgeLabel = (s: ExtractedLink["source"]): string => {
    if (s === "title") return "titulo";
    if (s === "description") return "descripcion";
    return "chat";
  };

  return (
    <Stack gap={6} p={4}>
      {links.map((l) => (
        <Paper key={l.url} withBorder p="xs" radius="sm">
          <Group gap="xs" wrap="nowrap" justify="space-between" align="flex-start">
            <Box style={{ flex: 1, minWidth: 0 }}>
              <Anchor href={l.url} target="_blank" rel="noopener noreferrer" size="sm" style={{ wordBreak: "break-all" }}>
                <Group gap={4} wrap="nowrap" align="center">
                  <IconExternalLink size={12} />
                  <span>{hostname(l.url)}</span>
                </Group>
              </Anchor>
              <Text size="xs" c="dimmed" style={{ wordBreak: "break-all" }}>{l.url}</Text>
            </Box>
            <Badge size="xs" variant="light" color={badgeColor(l.source)}>
              {badgeLabel(l.source)}
            </Badge>
          </Group>
        </Paper>
      ))}
    </Stack>
  );
}
