"use client";

import { useMemo } from "react";
import { AlertTriangle, Bell, Timer, ChevronRight } from "lucide-react";
import { Badge } from "@/shared/components/ui/badge";
import { cn } from "@/shared/lib/utils";
import type { RegistryEntry } from "../types";

interface ImminentActionsProps {
  entries: RegistryEntry[];
  onNavigate?: (entry: RegistryEntry) => void;
}

interface ActionItem {
  entry: RegistryEntry;
  type: "expiry" | "ac-validity";
  label: string;
  detail: string;
  daysLeft: number;
  color: "red" | "amber";
}

/** Max lookahead window in days */
const HORIZON_DAYS = 60;

function formatDate(iso: string): string {
  try {
    return new Date(iso).toLocaleDateString("ro-RO", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  } catch {
    return iso;
  }
}

export function ImminentActions({ entries, onNavigate }: ImminentActionsProps) {
  const actions = useMemo(() => {
    const items: ActionItem[] = [];
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const nowMs = now.getTime();

    for (const entry of entries) {

      // Document expiry alerts (already expired or within horizon)
      if (entry.expiryDate) {
        const expiry = new Date(entry.expiryDate);
        expiry.setHours(0, 0, 0, 0);
        const daysLeft = Math.ceil((expiry.getTime() - nowMs) / (1000 * 60 * 60 * 24));

        if (daysLeft < 0) {
          items.push({
            entry,
            type: "expiry",
            label: `Expirat de ${Math.abs(daysLeft)} zile`,
            detail: `Valabil până: ${formatDate(entry.expiryDate)}`,
            daysLeft,
            color: "red",
          });
        } else if (daysLeft <= HORIZON_DAYS) {
          items.push({
            entry,
            type: "expiry",
            label: daysLeft === 0 ? "Expiră azi" : `Expiră în ${daysLeft} zile`,
            detail: `Valabil până: ${formatDate(entry.expiryDate)}`,
            daysLeft,
            color: daysLeft <= 14 ? "red" : "amber",
          });
        }
      }

      // AC validity alerts (already expired or within horizon)
      if (entry.acValidity?.enabled && !entry.acValidity.reminder.dismissed) {
        const ac = entry.acValidity;
        const validityMonths = ac.validityMonths ?? 12;
        const issuance = new Date(ac.issuanceDate);
        const validityEnd = new Date(issuance);
        validityEnd.setMonth(validityEnd.getMonth() + validityMonths);
        validityEnd.setHours(0, 0, 0, 0);
        const daysLeft = Math.ceil((validityEnd.getTime() - nowMs) / (1000 * 60 * 60 * 24));

        if (daysLeft < 0) {
          items.push({
            entry,
            type: "ac-validity",
            label: `AC expirat de ${Math.abs(daysLeft)} zile`,
            detail: `${validityMonths} luni de la ${formatDate(ac.issuanceDate)}`,
            daysLeft,
            color: "red",
          });
        } else if (daysLeft <= HORIZON_DAYS) {
          items.push({
            entry,
            type: "ac-validity",
            label: daysLeft === 0 ? "AC expiră azi" : `AC expiră în ${daysLeft} zile`,
            detail: `${validityMonths} luni de la ${formatDate(ac.issuanceDate)}`,
            daysLeft,
            color: daysLeft <= 30 ? "red" : "amber",
          });
        }
      }
    }

    // Most urgent first
    items.sort((a, b) => a.daysLeft - b.daysLeft);
    return items;
  }, [entries]);

  if (actions.length === 0) return null;

  const ICON_MAP = {
    expiry: Timer,
    "ac-validity": Bell,
  } as const;

  const COLOR_MAP = {
    red: {
      border: "border-red-200 dark:border-red-900",
      bg: "bg-red-50/60 dark:bg-red-950/20",
      text: "text-red-700 dark:text-red-400",
    },
    amber: {
      border: "border-amber-200 dark:border-amber-900",
      bg: "bg-amber-50/60 dark:bg-amber-950/20",
      text: "text-amber-700 dark:text-amber-400",
    },
  } as const;

  return (
    <div className="rounded-lg border border-amber-200 dark:border-amber-900 bg-amber-50/30 dark:bg-amber-950/10 p-3">
      <div className="flex items-center gap-2 mb-2.5">
        <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400" />
        <span className="text-sm font-semibold text-amber-800 dark:text-amber-300">
          De reînnoit
        </span>
        <Badge className="text-[10px] px-1.5 py-0 bg-amber-200 text-amber-800 dark:bg-amber-900/50 dark:text-amber-300">
          {actions.length}
        </Badge>
        <span className="ml-auto text-[10px] text-muted-foreground">
          următoarele {HORIZON_DAYS} zile
        </span>
      </div>
      <div className="space-y-1.5">
        {actions.map((action, i) => {
          const Icon = ICON_MAP[action.type];
          const colors = COLOR_MAP[action.color];
          return (
            <button
              key={`${action.entry.id}-${action.type}-${i}`}
              type="button"
              className={cn(
                "w-full flex items-center gap-2.5 rounded-md border px-3 py-1.5 text-left transition-colors hover:opacity-80",
                colors.border,
                colors.bg,
              )}
              onClick={() => onNavigate?.(action.entry)}
            >
              <Icon className={cn("h-3.5 w-3.5 shrink-0", colors.text)} />
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="font-mono text-[10px] text-muted-foreground shrink-0">
                    {action.entry.number}
                  </span>
                  <span className={cn("text-xs font-medium truncate", colors.text)}>
                    {action.label}
                  </span>
                </div>
                <p className="text-[10px] text-muted-foreground truncate">
                  {action.entry.subject} — {action.detail}
                </p>
              </div>
              <ChevronRight className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
            </button>
          );
        })}
      </div>
    </div>
  );
}
