import { useState, useCallback } from "react";
import type { DiffLine, ReviewComment } from "./types";
import { LineWithComments } from "./LineWithComments";

interface HunkRowsProps {
  hunk: { header: string; lines: DiffLine[] };
  filePath: string;
  comments: ReviewComment[];
  onAddComment: (
    filePath: string,
    lineNumber: number,
    lineType: DiffLine["type"],
    body: string,
  ) => void;
  onResolveComment: (commentId: string) => void;
  onUnresolveComment: (commentId: string) => void;
}

export function HunkRows({
  hunk,
  filePath,
  comments,
  onAddComment,
  onResolveComment,
  onUnresolveComment,
}: HunkRowsProps) {
  const [commentingLine, setCommentingLine] = useState<{
    lineNumber: number;
    lineType: DiffLine["type"];
  } | null>(null);

  const handleSubmitComment = useCallback(
    (body: string) => {
      if (!commentingLine) return;
      onAddComment(
        filePath,
        commentingLine.lineNumber,
        commentingLine.lineType,
        body,
      );
      setCommentingLine(null);
    },
    [commentingLine, filePath, onAddComment],
  );

  return (
    <>
      {/* Hunk header */}
      <tr>
        <td
          colSpan={3}
          className="px-3 py-1 text-muted-foreground bg-blue-50 dark:bg-blue-950/30 text-[11px] select-none"
        >
          {hunk.header}
        </td>
      </tr>

      {hunk.lines.map((line, li) => {
        const lineKey = line.newLineNumber ?? line.oldLineNumber ?? li;
        const lineComments = comments.filter(
          (c) => c.lineNumber === lineKey && c.lineType === line.type,
        );
        const isCommenting =
          commentingLine?.lineNumber === lineKey &&
          commentingLine?.lineType === line.type;

        return (
          <LineWithComments
            key={`${line.type}-${lineKey}-${li}`}
            line={line}
            lineKey={lineKey}
            lineComments={lineComments}
            isCommenting={isCommenting}
            onStartComment={() =>
              setCommentingLine({ lineNumber: lineKey, lineType: line.type })
            }
            onCancelComment={() => setCommentingLine(null)}
            onSubmitComment={handleSubmitComment}
            onResolveComment={onResolveComment}
            onUnresolveComment={onUnresolveComment}
          />
        );
      })}
    </>
  );
}
