import { useCallback, useEffect, useRef } from 'react';
import { Loader2 } from 'lucide-react';
import { MarkdownRenderer } from './MarkdownRenderer';
import { cn } from '@/lib/utils';

export interface CompareResponse {
  model: string;
  assistantMessageId: string;
  content: string;
  status: 'streaming' | 'complete' | 'error';
}

interface Props {
  models: string[];
  responses: CompareResponse[];
  onClose: () => void;
}

export function ComparePane({ models, responses, onClose }: Props) {
  const panelsRef = useRef<(HTMLDivElement | null)[]>([]);
  const isSyncingRef = useRef(false);

  const responseMap = new Map<string, CompareResponse>();
  for (const r of responses) {
    responseMap.set(r.model, r);
  }

  // Synced scroll: when one panel scrolls, scroll all others to the same ratio
  const handleScroll = useCallback((sourceIndex: number) => {
    if (isSyncingRef.current) return;
    const source = panelsRef.current[sourceIndex];
    if (!source) return;
    const ratio = source.scrollTop / (source.scrollHeight - source.clientHeight);
    isSyncingRef.current = true;
    for (let i = 0; i < panelsRef.current.length; i++) {
      if (i === sourceIndex) continue;
      const target = panelsRef.current[i];
      if (!target) continue;
      const targetMax = target.scrollHeight - target.clientHeight;
      target.scrollTop = targetMax > 0 ? ratio * targetMax : 0;
    }
    isSyncingRef.current = false;
  }, []);

  // Refresh scroll sync when content changes (streaming updates)
  useEffect(() => {
    if (responses.length === 0) return;
    const anyStreaming = responses.some((r) => r.status === 'streaming');
    if (!anyStreaming) return;
    // Sync scroll to bottom when any panel is still streaming
    if (!isSyncingRef.current) {
      for (const panel of panelsRef.current) {
        if (!panel) continue;
        panel.scrollTop = panel.scrollHeight;
      }
    }
  }, [responses]);

  const gridCols = models.length === 2 ? 'grid-cols-2' : 'grid-cols-3';

  return (
    <div className="flex flex-col h-full min-h-0 relative">
      {/* Header */}
      <div className="flex items-center gap-2 border-b border-border bg-muted/20 px-3 py-2 shrink-0">
        <span className="text-sm font-medium">Compare Models</span>
        <span className="text-xs text-muted-foreground">
          {models.length} models
        </span>
        <div className="ml-auto flex items-center gap-1 shrink-0">
          <button
            type="button"
            onClick={onClose}
            className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted"
          >
            Back to single
          </button>
        </div>
      </div>

      {/* Grid of response panels */}
      <div className={cn('flex-1 grid min-h-0', gridCols)}>
        {models.map((model, idx) => {
          const resp = responseMap.get(model) ?? {
            model,
            assistantMessageId: '',
            content: '',
            status: 'streaming' as const,
          };
          const isStreaming = resp.status === 'streaming';
          const isError = resp.status === 'error';

          return (
            <div
              key={model}
              ref={(el) => { panelsRef.current[idx] = el; }}
              onScroll={() => handleScroll(idx)}
              className={cn(
                'overflow-y-auto border-r border-border/50 last:border-r-0',
                'flex flex-col',
              )}
            >
              {/* Model header */}
              <div className="sticky top-0 z-10 bg-background/95 backdrop-blur border-b border-border/50 px-3 py-2 text-xs font-medium text-foreground truncate">
                {model}
              </div>

              {/* Empty / loading state */}
              {resp.content.length === 0 && isStreaming && (
                <div className="flex items-center justify-center flex-1 gap-2 text-sm text-muted-foreground">
                  <Loader2 size={14} className="animate-spin" />
                  Generating…
                </div>
              )}

              {/* Error state */}
              {isError && resp.content.length === 0 && (
                <div className="flex items-center justify-center flex-1 text-sm text-destructive px-3">
                  Failed to generate
                </div>
              )}

              {/* Content */}
              {resp.content.length > 0 && (
                <div className="px-3 py-2 text-sm">
                  <MarkdownRenderer content={resp.content} />
                </div>
              )}

              {/* Streaming indicator at bottom */}
              {isStreaming && resp.content.length > 0 && (
                <div className="sticky bottom-0 bg-background/80 backdrop-blur px-3 py-1.5 flex items-center gap-1.5 text-xs text-muted-foreground border-t border-border/30">
                  <Loader2 size={10} className="animate-spin" />
                  Streaming…
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
