import React from 'react';
import {
  RiGitMergeLine,
  RiGitBranchLine,
  RiLoader4Line,
  RiCheckLine,
  RiCloseLine,
  RiSparklingLine,
} from '@remixicon/react';
import { Button } from '@/components/ui/button';
import type { GitMergeInProgress, GitRebaseInProgress } from '@/lib/api/types';

interface InProgressOperationBannerProps {
  mergeInProgress: GitMergeInProgress | null | undefined;
  rebaseInProgress: GitRebaseInProgress | null | undefined;
  onContinue: () => Promise<void>;
  onAbort: () => Promise<void>;
  onResolveWithAI?: () => void;
  hasUnresolvedConflicts?: boolean;
  isLoading?: boolean;
}

export const InProgressOperationBanner: React.FC<InProgressOperationBannerProps> = ({
  mergeInProgress,
  rebaseInProgress,
  onContinue,
  onAbort,
  onResolveWithAI,
  hasUnresolvedConflicts = false,
  isLoading = false,
}) => {
  const [processingAction, setProcessingAction] = React.useState<'continue' | 'abort' | null>(null);

  // Only show banner if we have actual in-progress operation data
  const hasMergeInProgress = mergeInProgress && mergeInProgress.head;
  const hasRebaseInProgress = rebaseInProgress && (rebaseInProgress.headName || rebaseInProgress.onto);
  const operation = hasMergeInProgress ? 'merge' : hasRebaseInProgress ? 'rebase' : null;
  
  if (!operation) {
    return null;
  }

  const handleContinue = async () => {
    setProcessingAction('continue');
    try {
      await onContinue();
    } finally {
      setProcessingAction(null);
    }
  };

  const handleAbort = async () => {
    setProcessingAction('abort');
    try {
      await onAbort();
    } finally {
      setProcessingAction(null);
    }
  };

  const isProcessing = processingAction !== null;

  const operationLabel = operation === 'merge' ? 'Merge' : 'Rebase';
  const OperationIcon = operation === 'merge' ? RiGitMergeLine : RiGitBranchLine;

  // Build description
  let description = '';
  if (mergeInProgress) {
    description = mergeInProgress.message 
      ? `Merging: ${mergeInProgress.message}` 
      : `Merge in progress (${mergeInProgress.head})`;
  } else if (rebaseInProgress) {
    description = rebaseInProgress.headName 
      ? `Rebasing ${rebaseInProgress.headName} onto ${rebaseInProgress.onto}` 
      : `Rebase in progress`;
  }

  return (
    <div className="bg-[var(--status-warning-bg)] border border-[var(--status-warning)] rounded-lg p-3 mx-3 mt-3">
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2 min-w-0">
          <OperationIcon className="size-4 text-[var(--status-warning)] shrink-0" />
          <div className="min-w-0">
            <p className="typography-label text-[var(--status-warning)]">
              {operationLabel} in Progress
            </p>
            {description && (
              <p className="typography-micro text-muted-foreground truncate">
                {description}
              </p>
            )}
          </div>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          {hasUnresolvedConflicts && onResolveWithAI && (
            <Button
              variant="outline"
              size="sm"
              onClick={onResolveWithAI}
              disabled={isProcessing || isLoading}
              className="gap-1.5"
            >
              <RiSparklingLine className="size-4" />
              Resolve with AI
            </Button>
          )}

          {processingAction !== 'continue' && (
            <Button
              variant="ghost"
              size="sm"
              onClick={handleAbort}
              disabled={isProcessing || isLoading}
              className="gap-1.5"
            >
              {processingAction === 'abort' ? (
                <RiLoader4Line className="size-4 animate-spin" />
              ) : (
                <RiCloseLine className="size-4" />
              )}
              Abort
            </Button>
          )}

          {!hasUnresolvedConflicts && (
            <Button
              variant="default"
              size="sm"
              onClick={handleContinue}
              disabled={isProcessing || isLoading}
              className="gap-1.5"
            >
              {processingAction === 'continue' ? (
                <RiLoader4Line className="size-4 animate-spin" />
              ) : (
                <RiCheckLine className="size-4" />
              )}
              Continue
            </Button>
          )}
        </div>
      </div>

      {hasUnresolvedConflicts && (
        <p className="typography-micro text-[var(--status-warning)] mt-2">
          Conflicts must be resolved before continuing. Use &quot;Resolve with AI&quot; or resolve manually, then stage changes and click Continue.
        </p>
      )}
    </div>
  );
};
