/**
 * TestPhaseTimeline
 *
 * Read-only timeline of automated phase durations, with Tempo sync status and
 * a manual "Sync to Tempo" button for the Red Team Execution phase.
 *
 *   1. Red Team Execution  (red_started_at → blue_started_at, minus paused)
 *   2. Blue Queue           (blue_started_at → blue_work_started_at)
 *   3. Blue Evaluation      (blue_work_started_at → …)
 *   4. Red Lead Validation  (red_validated_at + status)
 *   5. Blue Lead Validation (blue_validated_at + status)
 */

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Clock, Sword, Shield, CheckCircle, XCircle, Timer, RefreshCw, Loader2,
} from "lucide-react";
import type { Test } from "../types/models";
import { listTestWorklogs, type Worklog } from "../api/worklogs";
import { syncTestToTempo } from "../api/tests";

// ── Helpers ──────────────────────────────────────────────────────────

function parseDate(s: string): Date {
  return new Date(s.endsWith("Z") ? s : s + "Z");
}

function durationSeconds(start: string, end: string, pausedSecs = 0): number {
  const ms = parseDate(end).getTime() - parseDate(start).getTime();
  return Math.max(0, Math.floor(ms / 1000) - pausedSecs);
}

function fmtDuration(secs: number): string {
  if (secs < 60) return `${secs}s`;
  if (secs < 3600) return `${Math.floor(secs / 60)}m`;
  const h = Math.floor(secs / 3600);
  const m = Math.floor((secs % 3600) / 60);
  return m > 0 ? `${h}h ${m}m` : `${h}h`;
}

