'use client';

import { useState } from 'react';
import { Phone, MessageSquare, Clock, ChevronRight, Zap } from 'lucide-react';
import StatusBadge from '@client/components/ui/StatusBadge';
import Link from 'next/link';
import type { Conversation } from '@client/api/conversations';
import { useLanguage } from '@client/contexts/LanguageContext';

const getConfidenceColor = (score: number) => {
  if (score >= 90) return 'hsl(var(--success))';
  if (score >= 70) return 'hsl(var(--warning))';
  return 'hsl(var(--danger))';
};

interface ActiveConversationsFeedProps {
  conversations: Conversation[];
  loading: boolean;
}

export default function ActiveConversationsFeed({ conversations, loading }: ActiveConversationsFeedProps) {
  const { t } = useLanguage();
  const [filter, setFilter] = useState<'all' | 'active' | 'escalated'>('all');

  const filtered = conversations.filter(c => {
    if (filter === 'all') return true;
    if (filter === 'active') return c.status === 'ai';
    if (filter === 'escalated') return c.status === 'human';
    return true;
  });

  return (
    <div className="card p-5" style={{ height: '100%' }}>
      <div className="flex items-center justify-between mb-4">
        <div>
          <p className="section-label">{t('dashboard.conversationFeed', 'Conversation Feed')}</p>
          <p className="text-sm font-semibold mt-0.5" style={{ color: 'hsl(var(--foreground))' }}>{t('dashboard.recentAiSessions', 'Recent AI Sessions')}</p>
        </div>
        <div className="flex items-center gap-1 p-0.5 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
          {(['all', 'active', 'escalated'] as const).map(f => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1 rounded-md text-xs font-semibold transition-all duration-150 capitalize ${filter === f ? 'bg-white text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
              style={filter === f ? { color: 'hsl(var(--foreground))' } : { color: 'hsl(var(--muted-foreground))' }}
            >
              {t(`dashboard.filter.${f}`, f)}
            </button>
          ))}
        </div>
      </div>

      <div className="space-y-2 overflow-y-auto" style={{ maxHeight: '420px' }}>
        {loading ? (
          Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="flex items-start gap-3 p-3 rounded-xl animate-pulse" style={{ border: '1px solid hsl(var(--border))' }}>
              <div className="w-8 h-8 rounded-lg bg-gray-200" />
              <div className="flex-1">
                <div className="h-4 w-32 bg-gray-200 rounded mb-2" />
                <div className="h-3 w-48 bg-gray-200 rounded" />
              </div>
            </div>
          ))
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-10 text-center">
            <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('dashboard.noConversations', 'No conversations')}</p>
            <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {filter === 'all' ? t('dashboard.noConversationsYet', 'No conversations yet') : t('dashboard.noFilteredConversations', `No ${filter} conversations`, { filter })}
            </p>
          </div>
        ) : (
          filtered.map(conv => {
            const lastMsg = conv.messages?.[conv.messages.length - 1];
            const topic = lastMsg?.text ?? '';
            const confidence = conv.aiConfidence ?? lastMsg?.confidence ?? null;
            const custName = conv.customerName;
            const startTime = new Date(conv.createdAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });

            return (
              <Link
                key={conv.id}
                href={`/conversations/${conv.id}`}
                className="flex items-start gap-3 p-3 rounded-xl cursor-pointer transition-all duration-150 table-row-hover group"
                style={{ border: '1px solid hsl(var(--border))' }}
              >
                <div className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0 mt-0.5" style={{ backgroundColor: conv.channel === 'voice' ? 'hsl(var(--primary-light))' : 'hsl(var(--info-bg))', color: conv.channel === 'voice' ? 'hsl(var(--primary))' : 'hsl(var(--info))' }}>
                  {conv.channel === 'voice' ? <Phone size={14} /> : <MessageSquare size={14} />}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2 min-w-0">
                      <p className="text-sm font-semibold truncate" style={{ color: 'hsl(var(--foreground))' }}>{custName}</p>
                    </div>
                    <StatusBadge status={conv.status} size="sm" />
                  </div>
                  {topic && <p className="text-xs mt-0.5 truncate" style={{ color: 'hsl(var(--foreground-secondary))' }}>{topic}</p>}
                  <div className="flex items-center gap-3 mt-1.5">
                    <div className="flex items-center gap-1 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      <Clock size={11} />
                      <span className="font-mono">{startTime}</span>
                    </div>
                    {confidence != null && (
                      <div className="flex items-center gap-1 text-xs">
                        <Zap size={11} style={{ color: getConfidenceColor(confidence) }} />
                        <span className="font-mono tabular-nums font-semibold" style={{ color: getConfidenceColor(confidence) }}>{confidence}%</span>
                      </div>
                    )}
                  </div>
                </div>
                <ChevronRight size={14} className="shrink-0 mt-1 opacity-0 group-hover:opacity-100 transition-opacity" style={{ color: 'hsl(var(--muted-foreground))' }} />
              </Link>
            );
          })
        )}
      </div>
    </div>
  );
}
