import { useEffect, useMemo, useState } from 'react';
import { apiGet, apiPost } from '../lib/firebase';
import {
  Search, SlidersHorizontal, MessageSquare, Phone, Mail, Globe2, Voicemail,
  Bot, UserRound, Clock3, Tag, CalendarDays, BriefcaseBusiness, Send,
  RefreshCw, AlertTriangle, CheckCircle2, ChevronRight, Sparkles, Inbox,
  Building2, ArrowUpRight, X, Filter, PhoneMissed, CircleDot,
} from 'lucide-react';

type Channel = 'all' | 'sms' | 'call' | 'email' | 'voicemail' | 'webchat';
type Direction = 'inbound' | 'outbound';

interface Client {
  id: string;
  business_name: string;
  subdomain: string;
  status: string;
  twilio_phone_number: string | null;
}

interface ApiConversation {
  contact_id: string;
  contact_name: string | null;
  contact_phone: string;
  pipeline_stage: string;
  message_count: number;
  last_message_at: string;
  last_message: string;
  last_direction: Direction;
}

interface Conversation extends ApiConversation {
  client_id: string;
  client_name: string;
  channel: Exclude<Channel, 'all'>;
  unread: boolean;
  priority: 'normal' | 'high';
}

interface SmsLog {
  id: string;
  direction: Direction;
  message_body: string;
  status: string;
  template_name: string | null;
  created_at: string;
  contact_name: string | null;
  contact_phone: string | null;
}

const CHANNELS: Array<{ value: Channel; label: string; icon: typeof MessageSquare }> = [
  { value: 'all', label: 'All', icon: Inbox },
  { value: 'sms', label: 'SMS', icon: MessageSquare },
  { value: 'call', label: 'Calls', icon: Phone },
  { value: 'voicemail', label: 'Voicemail', icon: Voicemail },
  { value: 'email', label: 'Email', icon: Mail },
  { value: 'webchat', label: 'Web Chat', icon: Globe2 },
];

function relativeTime(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '';
  const diff = Date.now() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);
  if (minutes < 1) return 'Now';
  if (minutes < 60) return `${minutes}m`;
  if (hours < 24) return `${hours}h`;
  if (days < 7) return `${days}d`;
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

function fullTime(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '';
  return date.toLocaleString('en-US', {
    month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
  });
}

function initials(name: string | null, phone: string) {
  if (name?.trim()) return name.trim().split(/\s+/).slice(0, 2).map(part => part[0]).join('').toUpperCase();
  return phone.slice(-2);
}

function displayName(conversation: Conversation | null) {
  return conversation?.contact_name?.trim() || conversation?.contact_phone || 'Unknown contact';
}

