import { useState } from 'react'
import { Link } from 'react-router-dom'
import { RefreshCw, MessageSquare, Eye, Trash2, User } from 'lucide-react'
import { useConversations, useDeleteConversation } from '@/hooks/useConversations'
import { PageHeader } from '@/components/layout/PageHeader'
import { Button } from '@/components/common/Button'
import { Badge } from '@/components/common/Badge'
import { PageLoading } from '@/components/common/Spinner'
import { EmptyState } from '@/components/common/EmptyState'
import { formatRelativeTime } from '@/utils/formatters'
import { useLanguage } from '@/contexts/LanguageContext'
import { t, sprintf } from '@/lib/i18n'

export function Conversations() {
  const { currentLanguage } = useLanguage()
  const [page, setPage] = useState(1)
  
  const { data, isLoading, isFetching, refetch } = useConversations(page, 20, currentLanguage)
  const deleteConversation = useDeleteConversation()
  
  const handleDelete = (id: string) => {
    if (confirm(t('Are you sure you want to delete this conversation?'))) {
      deleteConversation.mutate(id)
    }
  }
  
  if (isLoading) {
    return <PageLoading />
  }
  
  const conversations = data?.data?.conversations || []
  const pagination = data?.data?.pagination
  
  return (
    <div className="space-y-6 animate-fade-in" data-wizard-id="conversations-content">
      <PageHeader 
        title={t('Conversations')}
        subtitle={sprintf(t('Total %d conversations'), pagination?.total ?? 0)}
      >
        <Button
          variant="outline"
          onClick={() => refetch()}
          disabled={isFetching}
        >
          <RefreshCw className={`w-4 h-4 me-2 ${isFetching ? 'animate-spin' : ''}`} />
          {t('Refresh')}
        </Button>
      </PageHeader>
      
      {conversations.length === 0 ? (
        <EmptyState
          icon={MessageSquare}
          title={t('No Conversations')}
          description={t('No conversations yet. New conversations will appear here.')}
        />
      ) : (
        <div className="bg-white rounded-xl shadow-card border border-gray-100 overflow-hidden">
          <ul className="divide-y divide-gray-200">
            {conversations.map((conversation) => (
              <li key={conversation.id} className="hover:bg-gray-50 transition-colors">
                <div className="flex items-center gap-4 p-4">
                  {/* Avatar */}
                  <div className="w-12 h-12 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0">
                    {conversation.is_lead ? (
                      <User className="w-6 h-6 text-primary-600" />
                    ) : (
                      <MessageSquare className="w-6 h-6 text-primary-600" />
                    )}
                  </div>
                  
                  {/* Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="font-medium text-gray-900 truncate">
                        {conversation.conversation_title || conversation.page_title || t('Conversation')}
                      </p>
                      {conversation.is_lead && (
                        <Badge variant="success" size="sm">{t('Lead')}</Badge>
                      )}
                      <Badge 
                        variant={conversation.status === 'active' ? 'primary' : 'default'}
                        size="sm"
                      >
                        {conversation.status === 'active' ? t('Active') : 
                         conversation.status === 'closed' ? t('Closed') : t('Archived')}
                      </Badge>
                    </div>
                    <p className="text-sm text-gray-500 truncate">
                      {conversation.source_label || conversation.page_url || t('No source')}
                    </p>
                  </div>
                  
                  {/* Stats */}
                  <div className="text-end flex-shrink-0">
                    <p className="text-sm font-medium text-gray-900">
                      {conversation.messages_count} {t('messages')}
                    </p>
                    <p className="text-xs text-gray-500">
                      {formatRelativeTime(conversation.last_message_at || conversation.started_at)}
                    </p>
                  </div>
                  
                  {/* Actions */}
                  <div className="flex gap-2 flex-shrink-0">
                    <Link
                      to={`/conversations/${conversation.id}`}
                      className="p-2 text-gray-400 hover:text-primary-600 transition-colors"
                      title={t('View')}
                    >
                      <Eye className="w-4 h-4" />
                    </Link>
                    <button
                      onClick={() => handleDelete(conversation.id)}
                      className="p-2 text-gray-400 hover:text-red-600 transition-colors"
                      title={t('Delete')}
                      disabled={deleteConversation.isPending}
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </li>
            ))}
          </ul>
          
          {/* Pagination */}
          {pagination && pagination.total_pages > 1 && (
            <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
              <p className="text-sm text-gray-500">
                {sprintf(t('Page %d of %d'), page, pagination.total_pages)}
              </p>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page === 1}
                  onClick={() => setPage(p => p - 1)}
                >
                  {t('Previous')}
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page === pagination.total_pages}
                  onClick={() => setPage(p => p + 1)}
                >
                  {t('Next')}
                </Button>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