function fmtTs(s: string): string {
  return parseDate(s).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

// ── Phase row ─────────────────────────────────────────────────────────

interface PhaseRowProps {
  dotClass: string;
  icon: React.ReactNode;
  label: string;
  badge?: React.ReactNode;
  startTs: string | null;
  duration?: number | null;
  isLast?: boolean;
  extra?: React.ReactNode;
}

function PhaseRow({ dotClass, icon, label, badge, startTs, duration, isLast, extra }: PhaseRowProps) {
  return (
    <div className="relative flex gap-3 py-2">
      {!isLast && (
        <div className="absolute left-[15px] top-[18px] bottom-0 w-px bg-gray-700/60" />
      )}
      <div
        className={`relative z-10 mt-1 h-[10px] w-[10px] shrink-0 rounded-full border-2 bg-gray-900 ${dotClass}`}
        style={{ marginLeft: "6px" }}
      />
      <div className="flex-1 min-w-0 pb-1">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-xs text-gray-400">{icon}</span>
          <span className="text-xs font-medium text-gray-200">{label}</span>
          {badge}
          {duration != null && (
            <span className="ml-auto text-xs font-semibold text-cyan-400">
              {fmtDuration(duration)}
            </span>
          )}
        </div>
        {startTs && (
          <p className="mt-0.5 text-xs text-gray-500">{fmtTs(startTs)}</p>
        )}
        {extra && <div className="mt-1.5">{extra}</div>}
      </div>
    </div>
  );
}

// ── Validation badge ──────────────────────────────────────────────────

function ValidationBadge({ status }: { status: string | null }) {
  if (!status) return null;
  if (status === "approved")
    return (
      <span className="flex items-center gap-0.5 rounded px-1.5 py-0.5 text-xs bg-green-900/40 text-green-400">
        <CheckCircle className="h-3 w-3" /> Approved
      </span>
    );
  if (status === "rejected")
    return (
      <span className="flex items-center gap-0.5 rounded px-1.5 py-0.5 text-xs bg-red-900/40 text-red-400">
        <XCircle className="h-3 w-3" /> Rejected
      </span>
    );
  return (
    <span className="rounded px-1.5 py-0.5 text-xs bg-yellow-900/30 text-yellow-400">
      {status}
    </span>
  );
}

// ── Tempo sync badge / button ─────────────────────────────────────────

function TempoSyncBadge({
  worklog,
  testId,
  onSynced,
}: {
  worklog: Worklog | undefined;
  testId: string;
  onSynced: () => void;
}) {
  const [toast, setToast] = useState<string | null>(null);

  const mutation = useMutation({
    mutationFn: () => syncTestToTempo(testId),
    onSuccess: (data) => {
      const r = data.results[0];
      if (r?.status === "synced") {
        setToast("Synced to Tempo ✓");
        onSynced();
      } else if (r?.status === "already_synced") {
        setToast("Already synced");
      } else {
        setToast(r?.detail ?? "Skipped — check Tempo settings");
      }
      setTimeout(() => setToast(null), 4000);
    },
    onError: (e: unknown) => {
      const msg =
        e && typeof e === "object" && "response" in e
          ? ((e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? "Sync failed")
          : "Sync failed";
      setToast(msg);
      setTimeout(() => setToast(null), 5000);
    },
  });

  // Already synced
  if (worklog?.tempo_synced) {
    return (
      <span
        className="flex items-center gap-0.5 rounded px-1.5 py-0.5 text-xs bg-green-900/30 text-green-400"
        title={`Synced to Tempo${worklog.tempo_worklog_id ? ` (ID: ${worklog.tempo_worklog_id})` : ""}`}
      >
        <CheckCircle className="h-3 w-3" /> Tempo
      </span>
    );
  }

  // Not synced — show button
  return (
    <div className="flex items-center gap-2 flex-wrap">
      <button
        onClick={() => mutation.mutate()}
        disabled={mutation.isPending}
        className="flex items-center gap-1 rounded px-2 py-0.5 text-xs border border-blue-500/30 bg-blue-900/20 text-blue-400 hover:bg-blue-900/40 disabled:opacity-50 transition-colors"
        title="Push this phase's time to Tempo"
      >
        {mutation.isPending ? (
          <Loader2 className="h-3 w-3 animate-spin" />
        ) : (
          <RefreshCw className="h-3 w-3" />
        )}
        Sync to Tempo
      </button>
      {toast && (
        <span className="text-xs text-gray-400">{toast}</span>
      )}
    </div>
  );
}

// ── Main component ────────────────────────────────────────────────────

interface TestPhaseTimelineProps {
  test: Test;
  testId?: string;
}

export default function TestPhaseTimeline({ test, testId }: TestPhaseTimelineProps) {
  const queryClient = useQueryClient();

  const {
    red_started_at,
    blue_started_at,
    blue_work_started_at,
    red_paused_seconds,
    blue_paused_seconds,
    red_validated_at,
    blue_validated_at,
    red_validation_status,
    blue_validation_status,
  } = test;

  // Fetch worklogs when testId is provided
  const { data: worklogs = [] } = useQuery({
    queryKey: ["worklogs", "test", testId],
    queryFn: () => listTestWorklogs(testId!),
    enabled: !!testId,
  });

  const redWorklog = worklogs.find((w) => w.activity_type === "red_team_execution");

  const refreshWorklogs = () => {
    if (testId) queryClient.invalidateQueries({ queryKey: ["worklogs", "test", testId] });
  };

  // Compute per-phase durations
  const redExecSecs =
    red_started_at && blue_started_at
      ? durationSeconds(red_started_at, blue_started_at, red_paused_seconds)
      : null;

  const blueQueueSecs =
    blue_started_at && blue_work_started_at
      ? durationSeconds(blue_started_at, blue_work_started_at)
      : null;

  const blueEvalEnd = red_validated_at || blue_validated_at || null;
  const blueEvalSecs =
    blue_work_started_at && blueEvalEnd
      ? durationSeconds(blue_work_started_at, blueEvalEnd, blue_paused_seconds)
      : null;

  const hasRedExec = !!red_started_at;
  const hasBlueQueue = !!blue_started_at;
  const hasBlueEval = !!blue_work_started_at;
  const hasRedValidation = !!red_validated_at;
  const hasBlueValidation = !!blue_validated_at;

  const anyPhase =
    hasRedExec || hasBlueQueue || hasBlueEval || hasRedValidation || hasBlueValidation;

  if (!anyPhase) return null;

  const phases = [hasRedExec, hasBlueQueue, hasBlueEval, hasRedValidation, hasBlueValidation];
  const lastIdx = phases.lastIndexOf(true);
  let phaseIdx = -1;

  return (
    <div className="rounded-xl border border-gray-800 bg-gray-900 p-6">
      <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-white">
        <Timer className="h-5 w-5 text-cyan-400" />
        Phase Timeline
      </h2>

      <div className="relative space-y-0">
        {hasRedExec && (
          <PhaseRow
            dotClass="border-orange-500/60"
            icon={<Sword className="h-3 w-3 text-orange-400 inline" />}
            label="Red Team Execution"
            startTs={red_started_at}
            duration={redExecSecs}
            isLast={++phaseIdx === lastIdx}
            extra={
              testId ? (
                <TempoSyncBadge
                  worklog={redWorklog}
                  testId={testId}
                  onSynced={refreshWorklogs}
                />
              ) : undefined
            }
          />
        )}

        {hasBlueQueue && (
          <PhaseRow
            dotClass="border-yellow-500/60"
            icon={<Clock className="h-3 w-3 text-yellow-400 inline" />}
            label="Blue Queue"
            startTs={blue_started_at}
            duration={blueQueueSecs}
            isLast={++phaseIdx === lastIdx}
          />
        )}

        {hasBlueEval && (
          <PhaseRow
            dotClass="border-indigo-500/60"
            icon={<Shield className="h-3 w-3 text-indigo-400 inline" />}
            label="Blue Evaluation"
            startTs={blue_work_started_at}
            duration={blueEvalSecs}
            isLast={++phaseIdx === lastIdx}
          />
        )}

        {hasRedValidation && (
          <PhaseRow
            dotClass="border-orange-400/60"
            icon={<CheckCircle className="h-3 w-3 text-orange-400 inline" />}
            label="Red Lead Validation"
            badge={<ValidationBadge status={red_validation_status} />}
            startTs={red_validated_at}
            duration={null}
            isLast={++phaseIdx === lastIdx}
          />
        )}

        {hasBlueValidation && (
          <PhaseRow
            dotClass="border-indigo-400/60"
            icon={<CheckCircle className="h-3 w-3 text-indigo-400 inline" />}
            label="Blue Lead Validation"
            badge={<ValidationBadge status={blue_validation_status} />}
            startTs={blue_validated_at}
            duration={null}
            isLast={++phaseIdx === lastIdx}
          />
        )}
      </div>
    </div>
  );
}