export default function ConversationsPage() {
  const [clients, setClients] = useState<Client[]>([]);
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [messages, setMessages] = useState<SmsLog[]>([]);
  const [selected, setSelected] = useState<Conversation | null>(null);
  const [loading, setLoading] = useState(true);
  const [messagesLoading, setMessagesLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState('');
  const [query, setQuery] = useState('');
  const [channel, setChannel] = useState<Channel>('all');
  const [clientFilter, setClientFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'unread' | 'high'>('all');
  const [composer, setComposer] = useState('');
  const [sending, setSending] = useState(false);
  const [sendSuccess, setSendSuccess] = useState('');

  const loadConversations = async (showRefresh = false) => {
    showRefresh ? setRefreshing(true) : setLoading(true);
    setError('');
    try {
      const clientResponse = await apiGet<{ clients: Client[] }>('/api/onboarding/clients');
      const activeClients = clientResponse.clients || [];
      setClients(activeClients);
      setClientFilter(current => current || activeClients[0]?.id || '');

      const results = await Promise.allSettled(
        activeClients.map(async client => {
          const response = await apiGet<{ conversations: ApiConversation[] }>(`/api/sms/conversations/${client.id}`);
          return (response.conversations || []).map((conversation, index): Conversation => ({
            ...conversation,
            client_id: client.id,
            client_name: client.business_name,
            channel: 'sms',
            unread: conversation.last_direction === 'inbound' && index < 3,
            priority: conversation.pipeline_stage?.toLowerCase().includes('urgent') ? 'high' : 'normal',
          }));
        })
      );

      const merged = results
        .filter((result): result is PromiseFulfilledResult<Conversation[]> => result.status === 'fulfilled')
        .flatMap(result => result.value)
        .sort((a, b) => new Date(b.last_message_at).getTime() - new Date(a.last_message_at).getTime());

      setConversations(merged);
      setSelected(current => {
        if (current) return merged.find(item => item.client_id === current.client_id && item.contact_id === current.contact_id) || merged[0] || null;
        return merged[0] || null;
      });
    } catch (err: any) {
      setError(err?.message || 'Unable to load conversations.');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  useEffect(() => {
    if (!selected) {
      setMessages([]);
      return;
    }
    let cancelled = false;
    const loadMessages = async () => {
      setMessagesLoading(true);
      try {
        const response = await apiGet<{ logs: SmsLog[] }>(
          `/api/sms/logs/${selected.client_id}?contactId=${encodeURIComponent(selected.contact_id)}&limit=100`
        );
        if (!cancelled) setMessages((response.logs || []).slice().reverse());
      } catch (err: any) {
        if (!cancelled) setError(err?.message || 'Unable to load message history.');
      } finally {
        if (!cancelled) setMessagesLoading(false);
      }
    };
    loadMessages();
    return () => { cancelled = true; };
  }, [selected?.client_id, selected?.contact_id]);

  const filtered = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    return conversations.filter(item => {
      const matchesSearch = !normalized || [item.contact_name, item.contact_phone, item.client_name, item.last_message, item.pipeline_stage]
        .some(value => value?.toLowerCase().includes(normalized));
      const matchesChannel = channel === 'all' || item.channel === channel;
      const matchesClient = clientFilter === 'all' || item.client_id === clientFilter;
      const matchesStatus = statusFilter === 'all' || (statusFilter === 'unread' ? item.unread : item.priority === 'high');
      return matchesSearch && matchesChannel && matchesClient && matchesStatus;
    });
  }, [conversations, query, channel, clientFilter, statusFilter]);

  useEffect(() => {
    if (selected && !filtered.some(item => item.client_id === selected.client_id && item.contact_id === selected.contact_id)) {
      setSelected(filtered[0] || null);
    }
  }, [filtered, selected]);

  const workspaceConversations = conversations.filter(item => clientFilter === 'all' || item.client_id === clientFilter);
  const unreadCount = workspaceConversations.filter(item => item.unread).length;
  const responseNeeded = workspaceConversations.filter(item => item.last_direction === 'inbound').length;
  const selectedWorkspace = clients.find(client => client.id === clientFilter) || null;
  const workspaceLabel = clientFilter === 'all' ? 'All Workspaces' : selectedWorkspace?.business_name || 'Select Workspace';

  const sendMessage = async () => {
    if (!selected || !composer.trim()) return;
    setSending(true);
    setError('');
    try {
      await apiPost('/api/sms/send', {
        clientId: selected.client_id,
        toNumber: selected.contact_phone,
        message: composer.trim(),
      });
      const optimistic: SmsLog = {
        id: `optimistic-${Date.now()}`,
        direction: 'outbound',
        message_body: composer.trim(),
        status: 'sent',
        template_name: null,
        created_at: new Date().toISOString(),
        contact_name: selected.contact_name,
        contact_phone: selected.contact_phone,
      };
      setMessages(prev => [...prev, optimistic]);
      setComposer('');
      setSendSuccess('Message sent');
      window.setTimeout(() => setSendSuccess(''), 2500);
    } catch (err: any) {
      setError(err?.message || 'Message could not be sent.');
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="page-content conversations-page">
      <div className="conversations-header">
        <div>
          <span className="eyebrow">Communications Operations</span>
          <h1>Unified Conversations</h1>
          <p>Manage calls, messages, and customer follow-up inside one business workspace at a time.</p>
        </div>
        <div className="conversations-header-actions">
          <button className="btn btn-outline" onClick={() => loadConversations(true)} disabled={refreshing}>
            <RefreshCw size={17} className={refreshing ? 'spin-icon' : ''} /> Refresh
          </button>
          <button className="btn btn-primary" onClick={() => document.getElementById('conversation-search')?.focus()}>
            <Search size={17} /> Find conversation
          </button>
        </div>
      </div>

      <section className="conversation-workspace-switcher">
        <div className="workspace-switcher-copy">
          <span className="workspace-switcher-icon"><Building2 size={21} /></span>
          <div>
            <span>Current Workspace</span>
            <strong>{workspaceLabel}</strong>
          </div>
        </div>
        <label className="workspace-switcher-control">
          <span>View conversations for</span>
          <select value={clientFilter} onChange={event => setClientFilter(event.target.value)}>
            {clients.map(client => <option key={client.id} value={client.id}>{client.business_name}</option>)}
            <option value="all">All Workspaces — Super Admin View</option>
          </select>
        </label>
        {clientFilter === 'all' && <div className="workspace-admin-warning"><AlertTriangle size={16} /><span>All Workspaces combines multiple businesses. Use this only for platform-wide review.</span></div>}
      </section>

      <div className="conversation-stat-grid">
        <div className="conversation-stat"><span className="conversation-stat-icon blue"><MessageSquare size={20} /></span><div><strong>{workspaceConversations.length}</strong><span>Open conversations</span></div></div>
        <div className="conversation-stat"><span className="conversation-stat-icon gold"><CircleDot size={20} /></span><div><strong>{unreadCount}</strong><span>Unread conversations</span></div></div>
        <div className="conversation-stat"><span className="conversation-stat-icon green"><ArrowUpRight size={20} /></span><div><strong>{responseNeeded}</strong><span>Awaiting response</span></div></div>
        <div className="conversation-stat"><span className="conversation-stat-icon purple"><Building2 size={20} /></span><div><strong>{clientFilter === 'all' ? clients.length : 1}</strong><span>{clientFilter === 'all' ? 'Workspaces in view' : 'Selected workspace'}</span></div></div>
      </div>

      {error && <div className="alert alert-error conversations-alert"><AlertTriangle size={18} /> {error}<button onClick={() => setError('')}><X size={16} /></button></div>}
      {sendSuccess && <div className="alert alert-success conversations-alert"><CheckCircle2 size={18} /> {sendSuccess}</div>}

      <div className="conversation-channel-bar">
        <div className="channel-tabs">
          {CHANNELS.map(item => {
            const Icon = item.icon;
            const available = item.value === 'all' || item.value === 'sms';
            return (
              <button key={item.value} className={`channel-tab ${channel === item.value ? 'active' : ''} ${!available ? 'planned' : ''}`} onClick={() => setChannel(item.value)}>
                <Icon size={17} /><span>{item.label}</span>{!available && <small>Next</small>}
              </button>
            );
          })}
        </div>
        <div className="channel-health"><span /><strong>SMS connected</strong><small>Voice, email & web chat ready to connect</small></div>
      </div>

      <div className="conversations-workspace">
        <section className="conversation-list-panel">
          <div className="conversation-filters">
            <label className="conversation-search">
              <Search size={18} />
              <input id="conversation-search" value={query} onChange={event => setQuery(event.target.value)} placeholder="Search people, numbers, messages..." />
              {query && <button onClick={() => setQuery('')}><X size={15} /></button>}
            </label>
            <div className="conversation-filter-row">
              <div className="active-workspace-chip"><Building2 size={15} /><span>{workspaceLabel}</span></div>
              <label><Filter size={15} /><select value={statusFilter} onChange={event => setStatusFilter(event.target.value as typeof statusFilter)}><option value="all">All status</option><option value="unread">Unread</option><option value="high">High priority</option></select></label>
            </div>
          </div>

          <div className="conversation-list-heading"><span>{filtered.length} conversations</span><button><SlidersHorizontal size={16} /> Sort: Recent</button></div>

          <div className="conversation-list" aria-live="polite">
            {loading ? (
              <div className="conversation-loading"><div className="spinner" /><p>Loading conversations...</p></div>
            ) : channel !== 'all' && channel !== 'sms' ? (
              <div className="channel-empty"><div><Sparkles size={25} /></div><h3>{CHANNELS.find(item => item.value === channel)?.label} is ready for connection</h3><p>This channel already has a place in the unified inbox. Its API and provider connection will be added without redesigning this page.</p></div>
            ) : filtered.length === 0 ? (
              <div className="channel-empty"><div><Inbox size={25} /></div><h3>No conversations found</h3><p>Adjust the filters or wait for a new customer conversation.</p></div>
            ) : filtered.map(item => {
              const isSelected = selected?.client_id === item.client_id && selected?.contact_id === item.contact_id;
              return (
                <button key={`${item.client_id}-${item.contact_id}`} className={`conversation-row ${isSelected ? 'selected' : ''}`} onClick={() => setSelected({ ...item, unread: false })}>
                  <span className="conversation-avatar">{initials(item.contact_name, item.contact_phone)}<i className="sms"><MessageSquare size={10} /></i></span>
                  <span className="conversation-row-main">
                    <span className="conversation-row-top"><strong>{displayName(item)}</strong><time>{relativeTime(item.last_message_at)}</time></span>
                    {clientFilter === 'all' && <span className="conversation-client-name">{item.client_name}</span>}
                    <span className="conversation-preview">{item.last_direction === 'outbound' && 'You: '}{item.last_message || 'No message preview'}</span>
                    <span className="conversation-meta"><em>{item.pipeline_stage || 'New lead'}</em><small>{item.message_count} messages</small>{item.last_direction === 'inbound' && <small className="needs-reply">Needs reply</small>}</span>
                  </span>
                  {item.unread && <span className="unread-dot" />}
                </button>
              );
            })}
          </div>
        </section>

        <section className="conversation-thread-panel">
          {!selected ? (
            <div className="thread-empty"><span><MessageSquare size={30} /></span><h2>Select a conversation</h2><p>Choose a customer conversation to see the complete history and respond.</p></div>
          ) : (
            <>
              <header className="thread-header">
                <div className="thread-contact"><span className="thread-avatar">{initials(selected.contact_name, selected.contact_phone)}</span><div><h2>{displayName(selected)}</h2><p><Phone size={14} /> {selected.contact_phone}<span>•</span><MessageSquare size={14} /> SMS<span>•</span><Building2 size={14} /> {selected.client_name}</p></div></div>
                <div className="thread-actions"><button title="Call"><Phone size={18} /></button><button title="Create appointment"><CalendarDays size={18} /></button><button title="Open contact"><UserRound size={18} /></button></div>
              </header>

              <div className="ai-summary-bar">
                <span><Sparkles size={18} /></span>
                <div><strong>Kingdom AI summary</strong><p>{selected.last_direction === 'inbound' ? 'The customer sent the latest message and may need a response.' : 'Your team sent the latest message. Monitor for the customer’s reply.'} Current pipeline stage: <b>{selected.pipeline_stage || 'New lead'}</b>.</p></div>
                <button>Generate full summary</button>
              </div>

              <div className="thread-messages">
                {messagesLoading ? <div className="conversation-loading"><div className="spinner" /><p>Loading message history...</p></div> : messages.length === 0 ? <div className="thread-no-messages"><Clock3 size={22} /><p>No message history is available yet.</p></div> : messages.map(message => (
                  <div key={message.id} className={`message-group ${message.direction}`}>
                    <div className="message-bubble"><p>{message.message_body}</p><span>{fullTime(message.created_at)} · {message.status || 'sent'}</span></div>
                  </div>
                ))}
              </div>

              <div className="message-composer">
                <div className="composer-tools"><button><Sparkles size={16} /> AI reply</button><button><Tag size={16} /> Template</button><span>Sending from {selected.client_name}</span></div>
                <div className="composer-input"><textarea value={composer} onChange={event => setComposer(event.target.value)} placeholder={`Reply to ${displayName(selected)}...`} onKeyDown={event => { if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') sendMessage(); }} /><button onClick={sendMessage} disabled={sending || !composer.trim()}>{sending ? <RefreshCw size={18} className="spin-icon" /> : <Send size={18} />} Send</button></div>
                <small>Press ⌘ + Enter to send</small>
              </div>
            </>
          )}
        </section>

        <aside className="conversation-inspector">
          {!selected ? <div className="inspector-empty"><UserRound size={26} /><p>Contact intelligence will appear here.</p></div> : (
            <>
              <div className="inspector-profile"><span>{initials(selected.contact_name, selected.contact_phone)}</span><h3>{displayName(selected)}</h3><p>{selected.contact_phone}</p><div><button><Phone size={16} /> Call</button><button><Mail size={16} /> Email</button></div></div>
              <div className="inspector-section"><h4>Conversation details</h4><dl><div><dt>Workspace</dt><dd>{selected.client_name}</dd></div><div><dt>Channel</dt><dd><MessageSquare size={14} /> SMS</dd></div><div><dt>Last activity</dt><dd>{relativeTime(selected.last_message_at)} ago</dd></div><div><dt>Messages</dt><dd>{selected.message_count}</dd></div></dl></div>
              <div className="inspector-section"><h4>CRM intelligence</h4><div className="stage-pill"><BriefcaseBusiness size={15} /> {selected.pipeline_stage || 'New lead'}</div><button className="inspector-link">Open full contact record <ChevronRight size={16} /></button></div>
              <div className="inspector-section"><h4>Recommended next action</h4><div className="recommended-action"><Bot size={18} /><div><strong>{selected.last_direction === 'inbound' ? 'Respond now' : 'Monitor for reply'}</strong><p>{selected.last_direction === 'inbound' ? 'The customer sent the latest message.' : 'Your latest message is awaiting a response.'}</p></div></div></div>
            </>
          )}
        </aside>
      </div>
    </div>
  );
}
