import { useState, useCallback, useMemo, useRef } from "react";
import { toast } from "sonner";
import { trpc } from "@/lib/trpc";
import { parseUnifiedDiff } from "./parse-diff";
import { DiffViewer } from "./DiffViewer";
import { ReviewSidebar } from "./ReviewSidebar";
import { PreviewPanel } from "./PreviewPanel";
import type { ReviewComment, ReviewStatus, DiffLine } from "./types";

interface ReviewTabProps {
  initiativeId: string;
}

export function ReviewTab({ initiativeId }: ReviewTabProps) {
  const [comments, setComments] = useState<ReviewComment[]>([]);
  const [status, setStatus] = useState<ReviewStatus>("pending");
  const fileRefs = useRef<Map<string, HTMLDivElement>>(new Map());

  // Fetch phases for this initiative
  const phasesQuery = trpc.listPhases.useQuery({ initiativeId });
  const pendingReviewPhases = useMemo(
    () => (phasesQuery.data ?? []).filter((p) => p.status === "pending_review"),
    [phasesQuery.data],
  );

  // Select first pending review phase
  const [selectedPhaseId, setSelectedPhaseId] = useState<string | null>(null);
  const activePhaseId = selectedPhaseId ?? pendingReviewPhases[0]?.id ?? null;

  // Fetch projects for this initiative (needed for preview)
  const projectsQuery = trpc.getInitiativeProjects.useQuery({ initiativeId });
  const firstProjectId = projectsQuery.data?.[0]?.id ?? null;

  // Fetch diff for active phase
  const diffQuery = trpc.getPhaseReviewDiff.useQuery(
    { phaseId: activePhaseId! },
    { enabled: !!activePhaseId },
  );

  const approveMutation = trpc.approvePhaseReview.useMutation({
    onSuccess: () => {
      setStatus("approved");
      toast.success("Phase approved and merged");
      phasesQuery.refetch();
    },
    onError: (err) => {
      toast.error(err.message);
    },
  });

  const files = useMemo(() => {
    if (!diffQuery.data?.rawDiff) return [];
    return parseUnifiedDiff(diffQuery.data.rawDiff);
  }, [diffQuery.data?.rawDiff]);

  const handleAddComment = useCallback(
    (filePath: string, lineNumber: number, lineType: DiffLine["type"], body: string) => {
      const newComment: ReviewComment = {
        id: `c${Date.now()}`,
        filePath,
        lineNumber,
        lineType,
        body,
        author: "you",
        createdAt: new Date().toISOString(),
        resolved: false,
      };
      setComments((prev) => [...prev, newComment]);
      toast.success("Comment added");
    },
    []
  );

  const handleResolveComment = useCallback((commentId: string) => {
    setComments((prev) =>
      prev.map((c) => (c.id === commentId ? { ...c, resolved: true } : c))
    );
  }, []);

  const handleUnresolveComment = useCallback((commentId: string) => {
    setComments((prev) =>
      prev.map((c) => (c.id === commentId ? { ...c, resolved: false } : c))
    );
  }, []);

  const handleApprove = useCallback(() => {
    if (!activePhaseId) return;
    approveMutation.mutate({ phaseId: activePhaseId });
  }, [activePhaseId, approveMutation]);

  const handleRequestChanges = useCallback(() => {
    setStatus("changes_requested");
    toast("Changes requested", {
      description: "The agent will be notified about the requested changes.",
    });
  }, []);

  const handleFileClick = useCallback((filePath: string) => {
    const el = fileRefs.current.get(filePath);
    if (el) {
      el.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  }, []);

  if (pendingReviewPhases.length === 0) {
    return (
      <div className="flex h-64 items-center justify-center text-muted-foreground">
        <p>No phases pending review</p>
      </div>
    );
  }

  const activePhaseName = diffQuery.data?.phaseName ?? pendingReviewPhases.find(p => p.id === activePhaseId)?.name ?? "Phase";
  const sourceBranch = diffQuery.data?.sourceBranch ?? "";

  return (
    <div className="space-y-4">
      {/* Phase selector if multiple pending */}
      {pendingReviewPhases.length > 1 && (
        <div className="flex gap-2">
          {pendingReviewPhases.map((phase) => (
            <button
              key={phase.id}
              onClick={() => setSelectedPhaseId(phase.id)}
              className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
                phase.id === activePhaseId
                  ? "border-primary bg-primary/10 font-medium"
                  : "border-border hover:bg-muted"
              }`}
            >
              {phase.name}
            </button>
          ))}
        </div>
      )}

      {/* Preview panel */}
      {firstProjectId && sourceBranch && (
        <PreviewPanel
          initiativeId={initiativeId}
          phaseId={activePhaseId ?? undefined}
          projectId={firstProjectId}
          branch={sourceBranch}
        />
      )}

      {diffQuery.isLoading ? (
        <div className="flex h-64 items-center justify-center text-muted-foreground">
          Loading diff...
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr_300px]">
          {/* Left: Diff */}
          <div className="min-w-0">
            <div className="flex items-center justify-between border-b border-border pb-3 mb-4">
              <h2 className="text-lg font-semibold">Review: {activePhaseName}</h2>
              <span className="text-xs text-muted-foreground">
                {comments.filter((c) => !c.resolved).length} unresolved thread
                {comments.filter((c) => !c.resolved).length !== 1 ? "s" : ""}
              </span>
            </div>
            {files.length === 0 ? (
              <div className="flex h-32 items-center justify-center text-muted-foreground">
                No changes in this phase
              </div>
            ) : (
              <DiffViewer
                files={files}
                comments={comments}
                onAddComment={handleAddComment}
                onResolveComment={handleResolveComment}
                onUnresolveComment={handleUnresolveComment}
              />
            )}
          </div>

          {/* Right: Sidebar */}
          <div className="w-full lg:w-[300px]">
            <ReviewSidebar
              title={`Phase: ${activePhaseName}`}
              description={`Review changes from phase "${activePhaseName}" before merging into the initiative branch.`}
              author="system"
              status={status}
              sourceBranch={sourceBranch}
              targetBranch={diffQuery.data?.targetBranch ?? ""}
              files={files}
              comments={comments}
              onApprove={handleApprove}
              onRequestChanges={handleRequestChanges}
              onFileClick={handleFileClick}
            />
          </div>
        </div>
      )}
    </div>
  );
}
