import { useState, useCallback } from "react";
import type { DiffLine, ReviewComment } from "./types";
import { LineWithComments } from "./LineWithComments";
import type { LineTokenMap } from "./use-syntax-highlight";

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;
  onReplyComment?: (parentCommentId: string, body: string) => void;
  onEditComment?: (commentId: string, body: string) => void;
  tokenMap?: LineTokenMap | null;
}

export function HunkRows({
  hunk,
  filePath,
  comments,
  onAddComment,
  onResolveComment,
  onUnresolveComment,
  onReplyComment,
  onEditComment,
  tokenMap,
}: 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-diff-hunk-bg text-[11px] select-none border-l-2 border-l-primary/20"
        >
          {(() => {
            const match = hunk.header.match(/^(@@[^@]+@@)(.*)$/);
            if (match) {
              const prefix = match[1];
              const context = match[2].trim();
              return (
                <>
                  <span className="text-muted-foreground/60">{prefix}</span>
                  {context && (
                    <span className="ml-1 text-muted-foreground/80 font-medium">
                      {context}
                    </span>
                  )}
                </>
              );
            }
            return 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}
            onReplyComment={onReplyComment}
            onEditComment={onEditComment}
            tokens={
              line.newLineNumber !== null
                ? tokenMap?.get(line.newLineNumber) ?? undefined
                : undefined
            }
          />
        );
      })}
    </>
  );
}
