"use client"

import { Info } from "lucide-react"
import type { ReactNode } from "react"

import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { cn } from "@/lib/utils"

import type { DetectAcProvenance, DetectAtProvenance } from "./schema"

type ChecklistItem = { label: string; detail?: string; ok: boolean }

function WhyPopover({
  title,
  triggerClassName,
  items,
  footer,
}: {
  title: string
  triggerClassName: string
  items: ChecklistItem[]
  footer?: ReactNode
}) {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          type="button"
          className={cn(
            "inline-flex size-3.5 shrink-0 items-center justify-center rounded-full",
            triggerClassName,
          )}
          aria-label={title}
          title={title}
          onClick={(event) => event.stopPropagation()}
        >
          <Info className="size-3.5" />
        </button>
      </PopoverTrigger>
      <PopoverContent
        align="start"
        side="bottom"
        className="z-[80] w-80 gap-2 p-3"
        onClick={(event) => event.stopPropagation()}
      >
        <div className="text-xs font-semibold text-foreground">{title}</div>
        <ul className="max-h-72 space-y-1.5 overflow-y-auto">
          {items.map((item) => (
            <li
              key={`${item.label}-${item.detail ?? ""}`}
              className="flex gap-2 text-xs"
            >
              <span
                className={cn(
                  "mt-0.5 shrink-0 font-semibold",
                  item.ok ? "text-sky-700" : "text-muted-foreground",
                )}
                aria-hidden
              >
                {item.ok ? "✓" : "•"}
              </span>
              <span className="min-w-0">
                <span className="block text-foreground">{item.label}</span>
                {item.detail ? (
                  <span className="mt-0.5 block break-words font-mono text-[10px] text-muted-foreground">
                    {item.detail}
                  </span>
                ) : null}
              </span>
            </li>
          ))}
        </ul>
        {footer}
      </PopoverContent>
    </Popover>
  )
}

export function DetectWhyAcPopover({ detectAc }: { detectAc: DetectAcProvenance | null }) {
  if (!detectAc) return null

  const items: ChecklistItem[] = [
    {
      label: "Asset class",
      detail: detectAc.assetClass || "—",
      ok: Boolean(detectAc.assetClass),
    },
    {
      label: "Kind",
      detail: detectAc.kind || "—",
      ok: Boolean(detectAc.kind),
    },
    {
      label: "Reason",
      detail: detectAc.reasonLabel || detectAc.reason || "—",
      ok: Boolean(detectAc.reasonLabel || detectAc.reason),
    },
  ]

  for (const rule of detectAc.matchedRules ?? []) {
    const condition = [rule.field, rule.operator, rule.value]
      .filter((part) => part != null && String(part) !== "")
      .join(" · ")
    items.push({
      label: rule.summary || rule.label || rule.code,
      detail: condition || undefined,
      ok: true,
    })
  }

  return (
    <WhyPopover
      title="Why Asset Class (Common Detect)"
      triggerClassName="text-sky-700 hover:bg-sky-200/70 hover:text-sky-900 dark:text-sky-300 dark:hover:bg-sky-900/50"
      items={items}
    />
  )
}

export function DetectWhyAtPopover({
  detectAt,
  detectFlagged,
}: {
  detectAt: DetectAtProvenance | null
  detectFlagged?: boolean
}) {
  if (!detectAt) return null

  const via = detectAt.via || ""
  const items: ChecklistItem[] = [
    {
      label: "Asset Type",
      detail: detectAt.thenAssetType || "—",
      ok: Boolean(detectAt.thenAssetType),
    },
    {
      label:
        via === "rule"
          ? "Matched name rule"
          : via === "default"
            ? "Class Default Asset Type"
            : "How assigned",
      detail:
        via === "rule"
          ? detectAt.operator
            ? `${detectAt.operator} "${detectAt.value ?? ""}"`
            : detectAt.label || "name rule matched"
          : via === "default"
            ? "No name rule matched — used Default for this Asset Class"
            : detectAt.reason || via || "—",
      ok: via === "rule" || via === "default",
    },
  ]

  if (detectAt.matchedRuleId != null) {
    items.push({
      label: "Rule",
      detail: `#${detectAt.matchedRuleId}${detectAt.label ? ` · ${detectAt.label}` : ""}`,
      ok: true,
    })
  }

  items.push({
    label: "Flag IAM",
    detail: detectAt.flagIam || detectFlagged ? "Yes" : "No",
    ok: Boolean(detectAt.flagIam || detectFlagged),
  })

  return (
    <WhyPopover
      title="Why Asset Type (AT Detect)"
      triggerClassName="text-orange-700 hover:bg-orange-200/70 hover:text-orange-900 dark:text-orange-300 dark:hover:bg-orange-900/50"
      items={items}
    />
  )
}
