'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Bot, User, Send, Phone, Mail, Tag, CheckCircle, AlertCircle, Zap, StickyNote, X, Loader2, PhoneCall, PhoneOff, MessageSquare } from 'lucide-react';
import { useAuth } from '@client/contexts/AuthContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { toast } from 'sonner';
import { getConversation, updateConversation } from '@client/api/conversations';
import { getAIConfig } from '@client/api/ai-config';
import { usePageHeader } from '@client/contexts/PageHeaderContext';

interface Message {
  id: string;
  sender: 'ai' | 'customer' | 'agent';
  text: string;
  time: string;
  confidence?: number;
}

interface ConversationRow {
  id: string;
  customer_name: string;
  customer_email?: string;
  customer_phone?: string;
  channel: string;
  status: string;
  topic: string;
  messages: any[];
  ai_confidence?: number;
  assigned_agent?: string;
  restaurant_id: string;
  branch_id?: string;
  unread_count?: number;
  updated_at: string;
}

const quickReplies = [
  "I'll look into that for you",
  'Let me check with the kitchen',
  'Your reservation has been updated',
  'Thank you for your patience',
  'Is there anything else I can help with?',
];

function msgTime() {
  return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

function rowToMessages(raw: any[]): Message[] {
  if (!Array.isArray(raw)) return [];
  return raw.map((m, i) => ({
    id: m.id || String(i),
    sender: m.sender || (m.role === 'assistant' ? 'ai' : m.role === 'user' ? 'customer' : 'agent'),
    text: m.text || m.content || '',
    time: m.time || (m.created_at ? new Date(m.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : msgTime()),
    confidence: m.confidence,
  }));
}

export default function LiveChatPage() {
  const { t } = useLanguage();
  usePageHeader(t('conversations.liveChat', "Live Chat"), t('conversations.loadingConversation', "Loading conversation..."));
  const params = useParams();
  const conversationId = params?.id as string;
  const { restaurantId } = useAuth();

  const [conversation, setConversation] = useState<ConversationRow | null>(null);
  const [chatMessages, setChatMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isAgentMode, setIsAgentMode] = useState(false);
  const [showNotes, setShowNotes] = useState(false);
  const [note, setNote] = useState('');
  const [loading, setLoading] = useState(true);
  const [aiThinking, setAiThinking] = useState(false);
  const [agentModel, setAgentModel] = useState('gpt-4o');
  const [agentStyle, setAgentStyle] = useState('friendly');
  const [callLoading, setCallLoading] = useState(false);
  const [callActive, setCallActive] = useState(false);
  const [callSid, setCallSid] = useState<string | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [chatMessages, aiThinking]);

  const loadAll = useCallback(async () => {
    if (!conversationId || !restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const [convResult, configResult] = await Promise.all([
        getConversation(conversationId),
        getAIConfig().catch(() => ({})),
      ]);

      const conv = convResult.conversation as unknown as ConversationRow;
      setConversation(conv);
      setChatMessages(rowToMessages(conv.messages || []));
      setIsAgentMode(conv.status === 'human');

      if (configResult?.config) {
        setAgentModel(configResult.config.model || 'gpt-4o');
        setAgentStyle(configResult.config.response_style || 'friendly');
      }
    } catch (err: any) {
      toast.error(t('conversations.failedToLoad', 'Failed to load conversation: ') + err.message);
    } finally {
      setLoading(false);
    }
  }, [conversationId, restaurantId]);

  useEffect(() => { loadAll(); }, [loadAll]);

  const persistMessages = useCallback(async (msgs: Message[], status?: string) => {
    if (!conversationId) return;
    const lastMsg = msgs[msgs.length - 1];
    if (lastMsg) {
      await updateConversation(conversationId, {
        messages: [{ id: lastMsg.id, sender: lastMsg.sender, text: lastMsg.text, time: lastMsg.time, confidence: lastMsg.confidence }],
      });
    }
    if (status) {
      await updateConversation(conversationId, { status });
    }
  }, [conversationId]);

  const handleCustomerMessage = async (text: string) => {
    const customerMsg: Message = { id: Date.now().toString(), sender: 'customer', text, time: msgTime() };
    const updatedMsgs = [...chatMessages, customerMsg];
    setChatMessages(updatedMsgs);

    if (isAgentMode) {
      await persistMessages(updatedMsgs);
      return;
    }

    setAiThinking(true);
    try {
      const res = await fetch('/api/conversations/send-message', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          conversationId,
          message: text,
          history: updatedMsgs.slice(-20).map(m => ({ role: m.sender === 'customer' ? 'user' : 'assistant', content: m.text })),
        }),
      });
      const data = await res.json();

      const aiMsg: Message = {
        id: (Date.now() + 1).toString(),
        sender: 'ai',
        text: data.reply || 'I understand. How can I help?',
        time: msgTime(),
        confidence: data.shouldEscalate ? undefined : 90,
      };

      const finalMsgs = [...updatedMsgs, aiMsg];
      setChatMessages(finalMsgs);

      if (data.shouldEscalate) {
        setIsAgentMode(true);
        toast.warning(`${t('conversations.escalated', 'Escalated')}: ${data.escalationReason || t('conversations.needsHuman', 'Needs human agent')}`);
        await persistMessages(finalMsgs, 'human');
      } else {
        await persistMessages(finalMsgs);
      }
    } catch {
      const aiMsg: Message = { id: (Date.now() + 1).toString(), sender: 'ai', text: t('conversations.aiFallbackReply', 'I understand. How can I help you further?'), time: msgTime(), confidence: 85 };
      const finalMsgs = [...updatedMsgs, aiMsg];
      setChatMessages(finalMsgs);
      await persistMessages(finalMsgs);
    } finally {
      setAiThinking(false);
    }
  };

  const handleAgentSend = async () => {
    if (!input.trim()) return;
    const agentMsg: Message = { id: Date.now().toString(), sender: 'agent', text: input, time: msgTime() };
    const updated = [...chatMessages, agentMsg];
    setChatMessages(updated);
    setInput('');
    await persistMessages(updated);
  };

  const handleSend = async () => {
    if (!input.trim()) return;
    const text = input;
    setInput('');
    if (isAgentMode) {
      const agentMsg: Message = { id: Date.now().toString(), sender: 'agent', text, time: msgTime() };
      const updated = [...chatMessages, agentMsg];
      setChatMessages(updated);
      await persistMessages(updated);
    } else {
      await handleCustomerMessage(text);
    }
  };

  const handleTakeOver = async () => {
    setIsAgentMode(true);
    const takeoverMsg: Message = {
      id: Date.now().toString(),
      sender: 'agent',
      text: `👋 ${t('conversations.takeoverHi', 'Hi')} ${conversation?.customer_name?.split(' ')[0] || t('conversations.there', 'there')}, ${t('conversations.takeoverMessage', "I've taken over from our AI assistant. How can I help you?")}`,
      time: msgTime(),
    };
    const updated = [...chatMessages, takeoverMsg];
    setChatMessages(updated);
    await persistMessages(updated, 'human');
    toast.success(t('conversations.takeoverSuccess', 'You are now handling this conversation'));
  };

  const handleResolve = async () => {
    const resolveMsg: Message = { id: Date.now().toString(), sender: 'agent', text: `✅ ${t('conversations.resolveMessage', 'This conversation has been resolved. Thank you!')}`, time: msgTime() };
    const updated = [...chatMessages, resolveMsg];
    setChatMessages(updated);
    await persistMessages(updated, 'resolved');
    toast.success(t('conversations.resolveSuccess', 'Conversation resolved'));
  };

  const handleOutboundCall = async () => {
    if (!conversation?.customer_phone) { toast.error(t('conversations.noPhone', 'No phone number available for this customer')); return; }
    if (!restaurantId) return;
    setCallLoading(true);
    try {
      const res = await fetch('/api/twilio/outbound-call', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ to: conversation.customer_phone, restaurantId, conversationId }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || t('conversations.callFailed', 'Failed to initiate call'));
      setCallActive(true);
      setCallSid(data.callSid);
      toast.success(`${t('conversations.calling', 'Calling')} ${conversation.customer_phone}...`);
    } catch (err: any) {
      toast.error(err.message);
    } finally {
      setCallLoading(false);
    }
  };

  const customerName = conversation?.customer_name || t('conversations.customer', 'Customer');
  const customerInitials = customerName.split(' ').map((n: string) => n[0]).join('').slice(0, 2).toUpperCase();
  const avgConfidence = chatMessages.filter(m => m.confidence).reduce((sum, m, _, arr) => sum + (m.confidence || 0) / arr.length, 0);

  if (loading) {
    return (
      <>
        <div className="flex items-center justify-center py-24">
          <Loader2 size={28} className="animate-spin" style={{ color: 'hsl(var(--primary))' }} />
        </div>
      </>
    );
  }

  return (
    <>
      <div className="flex gap-5 h-[calc(100vh-180px)]">
        <div className="flex-1 flex flex-col card overflow-hidden">
          <div className="flex items-center justify-between px-5 py-3.5" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
            <div className="flex items-center gap-3">
              <Link href="/conversations" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
              <div className="w-9 h-9 rounded-full flex items-center justify-center text-white text-sm font-bold" style={{ background: 'linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))' }}>
                {customerInitials}
              </div>
              <div>
                <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{customerName}</p>
                <div className="flex items-center gap-1.5">
                  <span className="w-1.5 h-1.5 rounded-full bg-green-500" />
                  <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.activeNow', 'Active now')} · {conversation?.topic || t('conversations.general', 'General')}</span>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-2">
              {conversation?.customer_phone && (
                <button
                  onClick={callActive ? undefined : handleOutboundCall}
                  disabled={callLoading}
                  className="btn-secondary text-xs py-1.5 px-3"
                  style={{ color: callActive ? 'hsl(var(--danger))' : 'hsl(var(--success))', borderColor: callActive ? 'hsl(var(--danger-border))' : 'hsl(var(--success-border))' }}
                  title={callActive ? `${t('conversations.callActive', 'Call active')}: ${callSid}` : `${t('conversations.call', 'Call')} ${conversation.customer_phone}`}
                >
                  {callLoading ? <Loader2 size={13} className="animate-spin" /> : callActive ? <><PhoneOff size={13} /> {t('conversations.onCall', 'On Call')}</> : <><PhoneCall size={13} /> {t('conversations.callShort', 'Call')}</>}
                </button>
              )}
              {!isAgentMode ? (
                <button onClick={handleTakeOver} className="btn-secondary text-xs py-1.5 px-3" style={{ color: 'hsl(var(--warning))', borderColor: 'hsl(var(--warning-border))' }}>
                  <Zap size={13} /> {t('conversations.takeOver', 'Take Over')}
                </button>
              ) : (
                <span className="badge badge-warning text-xs"><User size={11} /> {t('conversations.agentMode', 'Agent Mode')}</span>
              )}
              <button onClick={handleResolve} className="btn-secondary text-xs py-1.5 px-3"><CheckCircle size={13} /> {t('conversations.resolve', 'Resolve')}</button>
              <button onClick={() => setShowNotes(!showNotes)} className="btn-ghost p-1.5"><StickyNote size={16} /></button>
            </div>
          </div>

          {!isAgentMode && (
            <div className="px-5 py-2 flex items-center gap-2" style={{ backgroundColor: 'hsl(var(--info-bg))', borderBottom: '1px solid hsl(var(--info-border))' }}>
              <Bot size={14} style={{ color: 'hsl(var(--info))' }} />
              <span className="text-xs font-medium" style={{ color: 'hsl(var(--info))' }}>
                {t('conversations.aiHandling', 'AI Agent is handling this conversation')} · {t('conversations.model', 'Model')}: {agentModel}
                {avgConfidence > 0 ? ` · ${t('conversations.avgConfidence', 'Avg confidence')}: ${Math.round(avgConfidence)}%` : ''}
              </span>
            </div>
          )}

          <div className="flex-1 overflow-y-auto scrollbar-thin p-5 space-y-4">
            {chatMessages.map(msg => (
              <div key={msg.id} className={`flex gap-3 ${msg.sender === 'customer' ? '' : 'flex-row-reverse'}`}>
                <div
                  className="w-7 h-7 rounded-full flex items-center justify-center shrink-0 text-xs font-bold text-white"
                  style={{ background: msg.sender === 'customer' ? 'linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))' : msg.sender === 'ai' ? 'linear-gradient(135deg, hsl(var(--info)), hsl(210, 100%, 30%))' : 'linear-gradient(135deg, hsl(var(--success)), hsl(142, 72%, 20%))' }}
                >
                  {msg.sender === 'customer' ? customerInitials[0] : msg.sender === 'ai' ? <Bot size={12} /> : <User size={12} />}
                </div>
                <div className={`max-w-[70%] ${msg.sender === 'customer' ? '' : 'items-end'} flex flex-col gap-1`}>
                  <div
                    className="px-4 py-2.5 rounded-2xl text-sm"
                    style={{
                      backgroundColor: msg.sender === 'customer' ? 'hsl(var(--muted))' : msg.sender === 'ai' ? 'hsl(var(--info-bg))' : 'hsl(var(--primary))',
                      color: msg.sender === 'agent' ? 'white' : 'hsl(var(--foreground))',
                      borderRadius: msg.sender === 'customer' ? '4px 18px 18px 18px' : '18px 4px 18px 18px',
                    }}
                  >
                    {msg.text}
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{msg.time}</span>
                    {msg.confidence && <span className="text-xs" style={{ color: 'hsl(var(--info))' }}>AI {msg.confidence}%</span>}
                    {msg.sender === 'ai' && <Bot size={10} style={{ color: 'hsl(var(--info))' }} />}
                    {msg.sender === 'agent' && <User size={10} style={{ color: 'hsl(var(--success))' }} />}
                  </div>
                </div>
              </div>
            ))}
            {aiThinking && (
              <div className="flex gap-3 flex-row-reverse">
                <div className="w-7 h-7 rounded-full flex items-center justify-center shrink-0 text-white" style={{ background: 'linear-gradient(135deg, hsl(var(--info)), hsl(210, 100%, 30%))' }}>
                  <Bot size={12} />
                </div>
                <div className="px-4 py-2.5 rounded-2xl text-sm flex items-center gap-2" style={{ backgroundColor: 'hsl(var(--info-bg))', borderRadius: '18px 4px 18px 18px' }}>
                  <Loader2 size={14} className="animate-spin" style={{ color: 'hsl(var(--info))' }} />
                  <span style={{ color: 'hsl(var(--info))' }}>{t('conversations.aiThinking', 'AI is thinking...')}</span>
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          <div className="px-5 py-2 flex gap-2 overflow-x-auto scrollbar-thin" style={{ borderTop: '1px solid hsl(var(--border))' }}>
            {quickReplies.map(r => (
              <button key={r} onClick={() => setInput(r)} className="shrink-0 text-xs px-3 py-1.5 rounded-full border transition-all" style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground-secondary))', backgroundColor: 'hsl(var(--surface))' }}>
                {t(`conversations.quickReplies.${r}`, r)}
              </button>
            ))}
          </div>

          <div className="px-5 py-3 flex gap-3" style={{ borderTop: '1px solid hsl(var(--border))' }}>
            <input
              className="input-base flex-1"
              placeholder={isAgentMode ? t('conversations.placeholderAgent', 'Type a message as agent...') : t('conversations.placeholderTest', 'Type a customer message to test AI...')}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && !aiThinking && handleSend()}
              disabled={aiThinking}
            />
            <button onClick={handleSend} disabled={aiThinking || !input.trim()} className="btn-primary px-3 disabled:opacity-40">
              {aiThinking ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}
            </button>
          </div>
        </div>

        <div className="w-72 shrink-0 space-y-4 overflow-y-auto scrollbar-thin">
          <div className="card p-4">
            <h3 className="text-xs font-semibold uppercase tracking-wider mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.customerLabel', 'Customer')}</h3>
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold" style={{ background: 'linear-gradient(135deg, hsl(var(--primary)), hsl(22, 89%, 36%))' }}>
                {customerInitials}
              </div>
              <div>
                <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{customerName}</p>
                <span
                  className="text-xs px-2 py-0.5 rounded-full font-medium flex items-center gap-1 w-fit"
                  style={{
                    backgroundColor: (conversation?.channel || 'chat') === 'voice' ? 'hsl(var(--success-bg))' : 'hsl(var(--info-bg))',
                    color: (conversation?.channel || 'chat') === 'voice' ? 'hsl(var(--success))' : 'hsl(var(--info))',
                  }}
                >
                  {(conversation?.channel || 'chat') === 'voice' ? <Phone size={10} /> : <MessageSquare size={10} />}
                  {(conversation?.channel || 'chat') === 'voice' ? t('conversations.voice', 'Voice') : t('conversations.chat', 'Chat')}
                </span>
              </div>
            </div>
            <div className="space-y-2 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {conversation?.customer_email && <div className="flex items-center gap-2"><Mail size={12} /> {conversation.customer_email}</div>}
              {conversation?.customer_phone && <div className="flex items-center gap-2"><Phone size={12} /> {conversation.customer_phone}</div>}
            </div>
          </div>

          <div className="card p-4">
            <h3 className="text-xs font-semibold uppercase tracking-wider mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.aiAgentConfig', 'AI Agent Config')}</h3>
            <div className="space-y-2 text-xs">
              {[{ label: t('conversations.modelLabel', 'Model'), value: agentModel }, { label: t('conversations.styleLabel', 'Style'), value: agentStyle }, { label: t('conversations.statusLabel', 'Status'), value: isAgentMode ? t('conversations.humanAgent', 'Human Agent') : t('conversations.aiHandlingShort', 'AI Handling') }].map(item => (
                <div key={item.label} className="flex justify-between">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</span>
                  <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{item.value}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card p-4">
            <h3 className="text-xs font-semibold uppercase tracking-wider mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.conversationInfo', 'Conversation Info')}</h3>
            <div className="space-y-2 text-xs">
              {[
                { label: t('conversations.topic', 'Topic'), value: conversation?.topic || t('conversations.general', 'General') },
                { label: t('conversations.channel', 'Channel'), value: (conversation?.channel || 'chat') === 'voice' ? `📞 ${t('conversations.voice', 'Voice')}` : `💬 ${t('conversations.chat', 'Chat')}` },
                { label: t('conversations.status', 'Status'), value: conversation?.status || 'ai' },
                { label: t('conversations.messages', 'Messages'), value: chatMessages.length },
                { label: t('conversations.aiMessages', 'AI Messages'), value: chatMessages.filter(m => m.sender === 'ai').length },
              ].map(item => (
                <div key={item.label} className="flex justify-between">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{item.label}</span>
                  <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{item.value}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card p-4">
            <h3 className="text-xs font-semibold uppercase tracking-wider mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.actions', 'Actions')}</h3>
            <div className="space-y-2">
              <button className="btn-secondary w-full justify-start text-xs py-2"><Tag size={13} /> {t('conversations.addTag', 'Add Tag')}</button>
              <button
                className="btn-secondary w-full justify-start text-xs py-2"
                style={{ color: 'hsl(var(--danger))' }}
                onClick={async () => { setIsAgentMode(true); await updateConversation(conversationId, { status: 'human' }); toast.warning(t('conversations.escalatedToManager', 'Escalated to manager')); }}
              >
                <AlertCircle size={13} /> {t('conversations.escalateToManager', 'Escalate to Manager')}
              </button>
            </div>
          </div>

          {showNotes && (
            <div className="card p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('conversations.internalNotes', 'Internal Notes')}</h3>
                <button onClick={() => setShowNotes(false)}><X size={14} style={{ color: 'hsl(var(--muted-foreground))' }} /></button>
              </div>
              <textarea className="input-base text-xs resize-none" rows={3} placeholder={t('conversations.notePlaceholder', "Add a private note (not visible to customer)...")} value={note} onChange={e => setNote(e.target.value)} />
              <button className="btn-secondary w-full justify-center mt-2 text-xs py-1.5">{t('conversations.saveNote', 'Save Note')}</button>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
