import { Clock, AlertCircle, CheckCircle2, CalendarClock } from "lucide-react";
import { memo } from "react";

interface DeadlineBadgeProps {
  deadline?: string | null;
  deadlineStatus?: string | null;
  priority?: string | null;
  isCompleted?: boolean;
  compact?: boolean; // hiển thị gọn trong card list
}

const PRIORITY_LABEL: Record<string, { label: string; color: string }> = {
  low: { label: "Thấp", color: "#6b7280" },
  medium: { label: "Trung bình", color: "#f59e0b" },
  high: { label: "Cao", color: "#f97316" },
  urgent: { label: "Khẩn cấp", color: "#ef4444" },
};

function formatDeadline(isoStr: string): string {
  const dt = new Date(isoStr);
  const now = new Date();
  const diffMs = dt.getTime() - now.getTime();
  const diffH = Math.floor(diffMs / (1000 * 60 * 60));
  const diffD = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  const timeStr = dt.toLocaleTimeString("vi-VN", { hour: "2-digit", minute: "2-digit" });
  const dateStr = dt.toLocaleDateString("vi-VN", { day: "2-digit", month: "2-digit" });

  if (diffMs < 0) {
    // Quá hạn
    const overH = Math.abs(diffH);
    if (overH < 24) return `Quá hạn ${overH}h`;
    return `Quá hạn ${Math.abs(diffD)} ngày`;
  }

  if (diffH < 1) return `Còn < 1 giờ — ${timeStr}`;
  if (diffH < 24)
    return `Còn ${diffH}h — ${timeStr}`;
  if (diffD === 0) return `Hôm nay ${timeStr}`;
  if (diffD === 1) return `Ngày mai ${timeStr}`;
  return `${dateStr} ${timeStr} (còn ${diffD} ngày)`;
}

const STATUS_STYLES: Record<
  string,
  { bg: string; text: string; border: string; icon: React.ReactNode }
> = {
  OVERDUE: {
    bg: "#fef2f2",
    text: "#dc2626",
    border: "#fca5a5",
    icon: <AlertCircle size={12} />,
  },
  PENDING: {
    bg: "#fff7ed",
    text: "#ea580c",
    border: "#fdba74",
    icon: <Clock size={12} />,
  },
  TODAY: {
    bg: "#eff6ff",
    text: "#2563eb",
    border: "#93c5fd",
    icon: <CalendarClock size={12} />,
  },
  DONE: {
    bg: "#f0fdf4",
    text: "#16a34a",
    border: "#86efac",
    icon: <CheckCircle2 size={12} />,
  },
};

function resolveDisplayStatus(
  deadline: string | null | undefined,
  deadlineStatus: string | null | undefined,
  isCompleted: boolean
): string {
  if (isCompleted || deadlineStatus === "DONE") return "DONE";
  if (deadlineStatus === "OVERDUE") return "OVERDUE";
  // Check if today
  if (deadline) {
    const dt = new Date(deadline);
    const now = new Date();
    if (
      dt.getFullYear() === now.getFullYear() &&
      dt.getMonth() === now.getMonth() &&
      dt.getDate() === now.getDate()
    )
      return "TODAY";
  }
  return "PENDING";
}

const DeadlineBadge = memo(
  ({
    deadline,
    deadlineStatus,
    priority,
    isCompleted = false,
    compact = false,
  }: DeadlineBadgeProps) => {
    if (!deadline && !priority) return null;

    const displayStatus = resolveDisplayStatus(deadline, deadlineStatus, isCompleted);
    const style = STATUS_STYLES[displayStatus];
    const priorityInfo = priority ? PRIORITY_LABEL[priority] : null;

    return (
      <div
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: "6px",
          flexWrap: "wrap",
          marginTop: compact ? "4px" : "8px",
        }}
      >
        {/* Deadline badge */}
        {deadline && (
          <span
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: "4px",
              padding: compact ? "2px 7px" : "3px 9px",
              borderRadius: "999px",
              fontSize: compact ? "11px" : "12px",
              fontWeight: 500,
              background: style.bg,
              color: style.text,
              border: `1px solid ${style.border}`,
              lineHeight: 1.5,
              textDecoration: isCompleted ? "line-through" : "none",
              opacity: isCompleted ? 0.7 : 1,
            }}
          >
            {style.icon}
            {formatDeadline(deadline)}
          </span>
        )}

        {/* Priority badge */}
        {priorityInfo && (
          <span
            style={{
              display: "inline-flex",
              alignItems: "center",
              padding: compact ? "2px 7px" : "3px 9px",
              borderRadius: "999px",
              fontSize: compact ? "11px" : "12px",
              fontWeight: 600,
              color: "white",
              background: priorityInfo.color,
              lineHeight: 1.5,
              letterSpacing: "0.02em",
            }}
          >
            {priorityInfo.label.toUpperCase()}
          </span>
        )}
      </div>
    );
  }
);

DeadlineBadge.displayName = "DeadlineBadge";

export default DeadlineBadge;
