import React, { useState, useEffect, useCallback } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useSession } from 'next-auth/react';
import AdminLayout from '../../components/AdminLayout';
import { ArrowLeft } from 'lucide-react';

interface Conversation {
  id: number;
  title: string;
  created_at: string;
  updated_at: string;
  message_count: number;
}

interface Message {
  id: number;
  role: 'user' | 'assistant';
  content: string;
  created_at: string;
}

interface UserInfo {
  id: number;
  username: string | null;
  email: string | null;
  name: string | null;
}

export default function AdminConversations() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const { userId } = router.query;
  
  const [user, setUser] = useState<UserInfo | null>(null);
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [selectedConversation, setSelectedConversation] = useState<number | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingMessages, setLoadingMessages] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [darkMode, setDarkMode] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [showMessages, setShowMessages] = useState(false); // For mobile: show messages panel

  useEffect(() => {
    try {
      const savedTheme = localStorage.getItem('theme');
      if (savedTheme === 'dark') setDarkMode(true);
    } catch {}
    
    // Check for mobile
    const checkMobile = () => setIsMobile(window.innerWidth < 768);
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin');
    }
  }, [status, router]);

  useEffect(() => {
    if (status === 'authenticated' && userId) {
      loadConversations();
    }
  }, [status, userId]);

  async function loadConversations() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/admin/conversations?userId=${userId}`);
      const data = await res.json();
      
      if (!res.ok) {
        throw new Error(data.error || 'Failed to load conversations');
      }
      
      setUser(data.user);
      setConversations(data.conversations || []);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  async function loadMessages(conversationId: number) {
    setLoadingMessages(true);
    setSelectedConversation(conversationId);
    if (isMobile) setShowMessages(true); // Show messages panel on mobile
    try {
      const res = await fetch(`/api/admin/conversations?conversationId=${conversationId}`);
      const data = await res.json();
      
      if (!res.ok) {
        throw new Error(data.error || 'Failed to load messages');
      }
      
      setMessages(data.messages || []);
    } catch (err: any) {
      console.error('Error loading messages:', err);
    } finally {
      setLoadingMessages(false);
    }
  }

  const theme = {
    bg: darkMode ? '#1a1a2e' : '#f8fafc',
    cardBg: darkMode ? '#16213e' : '#ffffff',
    text: darkMode ? '#e2e8f0' : '#1e293b',
    textSecondary: darkMode ? '#94a3b8' : '#64748b',
    border: darkMode ? '#2d3748' : '#e2e8f0',
    userBubble: darkMode ? '#3b82f6' : '#2563eb',
    assistantBubble: darkMode ? '#374151' : '#f3f4f6',
  };

  const S: Record<string, React.CSSProperties> = {
    container: {
      display: 'flex',
      flexDirection: isMobile ? 'column' : 'row',
      gap: isMobile ? 0 : 24,
      height: isMobile ? 'auto' : 'calc(100vh - 180px)',
      minHeight: isMobile ? 'calc(100vh - 200px)' : undefined,
    },
    conversationList: {
      width: isMobile ? '100%' : 320,
      minWidth: isMobile ? undefined : 320,
      background: theme.cardBg,
      borderRadius: 12,
      border: `1px solid ${theme.border}`,
      overflow: 'hidden',
      display: isMobile && showMessages ? 'none' : 'flex',
      flexDirection: 'column',
      maxHeight: isMobile ? '60vh' : undefined,
    },
    listHeader: {
      padding: 16,
      borderBottom: `1px solid ${theme.border}`,
      fontWeight: 600,
      color: theme.text,
    },
    listContent: {
      flex: 1,
      overflowY: 'auto',
    },
    conversationItem: {
      padding: '12px 16px',
      borderBottom: `1px solid ${theme.border}`,
      cursor: 'pointer',
      transition: 'background 0.2s',
    },
    conversationTitle: {
      fontWeight: 500,
      color: theme.text,
      marginBottom: 4,
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
    },
    conversationMeta: {
      fontSize: 12,
      color: theme.textSecondary,
      display: 'flex',
      justifyContent: 'space-between',
    },
    messagePanel: {
      flex: 1,
      background: theme.cardBg,
      borderRadius: 12,
      border: `1px solid ${theme.border}`,
      display: isMobile && !showMessages ? 'none' : 'flex',
      flexDirection: 'column',
      overflow: 'hidden',
      marginTop: isMobile ? 16 : 0,
      minHeight: isMobile ? '50vh' : undefined,
    },
    messageHeader: {
      padding: 16,
      borderBottom: `1px solid ${theme.border}`,
      fontWeight: 600,
      color: theme.text,
    },
    messageContent: {
      flex: 1,
      overflowY: 'auto',
      padding: 16,
      display: 'flex',
      flexDirection: 'column',
      gap: 12,
    },
    messageBubble: {
      maxWidth: '80%',
      padding: '10px 14px',
      borderRadius: 12,
      fontSize: 14,
      lineHeight: 1.5,
      whiteSpace: 'pre-wrap',
      wordBreak: 'break-word',
    },
    userMessage: {
      alignSelf: 'flex-end',
      background: theme.userBubble,
      color: '#ffffff',
    },
    assistantMessage: {
      alignSelf: 'flex-start',
      background: theme.assistantBubble,
      color: theme.text,
    },
    emptyState: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      height: '100%',
      color: theme.textSecondary,
    },
    backLink: {
      display: 'inline-flex',
      alignItems: 'center',
      gap: 8,
      color: '#3b82f6',
      textDecoration: 'none',
      marginBottom: 16,
      fontSize: 14,
      cursor: 'pointer',
    },
  };

  if (status === 'loading' || loading) {
    return (
      <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="users">
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
          <div style={{ color: theme.textSecondary }}>Loading...</div>
        </div>
      </AdminLayout>
    );
  }

  if (error) {
    return (
      <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="users">
        <div style={{ textAlign: 'center', padding: 40, color: '#dc2626' }}>
          <p>{error}</p>
          <button onClick={() => router.push('/admin')} style={{ marginTop: 16, padding: '8px 16px', cursor: 'pointer' }}>
            Back to Admin
          </button>
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="users">
      <Head>
        <title>User Conversations - Admin - Gregory AI</title>
      </Head>

      <div style={S.backLink} onClick={() => router.push('/admin/users')}>
        ← Back to Users
      </div>

      {user && (
        <h2 style={{ color: theme.text, marginBottom: 16 }}>
          Conversations for {user.name || user.username || user.email}
        </h2>
      )}

      <div style={S.container}>
        {/* Conversation List */}
        <div style={S.conversationList}>
          <div style={S.listHeader}>
            📝 Conversations ({conversations.length})
          </div>
          <div style={S.listContent}>
            {conversations.length === 0 ? (
              <div style={{ ...S.emptyState, height: 200 }}>No conversations found</div>
            ) : (
              conversations.map((conv) => (
                <div
                  key={conv.id}
                  style={{
                    ...S.conversationItem,
                    background: selectedConversation === conv.id 
                      ? (darkMode ? '#2d3748' : '#e2e8f0') 
                      : 'transparent',
                  }}
                  onClick={() => loadMessages(conv.id)}
                >
                  <div style={S.conversationTitle}>{conv.title || 'Untitled'}</div>
                  <div style={S.conversationMeta}>
                    <span>{conv.message_count} messages</span>
                    <span>{new Date(conv.created_at).toLocaleDateString()}</span>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Message Panel */}
        <div style={S.messagePanel}>
          <div style={{ ...S.messageHeader, display: 'flex', alignItems: 'center', gap: 12 }}>
            {isMobile && showMessages && (
              <button
                onClick={() => setShowMessages(false)}
                style={{
                  background: 'none',
                  border: 'none',
                  cursor: 'pointer',
                  padding: 4,
                  display: 'flex',
                  alignItems: 'center',
                  color: theme.text
                }}
              >
                <ArrowLeft size={20} />
              </button>
            )}
            <span>
              {selectedConversation 
                ? `💬 ${conversations.find(c => c.id === selectedConversation)?.title || 'Conversation'}`
                : '💬 Select a conversation'
              }
            </span>
          </div>
          <div style={S.messageContent}>
            {!selectedConversation ? (
              <div style={S.emptyState}>Select a conversation to view messages</div>
            ) : loadingMessages ? (
              <div style={S.emptyState}>Loading messages...</div>
            ) : messages.length === 0 ? (
              <div style={S.emptyState}>No messages in this conversation</div>
            ) : (
              messages.map((msg) => (
                <div
                  key={msg.id}
                  style={{
                    ...S.messageBubble,
                    ...(msg.role === 'user' ? S.userMessage : S.assistantMessage),
                  }}
                >
                  {msg.content}
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </AdminLayout>
  );
}
