'use client';

import { useState } from 'react';
import { Check, ChevronDown, Copy, RefreshCw, ThumbsDown, ThumbsUp } from 'lucide-react';
import { MarkdownResponse } from '../../components/MarkdownResponse';
import type { Message } from '../../lib/types';

interface MessageBubbleProps {
  message: Message;
  isStreaming?: boolean;
  streamTokens?: number;
  streamTokPerSec?: number;
  onRegenerate?: (messageId: string, model?: string) => void;
  onRate?: (messageId: string, rating: 'up' | 'down') => void;
  models?: string[];
}

export function MessageBubble({
  message,
  isStreaming,
  streamTokens,
  streamTokPerSec,
  onRegenerate,
  onRate,
  models = [],
}: MessageBubbleProps) {
  const user = message.role === 'user';
  const [copied, setCopied] = useState(false);
  const [showRegenModels, setShowRegenModels] = useState(false);
  const [rating, setRating] = useState<'up' | 'down' | undefined>(message.rating);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(message.content);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handleRate = (r: 'up' | 'down') => {
    setRating(r);
    onRate?.(message.id, r);
  };

  return (
    <div className={`group flex ${user ? 'justify-end' : 'justify-start'}`}>
      <div
        className="relative max-w-[85%] rounded-lg border border-white/10 px-3 py-2"
        style={{
          background: user ? 'rgba(90, 140, 255, 0.2)' : 'var(--surface-card)',
          color: 'var(--text-primary)',
        }}
      >
        {!user && message.model ? (
          <div className="mb-1 text-[10px] text-[var(--text-tertiary)]">{message.model}</div>
        ) : null}
        {user ? (
          <p className="whitespace-pre-wrap text-sm">{message.content}</p>
        ) : (
          <MarkdownResponse
            content={message.content}
            isThinkModel={false}
            streaming={isStreaming}
          />
        )}

        {/* E4: Live streaming metrics */}
        {isStreaming && typeof streamTokens === 'number' && streamTokens > 0 && (
          <div className="mt-1 text-[10px] text-[var(--accent-secondary)]">
            {streamTokens} tokens · {(streamTokPerSec ?? 0).toFixed(1)} tok/s
          </div>
        )}

        {/* Completed assistant metrics */}
        {!user && !isStreaming && message.metrics ? (
          <div className="mt-1 text-[10px] text-[var(--text-tertiary)]">
            {message.metrics.totalTokens} tokens · {message.metrics.tokensPerSec.toFixed(1)} tok/s ·{' '}
            {(message.metrics.durationMs / 1000).toFixed(1)}s
          </div>
        ) : null}

        {/* E1: Action bar on hover for assistant messages */}
        {!user && !isStreaming && (
          <div className="mt-1 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">
            <button
              type="button"
              onClick={() => void handleCopy()}
              className="inline-flex h-6 w-6 items-center justify-center rounded text-[var(--text-tertiary)] hover:bg-white/10 hover:text-[var(--text-primary)]"
              title="Copy"
            >
              {copied ? <Check size={12} /> : <Copy size={12} />}
            </button>

            {/* E3: Regenerate / try with other model */}
            <div className="relative">
              <button
                type="button"
                onClick={() => setShowRegenModels(p => !p)}
                className="inline-flex h-6 items-center gap-0.5 rounded px-1 text-[var(--text-tertiary)] hover:bg-white/10 hover:text-[var(--text-primary)]"
                title="Regenerate"
              >
                <RefreshCw size={12} />
                <ChevronDown size={10} />
              </button>
              {showRegenModels && (
                <div className="absolute bottom-7 left-0 z-30 max-h-48 w-52 overflow-auto rounded border border-white/10 bg-[var(--surface-card)] p-1 shadow-lg">
                  <button
                    type="button"
                    onClick={() => {
                      setShowRegenModels(false);
                      onRegenerate?.(message.id);
                    }}
                    className="block w-full rounded px-2 py-1 text-left text-[11px] text-[var(--accent-secondary)] hover:bg-white/5"
                  >
                    Regenerate (same model)
                  </button>
                  {models.map(m => (
                    <button
                      key={m}
                      type="button"
                      onClick={() => {
                        setShowRegenModels(false);
                        onRegenerate?.(message.id, m);
                      }}
                      className="block w-full rounded px-2 py-1 text-left text-[11px] text-[var(--text-secondary)] hover:bg-white/5"
                    >
                      Try with {m}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* E5: Rating buttons */}
            <button
              type="button"
              onClick={() => handleRate('up')}
              className={`inline-flex h-6 w-6 items-center justify-center rounded hover:bg-white/10 ${rating === 'up' ? 'text-[var(--success)]' : 'text-[var(--text-tertiary)] hover:text-[var(--text-primary)]'}`}
              title="Good response"
            >
              <ThumbsUp size={12} />
            </button>
            <button
              type="button"
              onClick={() => handleRate('down')}
              className={`inline-flex h-6 w-6 items-center justify-center rounded hover:bg-white/10 ${rating === 'down' ? 'text-[var(--danger)]' : 'text-[var(--text-tertiary)] hover:text-[var(--text-primary)]'}`}
              title="Bad response"
            >
              <ThumbsDown size={12} />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
