"use client";
import * as React from "react";
import { useRouter } from "next/navigation";
import { ChevronDown, Rocket, RotateCcw, AlertTriangle } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { CopyText } from "@/components/ui/copy-text";
import { EmptyState } from "@/components/ui/empty-state";
import { LogViewerButton } from "@/components/deploy-log-viewer";
import { deployToneFor, deployLabelFor, ago } from "@/lib/format";
import { cn } from "@/lib/utils";

export interface DeployRow {
  id: string;
  imageTag: string;
  status: string;
  startedAt: Date;
  finishedAt: Date | null;
  errorMsg: string | null;
  logBlob?: string | null;
  commitHash?: string | null;
}

export function DeployHistoryList({
  rows,
  projectId,
}: {
  rows: DeployRow[];
  projectId: string;
}) {
  if (rows.length === 0) {
    return (
      <EmptyState
        icon={<Rocket className="h-5 w-5" />}
        title="Chưa có lượt deploy nào"
        description="Bấm Deploy để build commit hiện tại và push lên máy chủ đã cấu hình."
      />
    );
  }
  return (
    <ul className="divide-y divide-border/60">
      {rows.map((d) => (
        <DeployRowItem key={d.id} d={d} projectId={projectId} />
      ))}
    </ul>
  );
}

function DeployRowItem({ d, projectId }: { d: DeployRow; projectId: string }) {
  const [expanded, setExpanded] = React.useState(false);
  const router = useRouter();
  const tone = deployToneFor(d.status);
  const tag = d.imageTag.split("/").pop() ?? d.imageTag;

  const onRollback = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!confirm(`Rollback về phiên bản ${tag}?`)) return;
    const res = await fetch(`/api/projects/${projectId}/rollback`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ deployId: d.id }),
    });
    if (res.ok) {
      router.refresh();
    } else {
      const err = await res.json().catch(() => ({}));
      alert(`Rollback thất bại: ${err.error ?? res.status}`);
    }
  };

  return (
    <li>
      <button
        type="button"
        onClick={() => setExpanded((v) => !v)}
        className="flex w-full items-center gap-3 px-5 py-3 text-left transition-colors hover:bg-accent/30"
      >
        <Badge tone={tone} dot>
          {deployLabelFor(d.status)}
        </Badge>
        <CopyText
          value={d.imageTag}
          display={tag}
          truncate
          className="min-w-0 flex-1"
        />
        <span className="hidden shrink-0 text-2xs uppercase tracking-wider text-muted-foreground sm:inline">
          {ago(d.startedAt)}
        </span>
        <ChevronDown
          className={cn(
            "h-4 w-4 shrink-0 text-muted-foreground transition-transform",
            expanded && "rotate-180",
          )}
        />
      </button>

      {expanded && (
        <div className="space-y-3 border-t border-border/60 bg-surface/40 px-5 py-4 animate-fade-in">
          <div className="grid gap-3 text-xs sm:grid-cols-2">
            <div className="space-y-1">
              <span className="text-2xs font-medium uppercase tracking-wider text-muted-foreground">
                Image
              </span>
              <CopyText value={d.imageTag} className="block" />
            </div>
            <div className="space-y-1">
              <span className="text-2xs font-medium uppercase tracking-wider text-muted-foreground">
                Commit
              </span>
              {d.commitHash ? (
                <CopyText value={d.commitHash} display={d.commitHash.slice(0, 8)} />
              ) : (
                <span className="text-muted-foreground">—</span>
              )}
            </div>
            <div className="space-y-1">
              <span className="text-2xs font-medium uppercase tracking-wider text-muted-foreground">
                Bắt đầu
              </span>
              <span className="text-mono text-foreground">
                {new Date(d.startedAt).toISOString().replace("T", " ").slice(0, 19)}
              </span>
            </div>
            <div className="space-y-1">
              <span className="text-2xs font-medium uppercase tracking-wider text-muted-foreground">
                Kết thúc
              </span>
              <span className="text-mono text-foreground">
                {d.finishedAt
                  ? new Date(d.finishedAt).toISOString().replace("T", " ").slice(0, 19)
                  : "—"}
              </span>
            </div>
          </div>

          {d.errorMsg && (
            <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/10 p-3 text-xs text-destructive">
              <AlertTriangle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
              <div>
                <div className="font-medium">Lỗi</div>
                <code className="text-mono">{d.errorMsg}</code>
              </div>
            </div>
          )}

          <div className="flex flex-wrap items-center gap-2">
            {d.logBlob && (
              <LogViewerButton
                title={`Deploy ${d.id.slice(0, 8)} — ${tag}`}
                content={d.logBlob}
              />
            )}
            {d.status === "success" && (
              <button
                type="button"
                onClick={onRollback}
                className="inline-flex items-center gap-1.5 rounded-md border border-border bg-transparent px-3 py-1.5 text-xs font-medium text-foreground/85 transition-colors hover:border-warning/40 hover:bg-warning/10 hover:text-warning"
              >
                <RotateCcw className="h-3 w-3" />
                Rollback về phiên bản này
              </button>
            )}
          </div>
        </div>
      )}
    </li>
  );
}
