import { cva } from "class-variance-authority";
import { format } from "date-fns";
import { Activity, Link as LinkIcon } from "lucide-react";
import * as React from "react";

import { Checkbox } from "@/components/ui/checkbox";
import type { ProcessedAlert } from "@/lib/types/alerts";
import { cn } from "@/lib/utils";

function formatDuration(ms: number): string {
  const seconds = Math.floor(ms / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  if (days > 0) return `${days}d ${hours % 24}h`;
  if (hours > 0) return `${hours}h ${minutes % 60}m`;
  if (minutes > 0) return `${minutes}m`;
  return `${seconds}s`;
}

function formatTimeRange(start: number, end: number): string {
  return `${format(start, "HH:mm:ss")} - ${format(end, "HH:mm:ss")}`;
}

const alertItemVariants = cva(
  "group relative flex w-full items-center gap-3 border-b border-border p-3 transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
  {
    variants: {
      status: {
        firing:
          "bg-destructive/5 hover:bg-destructive/10 border-l-2 border-l-destructive",
        resolved: "border-l-2 border-l-transparent",
        pending: "border-l-2 border-l-yellow-500/50",
      },
      invalid: {
        true: "opacity-60 grayscale bg-muted/30",
        false: "",
      },
    },
    defaultVariants: {
      status: "resolved",
      invalid: false,
    },
  },
);

interface AlertListItemProps {
  alert: ProcessedAlert;
  isSelected?: boolean;
  onToggleInvalid: (id: number, isInvalid: boolean) => void;
  onSelect: (alert: ProcessedAlert) => void;
  style?: React.CSSProperties;
}

export const AlertListItem = React.memo(
  ({
    alert,
    isSelected,
    onToggleInvalid,
    onSelect,
    style,
  }: AlertListItemProps) => {
    const status = alert.isFiring ? "firing" : "resolved";

    return (
      <div
        style={style}
        className={cn(
          alertItemVariants({ status, invalid: alert.isInvalid }),
          isSelected && "bg-muted border-l-primary",
        )}
        onClick={() => onSelect(alert)}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            onSelect(alert);
          }
        }}
      >
        <div
          className="flex h-full items-start pt-0.5"
          onClick={(e) => e.stopPropagation()}
        >
          <Checkbox
            checked={alert.isInvalid}
            onCheckedChange={(checked) =>
              onToggleInvalid(alert.id, checked === true)
            }
            aria-label="Mark as invalid"
          />
        </div>

        <div className="flex min-w-0 flex-1 flex-col gap-1">
          <div className="flex items-center justify-between gap-2">
            <span className="truncate text-xs font-semibold text-foreground">
              {alert.alertName || `Unknown Alert #${alert.alertId}`}
            </span>
            <span className="flex shrink-0 items-center gap-1 text-[10px] font-mono text-muted-foreground">
              {alert.durationMs > 0 && (
                <span>{formatDuration(alert.durationMs)}</span>
              )}
            </span>
          </div>

          <div className="flex items-center justify-between gap-2 text-[10px] text-muted-foreground">
            <div className="flex items-center gap-2">
              <span
                className={cn(
                  "uppercase tracking-wider",
                  alert.isFiring
                    ? "text-destructive font-bold"
                    : "text-green-600 dark:text-green-500",
                )}
              >
                {alert.newState}
              </span>
              <span className="text-border">|</span>
              <span className="font-mono">
                {formatTimeRange(alert.time, alert.timeEnd)}
              </span>
            </div>

            <div className="flex items-center gap-1.5">
              {alert.attachedIncidentId && (
                <div
                  className="flex items-center gap-0.5 text-primary"
                  title="Attached to incident"
                >
                  <LinkIcon className="size-3" />
                  <span className="font-mono">{alert.attachedIncidentId}</span>
                </div>
              )}
              {alert.isInvalid && (
                <Activity className="size-3 text-muted-foreground/50" />
              )}
            </div>
          </div>

          <div className="truncate text-[10px] text-muted-foreground/70 font-mono">
            {Object.entries(alert.values)
              .map(
                ([k, v]) =>
                  `${k}=${Number.isFinite(v) ? v.toFixed(1) : String(v)}`,
              )
              .join(", ")}
          </div>
        </div>

        {alert.isFiring && !alert.isInvalid && (
          <div className="absolute right-0 top-0 h-full w-0.5 bg-destructive" />
        )}
      </div>
    );
  },
);

AlertListItem.displayName = "AlertListItem";
