import { Activity, ChevronLeft } from "lucide-react";
import { Badge } from "../ui/badge";
import { type BackupJob, type BackupJobLog } from "@/app/lib/api";
import {
  formatBytes,
  formatDate,
  formatDuration,
  formatRelativeTime,
  StatusIcon,
  statusBg,
} from "./utils";

type JobDrilldownProps = {
  job: BackupJob;
  logs: BackupJobLog[];
  onBack: () => void;
};

export function JobDrilldown({ job, logs, onBack }: JobDrilldownProps) {
  return (
    <div className="space-y-4">
      <button
        onClick={onBack}
        className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
      >
        <ChevronLeft className="h-3 w-3" /> Back to jobs
      </button>

      <div className="rounded-lg border border-border bg-card p-5 space-y-4">
        <div className="flex items-center gap-3">
          <StatusIcon status={job.status} />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-sm font-semibold text-foreground capitalize">
                {job.job_type}
              </span>
              <Badge
                className={`text-tiny px-1.5 py-0 border ${statusBg[job.status] ?? ""}`}
              >
                {job.status}
              </Badge>
              {job.client_name && (
                <Badge variant="outline" className="text-tiny px-1.5 py-0">
                  {job.client_name}
                </Badge>
              )}
            </div>
            {job.label && (
              <p className="text-xs text-muted-foreground mt-0.5">
                {job.label}
              </p>
            )}
          </div>
        </div>

        {(job.status === "running" || job.status === "completed") && (
          <div className="space-y-1.5">
            <div className="flex items-center justify-between text-xs">
              <span className="text-muted-foreground">
                {job.progress_stage ?? "Processing"}
              </span>
              <span className="text-foreground font-medium tabular-nums">
                {job.progress_pct ?? 0}%
              </span>
            </div>
            <div className="h-2 w-full rounded-full bg-muted overflow-hidden">
              <div
                className={`h-full rounded-full transition-all duration-700 ${job.status === "completed" ? "bg-success" : "bg-primary"}`}
                style={{
                  width: `${Math.max(job.progress_pct ?? 0, job.status === "running" ? 5 : 0)}%`,
                }}
              />
            </div>
          </div>
        )}

        <div className="grid grid-cols-2 gap-3 text-xs">
          <div className="space-y-0.5">
            <p className="text-muted-foreground">Started</p>
            <p className="text-foreground">{formatDate(job.started_at)}</p>
          </div>
          {job.completed_at && (
            <div className="space-y-0.5">
              <p className="text-muted-foreground">Completed</p>
              <p className="text-foreground">{formatDate(job.completed_at)}</p>
            </div>
          )}
          <div className="space-y-0.5">
            <p className="text-muted-foreground">Duration</p>
            <p className="text-foreground tabular-nums">
              {formatDuration(job.started_at, job.completed_at)}
            </p>
          </div>
          {job.size_bytes && (
            <div className="space-y-0.5">
              <p className="text-muted-foreground">Size</p>
              <p className="text-foreground tabular-nums">
                {formatBytes(job.size_bytes)}
              </p>
            </div>
          )}
          {job.s3_key && (
            <div className="space-y-0.5 col-span-2">
              <p className="text-muted-foreground">S3 Key</p>
              <p className="text-foreground font-mono text-caption break-all">
                {job.s3_key}
              </p>
            </div>
          )}
        </div>

        {job.error_message && (
          <div className="flex items-start gap-2 rounded-lg border border-destructive-border bg-destructive-subtle p-3 text-xs text-destructive">
            <span className="wrap-break-word">{job.error_message}</span>
          </div>
        )}
      </div>

      <div className="space-y-1.5">
        <h4 className="text-xs font-semibold text-foreground flex items-center gap-1.5">
          <Activity className="h-3.5 w-3.5" /> Job Timeline
        </h4>
        {logs.length === 0 && (
          <p className="text-body-sm text-muted-foreground py-3 text-center">
            No log entries yet.
          </p>
        )}
        <div className="relative pl-4 space-y-0">
          {[...logs].reverse().map((log, i) => (
            <div key={log.id} className="relative pb-3 last:pb-0">
              {i < logs.length - 1 && (
                <div className="absolute -left-3 top-2 bottom-0 w-px bg-border" />
              )}
              <div
                className={`absolute -left-3.5 top-1.5 h-1.5 w-1.5 rounded-full ${
                  log.level === "error"
                    ? "bg-destructive"
                    : log.level === "warn"
                      ? "bg-warning"
                      : "bg-primary"
                }`}
              />
              <div className="text-body-sm">
                <span
                  className={`font-medium ${
                    log.level === "error"
                      ? "text-destructive"
                      : log.level === "warn"
                        ? "text-warning"
                        : "text-foreground"
                  }`}
                >
                  {log.message}
                </span>
                <span className="text-muted-foreground-subtle ml-2 tabular-nums">
                  {formatRelativeTime(log.created_at)}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
