import { useState, useEffect, useRef, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ArrowLeft, Phone, Clock, Calendar, X, Play, Pause, Volume2, RefreshCw, User, ShoppingCart, Package, AlertCircle, CheckCircle, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { supabase } from "@/lib/supabase";
import { API_URL, ENABLE_MANUAL_ANALYTICS } from "@/lib/config";
import ReactMarkdown from 'react-markdown';
import { AnalyticsStatus, ANALYTICS_STATUS, RelatedCustomer, RelatedOrder, RelatedProduct } from "@/types/database.types";
import { RealtimeChannel } from "@supabase/supabase-js";

interface CallLog {
  id: string;
  store_id: string;
  created_at: string;
  started_at: string | null;
  ended_at: string | null;
  duration: number | null;
  caller: string | null;
  transcript: string | null;
  recording_url: string | null;
  costs: any | null;
  cost_total: number | null;
  payload: any;
  outcome: string | null;
  summary: string | null;
  satisfaction_score: number | null;
  related_customers: RelatedCustomer[] | null;
  related_orders: RelatedOrder[] | null;
  related_products: RelatedProduct[] | null;
  analytics_status: AnalyticsStatus | null;
  analytics_error: string | null;
}

// Helper function to get satisfaction emoji and color based on score
const getSatisfactionDisplay = (score: number | null): { emoji: string; label: string; color: string } => {
  if (score === null) return { emoji: '❓', label: 'Unknown', color: 'text-slate-400' };

  if (score >= 81) return { emoji: '😍', label: 'Very Satisfied', color: 'text-green-400' };
  if (score >= 61) return { emoji: '😊', label: 'Satisfied', color: 'text-lime-400' };
  if (score >= 41) return { emoji: '😐', label: 'Neutral', color: 'text-yellow-400' };
  if (score >= 21) return { emoji: '😞', label: 'Dissatisfied', color: 'text-orange-400' };
  return { emoji: '😠', label: 'Very Dissatisfied', color: 'text-red-400' };
};

const formatDuration = (seconds: number | null): string => {
  if (!seconds) return "-";
  const mins = Math.floor(seconds / 60);
  const secs = Math.round(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, '0')}`;
};

const getRelativeTime = (dateStr: string | null, t: (key: string, options?: any) => string): string => {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMins / 60);
  const diffDays = Math.floor(diffHours / 24);

  if (diffMins < 1) return t('common.justNow');
  if (diffMins < 60) return t('common.minsAgo', { count: diffMins });
  if (diffHours < 24) return t('common.hoursAgo', { count: diffHours });
  return t('common.daysAgo', { count: diffDays });
};

const getOutcomeColor = (outcome: string | null): string => {
  if (!outcome) return "bg-slate-600";

  const colorMap: Record<string, string> = {
    resolved: "bg-green-600",
    order_placed: "bg-green-600",
    order_inquiry: "bg-blue-600",
    product_inquiry: "bg-blue-600",
    general_question: "bg-blue-600",
    complaint: "bg-red-600",
    return_request: "bg-orange-600",
    callback_requested: "bg-purple-600",
    escalated: "bg-yellow-600",
    no_answer: "bg-slate-500",
    voicemail: "bg-slate-500",
    wrong_number: "bg-slate-500",
    abandoned: "bg-slate-500",
  };

  return colorMap[outcome] || "bg-slate-600";
};

const formatOutcome = (outcome: string | null): string => {
  if (!outcome) return "-";
  return outcome.split('_').map(word =>
    word.charAt(0).toUpperCase() + word.slice(1)
  ).join(' ');
};

const formatTranscript = (transcript: string | null): React.ReactNode => {
  if (!transcript) return null;

  // Split by newlines and process each line
  const lines = transcript.split('\n').filter(line => line.trim());

  return lines.map((line, index) => {
    // Remove AI:, User:, Assistant:, Customer: prefixes (case insensitive)
    let cleanLine = line.replace(/^(AI|User|Assistant|Customer|Bot|Agent):\s*/i, '').trim();

    // Determine if this was an AI/assistant line or user/customer line
    const isAI = /^(AI|Assistant|Bot|Agent):/i.test(line);
    const isUser = /^(User|Customer):/i.test(line);

    // Add emoji based on speaker
    let emoji = '';
    if (isAI) {
      emoji = '🤖 ';
    } else if (isUser) {
      emoji = '👤 ';
    }

    return (
      <p key={index} className={`text-slate-300 text-sm ${index > 0 ? 'mt-2' : ''}`}>
        {emoji}{cleanLine}
      </p>
    );
  });
};

export function CallLogDetailContent() {
  const { t } = useTranslation();
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [callLog, setCallLog] = useState<CallLog | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [isAnalyticsTriggering, setIsAnalyticsTriggering] = useState(false);
  const [isRealtimeConnected, setIsRealtimeConnected] = useState(false);
  const audioRef = useRef<HTMLAudioElement>(null);
  const channelRef = useRef<RealtimeChannel | null>(null);

  const handleTriggerAnalytics = async () => {
    if (!id || !callLog) return;

    setIsAnalyticsTriggering(true);
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        throw new Error('Not authenticated');
      }

      const response = await fetch(`${API_URL}/api/call-logs/${id}/trigger-analytics`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${session.access_token}`,
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to trigger analytics');
      }

      // Update local state to show running status
      // Realtime subscription will handle further updates automatically
      setCallLog({
        ...callLog,
        analytics_status: ANALYTICS_STATUS.RUNNING,
        analytics_error: null,
      });

    } catch (err) {
      console.error('Failed to trigger analytics:', err);
      setCallLog({
        ...callLog,
        analytics_status: ANALYTICS_STATUS.FAILED,
        analytics_error: err instanceof Error ? err.message : 'Failed to trigger analytics',
      });
    } finally {
      setIsAnalyticsTriggering(false);
    }
  };

  // Handle realtime updates for this call log
  const handleRealtimeUpdate = useCallback((payload: { eventType: string; new: CallLog }) => {
    console.log('[Realtime] Call log updated:', payload.eventType);
    if (payload.eventType === 'UPDATE' && payload.new) {
      setCallLog(payload.new);
    }
  }, []);

  // Setup realtime subscription for this specific call log
  const setupRealtimeSubscription = useCallback((callLogId: string) => {
    // Clean up existing subscription
    if (channelRef.current) {
      supabase.removeChannel(channelRef.current);
      channelRef.current = null;
    }

    console.log('[Realtime] Setting up subscription for call log:', callLogId);

    const channel = supabase
      .channel(`call_log_detail_${callLogId}`)
      .on(
        'postgres_changes',
        {
          event: 'UPDATE',
          schema: 'public',
          table: 'call_logs',
          filter: `id=eq.${callLogId}`
        },
        (payload) => {
          handleRealtimeUpdate(payload as { eventType: string; new: CallLog });
        }
      )
      .subscribe((status) => {
        console.log('[Realtime] Detail subscription status:', status);
        setIsRealtimeConnected(status === 'SUBSCRIBED');
      });

    channelRef.current = channel;
  }, [handleRealtimeUpdate]);

  useEffect(() => {
    const fetchCallLog = async () => {
      if (!id) return;

      setIsLoading(true);
      setError(null);

      try {
        const { data: { session } } = await supabase.auth.getSession();
        if (!session) {
          throw new Error('Not authenticated');
        }

        const response = await fetch(`${API_URL}/api/call-logs/${id}`, {
          headers: {
            'Authorization': `Bearer ${session.access_token}`,
            'Content-Type': 'application/json',
          },
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || 'Failed to fetch call log');
        }

        const data = await response.json();
        setCallLog(data.call_log);

        // Setup realtime subscription after initial fetch
        setupRealtimeSubscription(id);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setIsLoading(false);
      }
    };

    fetchCallLog();

    // Cleanup on unmount
    return () => {
      if (channelRef.current) {
        console.log('[Realtime] Cleaning up detail subscription');
        supabase.removeChannel(channelRef.current);
        channelRef.current = null;
      }
    };
  }, [id, setupRealtimeSubscription]);

  const handleBack = () => {
    navigate('/call-logs');
  };

  const togglePlayPause = () => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.pause();
      } else {
        audioRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  const handleAudioEnded = () => {
    setIsPlaying(false);
    setCurrentTime(0);
  };

  const handleTimeUpdate = () => {
    if (audioRef.current) {
      setCurrentTime(audioRef.current.currentTime);
    }
  };

  if (isLoading) {
    return (
      <div className="flex-1 bg-slate-900 text-white flex items-center justify-center">
        <div className="flex flex-col items-center">
          <div className="relative">
            <div className="w-12 h-12 border-4 border-slate-700 rounded-full"></div>
            <div className="w-12 h-12 border-4 border-white border-t-transparent rounded-full animate-spin absolute top-0"></div>
          </div>
          <p className="text-slate-400 mt-4 font-medium">{t('common.loading')}</p>
        </div>
      </div>
    );
  }

  if (error || !callLog) {
    return (
      <div className="flex-1 bg-slate-900 text-white flex items-center justify-center">
        <div className="flex flex-col items-center">
          <div className="w-16 h-16 bg-red-500/10 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-red-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="12" r="10"/>
              <line x1="12" y1="8" x2="12" y2="12"/>
              <line x1="12" y1="16" x2="12.01" y2="16"/>
            </svg>
          </div>
          <p className="text-red-500 font-medium mb-2">{t('callLogDetail.notFound')}</p>
          <Button
            className="bg-slate-700 hover:bg-slate-600 text-white mt-4"
            onClick={handleBack}
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            {t('callLogDetail.backToList')}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 bg-slate-900 text-white overflow-hidden flex flex-col">
      {/* Modal Header */}
      <div className="border-b border-slate-800 bg-slate-900 p-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <h1 className="text-xl font-semibold text-white">{t('callLogDetail.title')}</h1>
            {/* Realtime indicator */}
            <div className="flex items-center gap-1.5 px-2 py-1 rounded-full bg-slate-700/50" title={isRealtimeConnected ? t('callLogs.realtime.liveDescription') : t('callLogs.realtime.disconnectedDescription')}>
              <span className="relative flex h-2 w-2">
                {isRealtimeConnected && (
                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                )}
                <span className={`relative inline-flex rounded-full h-2 w-2 ${isRealtimeConnected ? 'bg-green-500' : 'bg-slate-500'}`}></span>
              </span>
              <span className="text-xs text-slate-400">
                {isRealtimeConnected ? t('callLogs.realtime.live') : t('callLogs.realtime.disconnected')}
              </span>
            </div>
          </div>
          <Button
            variant="ghost"
            size="sm"
            className="text-slate-400 hover:text-white"
            onClick={handleBack}
          >
            <X className="w-5 h-5" />
          </Button>
        </div>
      </div>

      {/* Content - Two Column Layout */}
      <div className="flex-1 overflow-y-auto p-6">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Left Column - Contact Information */}
          <Card className="bg-slate-800 border-slate-700 p-6">
            <div className="flex items-center gap-2 mb-6">
              <Phone className="w-5 h-5 text-slate-400" />
              <h3 className="text-lg font-semibold text-white">{t('callLogDetail.contactInfo')}</h3>
            </div>

            {/* Phone Number with Badge */}
            <div className="mb-4">
              <p className="text-slate-400 text-sm mb-1">{t('callLogDetail.caller')}</p>
              <div className="flex items-center gap-2">
                <span className="text-white font-medium">{callLog.caller || '-'}</span>
                {callLog.outcome && (
                  <span className={`px-2 py-0.5 rounded text-xs font-medium text-white ${getOutcomeColor(callLog.outcome)}`}>
                    {formatOutcome(callLog.outcome)}
                  </span>
                )}
              </div>
            </div>

            {/* Phone with icon */}
            <div className="flex items-center gap-2 mb-2">
              <Phone className="w-4 h-4 text-slate-400" />
              <span className="text-slate-300">{callLog.caller || '-'}</span>
            </div>

            {/* Added time */}
            <div className="flex items-center gap-2 mb-6">
              <Calendar className="w-4 h-4 text-slate-400" />
              <span className="text-slate-300">{getRelativeTime(callLog.created_at, t)}</span>
            </div>

            {/* Stats Grid - 2x3 */}
            <div className="grid grid-cols-2 gap-4 mb-6">
              {/* Total Calls */}
              <div className="bg-slate-700/50 rounded-lg p-4 text-center">
                <div className="text-2xl font-bold text-white">1</div>
                <div className="text-sm text-slate-400">{t('callLogDetail.totalCalls')}</div>
              </div>

              {/* Total Duration */}
              <div className="bg-slate-700/50 rounded-lg p-4 text-center">
                <div className="text-2xl font-bold text-white">{formatDuration(callLog.duration)}</div>
                <div className="text-sm text-slate-400">{t('callLogDetail.totalDuration')}</div>
              </div>

              {/* Total Cost */}
              <div className="bg-slate-700/50 rounded-lg p-4 text-center">
                <div className="text-2xl font-bold text-white">
                  {callLog.cost_total ? `$${callLog.cost_total.toFixed(2)}` : '-'}
                </div>
                <div className="text-sm text-slate-400">{t('callLogDetail.totalCost')}</div>
              </div>

              {/* Outcome in grid */}
              <div className="bg-slate-700/50 rounded-lg p-4 text-center">
                <div className="text-lg font-bold text-white">{formatOutcome(callLog.outcome)}</div>
                <div className="text-sm text-slate-400">{t('callLogDetail.callOutcome')}</div>
              </div>

              {/* Customer Satisfaction */}
              <div className="bg-slate-700/50 rounded-lg p-4 text-center col-span-2">
                {(() => {
                  const satisfaction = getSatisfactionDisplay(callLog.satisfaction_score);
                  return (
                    <>
                      <div className="flex items-center justify-center gap-2">
                        <span className="text-4xl">{satisfaction.emoji}</span>
                        <div className="text-left">
                          <div className={`text-2xl font-bold ${satisfaction.color}`}>
                            {callLog.satisfaction_score !== null ? `${callLog.satisfaction_score}%` : '-'}
                          </div>
                          <div className={`text-sm ${satisfaction.color}`}>{satisfaction.label}</div>
                        </div>
                      </div>
                      <div className="text-sm text-slate-400 mt-1">{t('callLogDetail.satisfaction')}</div>
                    </>
                  );
                })()}
              </div>
            </div>

            {/* Call Outcome Box */}
            <div className="bg-slate-700/50 rounded-lg p-4 text-center">
              <div className={`inline-block px-4 py-2 rounded-lg text-lg font-bold text-white ${getOutcomeColor(callLog.outcome)}`}>
                {formatOutcome(callLog.outcome)}
              </div>
              <div className="text-sm text-slate-400 mt-2">{t('callLogDetail.callOutcome')}</div>
            </div>
          </Card>

          {/* Right Column - Call History */}
          <Card className="bg-slate-800 border-slate-700 p-6">
            <div className="flex items-center gap-2 mb-6">
              <Calendar className="w-5 h-5 text-slate-400" />
              <h3 className="text-lg font-semibold text-white">{t('callLogDetail.callHistory')}</h3>
            </div>

            {/* Call Header */}
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4 text-slate-400" />
                <span className="text-slate-300">{getRelativeTime(callLog.started_at, t)}</span>
              </div>
              <div className="flex items-center gap-3">
                {callLog.outcome && (
                  <span className={`px-2 py-0.5 rounded text-xs font-medium text-white ${getOutcomeColor(callLog.outcome)}`}>
                    {formatOutcome(callLog.outcome)}
                  </span>
                )}
                <span className="text-slate-300 flex items-center gap-1">
                  <Clock className="w-4 h-4" />
                  {formatDuration(callLog.duration)}
                </span>
              </div>
            </div>

            {/* Transcript */}
            <div className="mb-6">
              <h4 className="text-white font-medium mb-2">{t('callLogDetail.transcript')}</h4>
              <div className="bg-slate-700/30 rounded-lg p-4 max-h-48 overflow-y-auto">
                {callLog.transcript ? (
                  formatTranscript(callLog.transcript)
                ) : (
                  <p className="text-slate-400 text-sm">{t('callLogDetail.noTranscript')}</p>
                )}
              </div>
            </div>

            {/* Summary */}
            <div className="mb-6">
              <h4 className="text-white font-medium mb-2">{t('callLogDetail.summary')}</h4>
              <div className="bg-teal-900/30 border border-teal-700/50 rounded-lg p-4">
                {callLog.summary ? (
                  <div className="text-slate-200 text-sm prose prose-sm prose-invert max-w-none prose-p:my-1 prose-ul:my-1 prose-li:my-0">
                    <ReactMarkdown>{callLog.summary}</ReactMarkdown>
                  </div>
                ) : (
                  <p className="text-slate-400 text-sm">-</p>
                )}
              </div>
            </div>

            {/* Call Outcome */}
            <div className="mb-6">
              <div className="flex items-center gap-2">
                <span className="text-slate-400">{t('callLogDetail.callOutcome')}:</span>
                <span className={`px-2 py-0.5 rounded text-sm font-medium text-white ${getOutcomeColor(callLog.outcome)}`}>
                  {formatOutcome(callLog.outcome)}
                </span>
              </div>
            </div>

            {/* Call Recording */}
            {callLog.recording_url && (
              <div className="mb-6">
                <h4 className="text-white font-medium mb-2">{t('callLogDetail.recording')}</h4>
                <div className="bg-slate-700/30 rounded-lg p-4">
                  <audio
                    ref={audioRef}
                    src={callLog.recording_url}
                    onEnded={handleAudioEnded}
                    onTimeUpdate={handleTimeUpdate}
                    className="hidden"
                  />
                  <div className="flex items-center gap-4">
                    <Button
                      onClick={togglePlayPause}
                      size="sm"
                      className="w-10 h-10 rounded-full bg-slate-600 hover:bg-slate-500 flex items-center justify-center p-0"
                    >
                      {isPlaying ? (
                        <Pause className="w-4 h-4" />
                      ) : (
                        <Play className="w-4 h-4 ml-0.5" />
                      )}
                    </Button>
                    <div className="flex-1">
                      <div className="flex items-center gap-2 text-sm text-slate-400">
                        <span>{formatDuration(Math.floor(currentTime))}</span>
                        <div className="flex-1 h-1 bg-slate-600 rounded-full overflow-hidden">
                          <div
                            className="h-full bg-cyan-500 transition-all"
                            style={{
                              width: callLog.duration
                                ? `${(currentTime / callLog.duration) * 100}%`
                                : '0%'
                            }}
                          />
                        </div>
                        <span>{formatDuration(callLog.duration)}</span>
                        <Volume2 className="w-4 h-4" />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Analytics Status Banner */}
            {callLog.analytics_status && callLog.analytics_status !== ANALYTICS_STATUS.COMPLETED && (
              <div className={`mb-6 p-4 rounded-lg flex items-center justify-between ${
                callLog.analytics_status === ANALYTICS_STATUS.RUNNING
                  ? 'bg-blue-900/30 border border-blue-700/50'
                  : callLog.analytics_status === ANALYTICS_STATUS.FAILED
                    ? 'bg-red-900/30 border border-red-700/50'
                    : 'bg-slate-700/30 border border-slate-600/50'
              }`}>
                <div className="flex items-center gap-3">
                  {callLog.analytics_status === ANALYTICS_STATUS.RUNNING && (
                    <>
                      <Loader2 className="w-5 h-5 text-blue-400 animate-spin" />
                      <span className="text-blue-300">{t('callLogs.analyticsStatus.running')}</span>
                    </>
                  )}
                  {callLog.analytics_status === ANALYTICS_STATUS.FAILED && (
                    <>
                      <AlertCircle className="w-5 h-5 text-red-400" />
                      <div>
                        <span className="text-red-300">{t('callLogs.analyticsStatus.failed')}</span>
                        {callLog.analytics_error && (
                          <p className="text-xs text-red-400 mt-1">{callLog.analytics_error}</p>
                        )}
                      </div>
                    </>
                  )}
                  {callLog.analytics_status === ANALYTICS_STATUS.PENDING && (
                    <>
                      <Clock className="w-5 h-5 text-slate-400" />
                      <span className="text-slate-300">{t('callLogs.analyticsStatus.pending')}</span>
                    </>
                  )}
                </div>

                {/* Retry/Run Analytics Button */}
                {ENABLE_MANUAL_ANALYTICS && callLog.transcript && (
                  callLog.analytics_status === ANALYTICS_STATUS.FAILED ||
                  callLog.analytics_status === ANALYTICS_STATUS.PENDING
                ) && (
                  <Button
                    onClick={handleTriggerAnalytics}
                    disabled={isAnalyticsTriggering}
                    size="sm"
                    className="bg-slate-600 hover:bg-slate-500"
                  >
                    {isAnalyticsTriggering ? (
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    ) : (
                      <RefreshCw className="w-4 h-4 mr-2" />
                    )}
                    {callLog.analytics_status === ANALYTICS_STATUS.FAILED
                      ? t('callLogs.retryAnalytics')
                      : t('callLogs.runAnalytics')
                    }
                  </Button>
                )}
              </div>
            )}

            {/* Related Entities */}
            <div className="space-y-4">
              {/* Related Customers */}
              {callLog.related_customers && callLog.related_customers.length > 0 && (
                <div>
                  <h4 className="text-white font-medium mb-2 flex items-center gap-2">
                    <User className="w-4 h-4 text-slate-400" />
                    {t('callLogDetail.relatedCustomers')} ({callLog.related_customers.length})
                  </h4>
                  <div className="space-y-2">
                    {callLog.related_customers.map((customer, idx) => (
                      <div key={idx} className="bg-slate-700/30 rounded-lg p-3">
                        <div className="flex items-center justify-between">
                          <div>
                            {customer.name && (
                              <p className="text-white font-medium">{customer.name}</p>
                            )}
                            {customer.email && (
                              <p className="text-slate-300 text-sm">{customer.email}</p>
                            )}
                            {customer.phone && (
                              <p className="text-slate-400 text-sm">{customer.phone}</p>
                            )}
                          </div>
                        </div>
                        <p className="text-slate-400 text-xs mt-2 italic">{customer.match_reason}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Related Orders */}
              {callLog.related_orders && callLog.related_orders.length > 0 && (
                <div>
                  <h4 className="text-white font-medium mb-2 flex items-center gap-2">
                    <ShoppingCart className="w-4 h-4 text-slate-400" />
                    {t('callLogDetail.relatedOrders')} ({callLog.related_orders.length})
                  </h4>
                  <div className="space-y-2">
                    {callLog.related_orders.map((order, idx) => (
                      <div key={idx} className="bg-slate-700/30 rounded-lg p-3">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-white font-medium">#{order.order_number}</p>
                            {order.status && (
                              <span className="text-xs px-2 py-0.5 bg-slate-600 rounded text-slate-300">
                                {order.status}
                              </span>
                            )}
                          </div>
                          {order.total && (
                            <p className="text-green-400 font-medium">{order.total}</p>
                          )}
                        </div>
                        <p className="text-slate-400 text-xs mt-2 italic">{order.match_reason}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Related Products */}
              {callLog.related_products && callLog.related_products.length > 0 && (
                <div>
                  <h4 className="text-white font-medium mb-2 flex items-center gap-2">
                    <Package className="w-4 h-4 text-slate-400" />
                    {t('callLogDetail.relatedProducts')} ({callLog.related_products.length})
                  </h4>
                  <div className="space-y-2">
                    {callLog.related_products.map((product, idx) => (
                      <div key={idx} className="bg-slate-700/30 rounded-lg p-3">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-white font-medium">{product.name}</p>
                            {product.sku && (
                              <p className="text-slate-400 text-sm">SKU: {product.sku}</p>
                            )}
                          </div>
                          {product.price && (
                            <p className="text-green-400 font-medium">{product.price}</p>
                          )}
                        </div>
                        <p className="text-slate-400 text-xs mt-2 italic">{product.match_reason}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Show "Run Analytics" button if no related data and analytics not completed */}
              {ENABLE_MANUAL_ANALYTICS && callLog.transcript &&
                !callLog.related_customers?.length &&
                !callLog.related_orders?.length &&
                !callLog.related_products?.length &&
                callLog.analytics_status !== ANALYTICS_STATUS.RUNNING && (
                <div className="text-center py-4">
                  <p className="text-slate-400 text-sm mb-3">{t('callLogDetail.noRelatedData')}</p>
                  <Button
                    onClick={handleTriggerAnalytics}
                    disabled={isAnalyticsTriggering}
                    className="bg-cyan-600 hover:bg-cyan-500"
                  >
                    {isAnalyticsTriggering ? (
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    ) : (
                      <RefreshCw className="w-4 h-4 mr-2" />
                    )}
                    {t('callLogs.runAnalytics')}
                  </Button>
                </div>
              )}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}
