import { formatDistanceToNow } from 'date-fns';

const PRIORITY_STYLE = {
  P1: 'bg-ap-red/20 text-ap-red',
  P2: 'bg-ap-orange/20 text-ap-orange',
  P3: 'bg-ap-yellow/20 text-ap-yellow',
  P4: 'bg-ap-blue/20 text-ap-blue',
};

const STATUS_COLOR = {
  Open: 'text-ap-red',
  Investigating: 'text-ap-orange',
  Contained: 'text-ap-yellow',
  Resolved: 'text-ap-green',
};

const STATUS_DOT = {
  Open: 'bg-ap-red',
  Investigating: 'bg-ap-orange',
  Contained: 'bg-ap-yellow',
  Resolved: 'bg-ap-green',
};

const STATUS_ORDER = ['Open', 'Investigating', 'Contained', 'Resolved'];

function getRelativeTime(created) {
  if (!created) return '--';
  const date = created instanceof Date ? created : new Date(created);
  if (Number.isNaN(date.getTime())) return '--';
  return formatDistanceToNow(date, { addSuffix: true });
}

function PriorityBadge({ priority }) {
  const style = PRIORITY_STYLE[priority] || PRIORITY_STYLE.P4;
  return (
    <span className={`font-mono text-[10px] font-bold px-1.5 py-0.5 select-none ${style}`}>
      {priority}
    </span>
  );
}

function StatusBadge({ status }) {
  const color = STATUS_COLOR[status] || STATUS_COLOR.Open;
  return (
    <span className={`font-mono text-[10px] uppercase select-none ${color}`}>
      {status}
    </span>
  );
}

function IncidentCard({ incident }) {
  const { id, description, status, priority, assignee, created } = incident;

  return (
    <div className="mx-3 my-2 p-3 bg-ap-dark border border-white/5">
      {/* Top row: priority + ID + status */}
      <div className="flex items-center gap-2">
        <PriorityBadge priority={priority} />
        <span className="font-mono text-xs text-ap-silver">
          {id}
        </span>
        <span className="ml-auto shrink-0">
          <StatusBadge status={status} />
        </span>
      </div>

      {/* Description */}
      <p className="text-xs text-ap-silver mt-1 truncate">
        {description}
      </p>

      {/* Bottom row: assignee + relative time */}
      <div className="flex items-center gap-2 mt-2">
        {assignee && (
          <span className="font-mono text-[10px] text-ap-silver-dim px-1.5 py-0.5 bg-white/5">
            {assignee}
          </span>
        )}
        <span className="ml-auto font-mono text-[10px] text-ap-silver-dim tabular-nums">
          {getRelativeTime(created)}
        </span>
      </div>
    </div>
  );
}

function StatsBar({ incidents }) {
  const counts = STATUS_ORDER.reduce((acc, status) => {
    acc[status] = incidents.filter((i) => i.status === status).length;
    return acc;
  }, {});

  return (
    <div className="flex items-center gap-4 px-3 py-2 border-b border-white/5">
      {STATUS_ORDER.map((status) => (
        <div key={status} className="flex items-center gap-1.5">
          <span className={`inline-block w-1.5 h-1.5 ${STATUS_DOT[status]}`} />
          <span className="font-mono text-[10px] text-ap-silver-dim">
            {status}
          </span>
          <span className="font-mono text-[10px] font-bold text-ap-silver tabular-nums">
            {counts[status]}
          </span>
        </div>
      ))}
    </div>
  );
}

export default function IncidentTracker({ incidents = [] }) {
  const activeCount = incidents.filter((i) => i.status !== 'Resolved').length;

  return (
    <div className="panel h-full flex flex-col">
      {/* Panel header */}
      <div className="panel-header">
        <span className="dot" />
        <span>Active Incidents</span>
        <span className="ml-auto px-1.5 py-0.5 text-[9px] font-mono font-bold tabular-nums bg-ap-red-dim text-ap-red select-none">
          {activeCount}
        </span>
      </div>

      {/* Stats bar */}
      <StatsBar incidents={incidents} />

      {/* Scrollable incident list */}
      <div className="flex-1 overflow-y-auto">
        {incidents.length === 0 && (
          <div className="px-3 py-6 text-center font-mono text-xs text-ap-silver-dim">
            No incidents
          </div>
        )}
        {incidents.map((incident) => (
          <IncidentCard key={incident.id} incident={incident} />
        ))}
      </div>
    </div>
  );
}
