// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)

import { useEffect, useRef } from 'react';
import { Hand, X as XIcon, Globe, Clock, MessageSquare } from 'lucide-react';
import { useTranslation } from '@/i18n/TranslationProvider';
import type { ConversationDetail as ConvDetail } from '../lib/types';
import { MessageBubble } from './MessageBubble';
import { StatusBadge } from './StatusBadge';
import { Composer } from './Composer';
import { RequestContactButton } from './RequestContactButton';

interface ConversationDetailProps {
  conversation: ConvDetail;
  onIntercept: () => void;
  onRelease: () => void;
  onSendOperatorMessage: (content: string) => void;
}

function formatRelative(date: Date | string, locale: string): string {
  const d = typeof date === 'string' ? new Date(date) : date;
  const diffMs = Date.now() - d.getTime();
  const min = Math.floor(diffMs / 60_000);
  if (min < 1) return locale === 'de' ? 'gerade eben' : 'just now';
  if (min < 60) return locale === 'de' ? `vor ${min} Min.` : `${min} min ago`;
  const hours = Math.floor(min / 60);
  if (hours < 24) return locale === 'de' ? `vor ${hours} Std.` : `${hours} h ago`;
  return d.toLocaleDateString(locale);
}

export function ConversationDetail({ conversation, onIntercept, onRelease, onSendOperatorMessage }: ConversationDetailProps) {
  const { t, locale } = useTranslation();
  const transcriptEndRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    transcriptEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [conversation.messages.length]);

  const isIntercepted = conversation.status === 'intercepted';
  const isClosed = conversation.status === 'closed';
  const canIntercept = !isIntercepted && !isClosed;
  const composerHint = isIntercepted
    ? t('conversations.composer.interceptHint')
    : isClosed
      ? t('conversations.composer.closedHint')
      : t('conversations.composer.takeoverHint');

  return (
    <section className="flex-1 flex flex-col bg-white" data-testid={`conv-detail-${conversation.id}`}>
      <header className="border-b border-gray-200 px-6 py-4">
        <div className="flex items-start justify-between gap-3 mb-3">
          <div className="min-w-0">
            <div className="flex items-center gap-2 mb-1">
              <h2 className="text-lg font-semibold text-gray-900 truncate">{conversation.visitorRef}</h2>
              <StatusBadge status={conversation.status} />
              <span className="text-xs text-gray-400 uppercase">{conversation.visitorLocale}</span>
            </div>
            <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-500">
              <span className="inline-flex items-center gap-1">
                <Globe size={12} />
                <span className="truncate max-w-[280px]">{conversation.pageUrlLast}</span>
              </span>
              <span className="inline-flex items-center gap-1">
                <MessageSquare size={12} />
                {t('conversations.detail.messageCount', { count: conversation.messageCount })}
              </span>
              <span className="inline-flex items-center gap-1">
                <Clock size={12} />
                {t('conversations.detail.lastActivity', { ago: formatRelative(conversation.lastActivityAt, locale) })}
              </span>
            </div>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            {canIntercept && (
              <button
                type="button"
                onClick={onIntercept}
                data-testid="intercept-btn"
                className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-violet-600 hover:bg-violet-700 text-white text-sm font-medium rounded-md"
              >
                <Hand size={14} />
                {t('conversations.detail.takeOver')}
              </button>
            )}
            {isIntercepted && (
              <button
                type="button"
                onClick={onRelease}
                data-testid="release-btn"
                className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-white border border-violet-300 text-violet-700 hover:bg-violet-50 text-sm font-medium rounded-md"
              >
                <XIcon size={14} />
                {t('conversations.detail.release')}
              </button>
            )}
            <RequestContactButton
              conversationId={conversation.id}
              conversationStatus={conversation.status}
            />
          </div>
        </div>
      </header>

      <div className="flex-1 overflow-y-auto px-6 py-4 bg-slate-50/40 flex flex-col" data-testid="transcript">
        {conversation.messages.map((msg) => (
          <MessageBubble key={msg.id} message={msg} />
        ))}
        <div ref={transcriptEndRef} />
      </div>

      <Composer
        onSend={onSendOperatorMessage}
        disabled={isClosed}
        hint={composerHint}
      />
    </section>
  );
}
