import { useParams, useNavigate, Link } from 'react-router-dom'
import { ArrowRight, MessageSquare, User, Calendar, Clock, ExternalLink, AlertCircle, FileText, CalendarCheck } from 'lucide-react'
import { t } from '@/lib/i18n'
import { useLanguage } from '@/contexts/LanguageContext'
import { useConversation } from '@/hooks/useConversations'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { Badge } from '@/components/common/Badge'
import { PageLoading } from '@/components/common/Spinner'
import { formatDate, formatRelativeTime } from '@/utils/formatters'
import type { Message, SessionMessage, ConversationMeeting } from '@/types/conversation'

/**
 * Conversation Detail Page
 * Shows full conversation history with messages in chat-style layout
 */
function isSafeUrl(url: string): boolean {
  try {
    const parsed = new URL(url)
    return parsed.protocol === 'http:' || parsed.protocol === 'https:'
  } catch { return false }
}

export function ConversationDetail() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const { currentLanguage } = useLanguage()
  
  const { data, isLoading, error } = useConversation(id || '', currentLanguage)
  
  if (isLoading) {
    return <PageLoading />
  }
  
  if (error || !data?.data?.conversation) {
    return (
      <div className="text-center py-12">
        <AlertCircle className="w-12 h-12 mx-auto text-gray-300 mb-4" />
        <p className="text-gray-500 mb-4">{t('Conversation not found')}</p>
        <Button 
          variant="outline" 
          onClick={() => navigate('/conversations')}
        >
          <ArrowRight className="w-4 h-4 me-2" />
          {t('Back to Conversations List')}
        </Button>
      </div>
    )
  }
  
  const conversation = data.data.conversation
  const meetings: ConversationMeeting[] = data.data.meetings || []
  // Messages are stored in session_data (can be array or object with messages key)
  const rawMessages = conversation.session_data || data.data.messages || []
  const messages = Array.isArray(rawMessages) 
    ? rawMessages 
    : (rawMessages.messages || [])
  
  return (
    <div className="space-y-6 animate-fade-in">
      {/* Header */}
      <PageHeader
        title={`${t('Conversation')} #${conversation.id}`}
        subtitle={conversation.page_title || t('No title')}
      >
        <Button
          variant="outline"
          onClick={() => navigate('/conversations')}
        >
          <ArrowRight className="w-4 h-4 me-2" />
          {t('Back')}
        </Button>
      </PageHeader>
      
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Chat Messages - Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* AI Summary — shown above chat history */}
          {conversation.ai_summary && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FileText className="w-5 h-5 text-purple-600" />
                  {t('Conversation Summary (AI)')}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="bg-purple-50 rounded-lg border border-purple-200 p-4">
                  <p className="text-sm text-purple-900 whitespace-pre-line leading-relaxed">
                    {conversation.ai_summary}
                  </p>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Meetings booked from this conversation */}
          {meetings.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <CalendarCheck className="w-5 h-5 text-green-600" />
                  {t('Meetings scheduled from this conversation')}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {meetings.map((m) => (
                    <Link
                      key={m.id}
                      to="/meetings"
                      className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-200 hover:bg-green-100 transition-colors"
                    >
                      <div className="flex items-center gap-3">
                        <Calendar className="w-4 h-4 text-green-600" />
                        <div>
                          <p className="text-sm font-medium text-gray-900">{m.title}</p>
                          <p className="text-xs text-gray-500">
                            {m.meeting_date} · {m.start_time} - {m.end_time}
                          </p>
                        </div>
                      </div>
                      <Badge variant={m.status === 'scheduled' ? 'primary' : m.status === 'cancelled' ? 'danger' : 'default'}>
                        {m.status === 'scheduled' ? t('Scheduled') : m.status === 'confirmed' ? t('Confirmed') : m.status === 'cancelled' ? t('Cancelled') : m.status === 'completed' ? t('Completed') : m.status}
                      </Badge>
                    </Link>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Chat History */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2">
                <MessageSquare className="w-5 h-5" />
                {t('Conversation History')}
              </CardTitle>
              <Badge variant="info">
                {messages.length} {t('messages')}
              </Badge>
            </CardHeader>
            <CardContent>
              {messages.length === 0 ? (
                <p className="text-gray-500 text-center py-8">
                  {t('No messages in this conversation')}
                </p>
              ) : (
                <div className="space-y-4 max-h-[500px] overflow-y-auto p-2">
                  {messages.map((message: Message | SessionMessage, index: number) => (
                    <MessageBubble 
                      key={'id' in message ? message.id : index} 
                      message={message}
                    />
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
        
        {/* Sidebar - Conversation Info */}
        <div className="space-y-6">
          {/* Conversation Stats */}
          <Card>
            <CardHeader>
              <CardTitle>{t('Conversation Details')}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <InfoRow 
                icon={Calendar}
                label={t('Started')}
                value={formatDate(conversation.started_at)}
              />
              <InfoRow 
                icon={Clock}
                label={t('Last Message')}
                value={conversation.last_message_at 
                  ? formatRelativeTime(conversation.last_message_at)
                  : t('Not available')}
              />
              <InfoRow 
                icon={MessageSquare}
                label={t('Total Messages')}
                value={`${conversation.messages_count || messages.length}`}
              />
              {conversation.page_url && (
                <InfoRow 
                  icon={ExternalLink}
                  label={t('Source Page')}
                  value={
                    isSafeUrl(conversation.page_url) ? (
                      <a 
                        href={conversation.page_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-primary-600 hover:underline truncate block max-w-[200px]"
                      >
                        {(() => {
                          try {
                            return new URL(conversation.page_url).pathname
                          } catch {
                            return conversation.page_url
                          }
                        })()}
                      </a>
                    ) : (
                      <span className="text-gray-500 truncate block max-w-[200px]">{conversation.page_url}</span>
                    )
                  }
                />
              )}
              <div className="pt-2 border-t">
                <Badge 
                  variant={conversation.status === 'active' ? 'primary' : 'default'}
                  className="w-full justify-center"
                >
                  {conversation.status === 'active' ? t('Active Conversation') : 
                   conversation.status === 'closed' ? t('Closed') : t('Archived')}
                </Badge>
              </div>
            </CardContent>
          </Card>
          
          {/* Associated Lead */}
          {conversation.is_lead && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <User className="w-5 h-5" />
                  {t('Associated Lead')}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-gray-600 mb-3">
                  {t('Conversation linked to a lead')}
                </p>
                <Link to="/leads">
                  <Button variant="outline" size="sm" className="w-full">
                    {t('View Leads')}
                  </Button>
                </Link>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  )
}

/**
 * Message Bubble Component
 * Supports both Message type (from API) and SessionMessage format (from DB)
 */
function MessageBubble({ message }: { message: Message | SessionMessage }) {
  const isBot = message.role === 'bot' || message.role === 'assistant' || message.role === 'system'
  // Support both created_at (API) and timestamp (session_data)
  const messageTime = ('created_at' in message && message.created_at) 
    ? message.created_at 
    : ('timestamp' in message && message.timestamp)
      ? message.timestamp
      : null
  
  return (
    <div className={`flex ${isBot ? 'justify-start' : 'justify-end'}`}>
      <div className={`max-w-[80%] rounded-2xl px-4 py-3 ${
        isBot 
          ? 'bg-gray-100 text-gray-900 rounded-tl-sm' 
          : 'bg-primary-600 text-white rounded-tr-sm'
      }`}>
        <p className="whitespace-pre-wrap text-sm">
          {message.content}
        </p>
        {messageTime && (
          <p className={`text-xs mt-1 ${
            isBot ? 'text-gray-500' : 'text-white/70'
          }`}>
            {formatRelativeTime(messageTime)}
          </p>
        )}
      </div>
    </div>
  )
}

/**
 * Info Row Component for sidebar
 */
function InfoRow({ 
  icon: Icon, 
  label, 
  value 
}: { 
  icon: React.ComponentType<{ className?: string }>
  label: string
  value: React.ReactNode 
}) {
  return (
    <div className="flex items-start gap-3">
      <Icon className="w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" />
      <div className="flex-1 min-w-0">
        <p className="text-xs text-gray-500">{label}</p>
        <div className="text-sm text-gray-900">{value}</div>
      </div>
    </div>
  )
}

