"use client";

import { useState, useEffect, useRef, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/AuthContext';
import { useToast } from '@/components/Toast';
import { Loader2, Send, MessageCircle, Plus, Trash2, CheckCircle, AlertTriangle } from 'lucide-react';
import '@/styles/Messages.css';

interface Conversation {
    id: number;
    subject: string;
    status: 'open' | 'closed';
    created_at: string;
    updated_at: string;
    product_id?: number;
    product_name?: string;
    unread_count: number;
    last_message?: string;
    user_name?: string;
    user_email?: string;
}

interface Message {
    id: number;
    sender_id: number;
    sender_role: 'customer' | 'admin';
    sender_name: string;
    content: string;
    created_at: string;
    is_read: boolean;
}

export default function MessagesPage() {
    const { user, loading: authLoading } = useAuth();
    const router = useRouter();
    const { showToast } = useToast();

    const [conversations, setConversations] = useState<Conversation[]>([]);
    const [activeConversation, setActiveConversation] = useState<Conversation | null>(null);
    const [messages, setMessages] = useState<Message[]>([]);
    const [loading, setLoading] = useState(true);
    const [newMessage, setNewMessage] = useState('');
    const [sending, setSending] = useState(false);
    const [showNewConversation, setShowNewConversation] = useState(false);
    const [newSubject, setNewSubject] = useState('');
    const [newInitialMessage, setNewInitialMessage] = useState('');
    const [showDeleteConfirm, setShowDeleteConfirm] = useState<number | null>(null);
    const [showResolveConfirm, setShowResolveConfirm] = useState<number | null>(null);

    const messagesEndRef = useRef<HTMLDivElement>(null);
    const activeConversationRef = useRef<Conversation | null>(null);
    const lastMessageCountRef = useRef<number>(0);

    useEffect(() => {
        activeConversationRef.current = activeConversation;
    }, [activeConversation]);

    useEffect(() => {
        if (!authLoading && !user) {
            router.push('/login');
        }
    }, [user, authLoading, router]);

    const getToken = useCallback(() => localStorage.getItem('token') || sessionStorage.getItem('token'), []);

    const fetchConversations = useCallback(async (silent = false) => {
        try {
            const res = await fetch('/api/conversations', {
                headers: { 'Authorization': `Bearer ${getToken()}` }
            });
            if (res.ok) {
                const data = await res.json();
                setConversations(data);
            }
        } catch (err) {
            console.error(err);
        } finally {
            if (!silent) setLoading(false);
        }
    }, [getToken]);

    const fetchMessages = useCallback(async (convId: number, silent = false) => {
        try {
            const res = await fetch(`/api/conversations/${convId}`, {
                headers: { 'Authorization': `Bearer ${getToken()}` }
            });
            if (res.ok) {
                const data = await res.json();
                const newCount = data.messages.length;

                // Only scroll to bottom if new messages arrived
                if (newCount > lastMessageCountRef.current) {
                    setTimeout(() => {
                        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
                    }, 100);
                }
                lastMessageCountRef.current = newCount;

                setMessages(data.messages);
                if (!silent) {
                    setConversations(prev => prev.map(c =>
                        c.id === convId ? { ...c, unread_count: 0 } : c
                    ));
                }
            }
        } catch (err) {
            console.error(err);
        }
    }, [getToken]);

    useEffect(() => {
        if (user) {
            fetchConversations();
        }
    }, [user, fetchConversations]);

    // Real-time polling
    useEffect(() => {
        if (!user) return;

        const pollInterval = setInterval(() => {
            fetchConversations(true);
            if (activeConversationRef.current) {
                fetchMessages(activeConversationRef.current.id, true);
            }
        }, 3000);

        return () => clearInterval(pollInterval);
    }, [user, fetchConversations, fetchMessages]);

    const openConversation = async (conv: Conversation) => {
        setActiveConversation(conv);
        lastMessageCountRef.current = 0; // Reset so it scrolls on open
        await fetchMessages(conv.id);
    };

    const handleSendMessage = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newMessage.trim() || !activeConversation) return;

        setSending(true);
        try {
            const res = await fetch(`/api/conversations/${activeConversation.id}`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${getToken()}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ content: newMessage })
            });

            if (res.ok) {
                setNewMessage('');
                lastMessageCountRef.current = 0; // Scroll to new message
                await fetchMessages(activeConversation.id);
                showToast('success', 'Meddelande skickat');
            }
        } catch (err) {
            showToast('error', 'Kunde inte skicka');
        } finally {
            setSending(false);
        }
    };

    const handleCreateConversation = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newSubject.trim() || !newInitialMessage.trim()) return;

        setSending(true);
        try {
            const res = await fetch('/api/conversations', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${getToken()}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    subject: newSubject,
                    message: newInitialMessage
                })
            });

            if (res.ok) {
                const data = await res.json();
                setShowNewConversation(false);
                setNewSubject('');
                setNewInitialMessage('');
                showToast('success', 'Ärende skapat');
                await fetchConversations();
                openConversation({ id: data.conversationId, subject: newSubject } as Conversation);
            }
        } catch (err) {
            showToast('error', 'Något gick fel');
        } finally {
            setSending(false);
        }
    };

    const handleDeleteConversation = async (id: number) => {
        try {
            const res = await fetch(`/api/conversations/${id}`, {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${getToken()}` }
            });
            if (res.ok) {
                showToast('success', 'Konversation borttagen');
                setShowDeleteConfirm(null);
                if (activeConversation?.id === id) {
                    setActiveConversation(null);
                    setMessages([]);
                }
                await fetchConversations();
            }
        } catch (err) {
            showToast('error', 'Kunde inte ta bort');
        }
    };

    const handleResolveConversation = async (id: number) => {
        try {
            const res = await fetch(`/api/conversations/${id}`, {
                method: 'PATCH',
                headers: {
                    'Authorization': `Bearer ${getToken()}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ action: 'resolve' })
            });
            if (res.ok) {
                showToast('success', 'Ärende markerat som löst');
                setShowResolveConfirm(null);
                if (activeConversation?.id === id) {
                    setActiveConversation(null);
                    setMessages([]);
                }
                await fetchConversations();
            }
        } catch (err) {
            showToast('error', 'Kunde inte lösa ärende');
        }
    };

    const isAdmin = user?.role === 'admin';

    if (authLoading || loading) {
        return (
            <div className="h-screen flex items-center justify-center">
                <Loader2 className="animate-spin" size={48} />
            </div>
        );
    }

    return (
        <div className="messages-container">
            <div className="messages-header">
                <h1>Meddelanden</h1>
                {!showNewConversation && !isAdmin && (
                    <button onClick={() => setShowNewConversation(true)} className="msg-btn">
                        <Plus size={16} />
                        Nytt ärende
                    </button>
                )}
            </div>

            {/* New Conversation Form */}
            {showNewConversation && (
                <div className="msg-form-card">
                    <h2>Nytt meddelande</h2>
                    <form onSubmit={handleCreateConversation}>
                        <input
                            type="text"
                            value={newSubject}
                            onChange={(e) => setNewSubject(e.target.value)}
                            className="msg-input"
                            placeholder="Ämne"
                            required
                        />
                        <textarea
                            value={newInitialMessage}
                            onChange={(e) => setNewInitialMessage(e.target.value)}
                            className="msg-input"
                            placeholder="Beskriv ditt ärende..."
                            style={{ minHeight: '100px', resize: 'vertical' }}
                            required
                        />
                        <div style={{ display: 'flex', gap: '0.75rem' }}>
                            <button type="button" onClick={() => setShowNewConversation(false)} className="msg-btn">
                                Avbryt
                            </button>
                            <button type="submit" disabled={sending} className="msg-btn primary">
                                <Send size={16} />
                                {sending ? 'Skickar...' : 'Skicka'}
                            </button>
                        </div>
                    </form>
                </div>
            )}

            <div className="messages-grid">
                {/* Conversation List */}
                <div className="conversation-list">
                    {conversations.length === 0 ? (
                        <div className="empty-state">
                            <MessageCircle size={48} />
                            <p>Inga meddelanden ännu</p>
                        </div>
                    ) : (
                        conversations.map(conv => (
                            <div
                                key={conv.id}
                                onClick={() => openConversation(conv)}
                                className={`conversation-item ${activeConversation?.id === conv.id ? 'active' : ''} ${conv.status === 'closed' ? 'closed' : ''}`}
                            >
                                <div className="conversation-subject">
                                    {conv.status === 'closed' && <CheckCircle size={14} style={{ color: '#10b981' }} />}
                                    <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{conv.subject}</span>
                                    {conv.unread_count > 0 && (
                                        <span className="unread-badge">{conv.unread_count}</span>
                                    )}
                                </div>
                                {isAdmin && conv.user_name && (
                                    <div style={{ fontSize: '0.7rem', color: activeConversation?.id === conv.id ? 'inherit' : '#3b82f6', marginBottom: '0.25rem' }}>
                                        {conv.user_name}
                                    </div>
                                )}
                                {conv.last_message && (
                                    <div className="conversation-preview">{conv.last_message}</div>
                                )}
                                <div className="conversation-meta">
                                    {new Date(conv.updated_at).toLocaleDateString('sv-SE')}
                                </div>

                                {activeConversation?.id === conv.id && (
                                    <div className="conversation-actions">
                                        {isAdmin && conv.status === 'open' && (
                                            <button
                                                onClick={(e) => { e.stopPropagation(); setShowResolveConfirm(conv.id); }}
                                                className="action-btn resolve"
                                                title="Markera som löst"
                                            >
                                                <CheckCircle size={14} />
                                            </button>
                                        )}
                                        <button
                                            onClick={(e) => { e.stopPropagation(); setShowDeleteConfirm(conv.id); }}
                                            className="action-btn delete"
                                            title="Ta bort"
                                        >
                                            <Trash2 size={14} />
                                        </button>
                                    </div>
                                )}
                            </div>
                        ))
                    )}
                </div>

                {/* Chat Panel */}
                <div className="chat-panel">
                    {activeConversation ? (
                        <>
                            <div className="chat-header">
                                <h2>{activeConversation.subject}</h2>
                                {activeConversation.product_name && (
                                    <div className="product-link">Produkt: {activeConversation.product_name}</div>
                                )}
                                {activeConversation.status === 'closed' && (
                                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.25rem', fontSize: '0.75rem', color: '#10b981', marginTop: '0.25rem' }}>
                                        <CheckCircle size={12} /> Löst
                                    </span>
                                )}
                            </div>

                            <div className="chat-messages">
                                {messages.map(msg => {
                                    const isMine = (isAdmin && msg.sender_role === 'admin') || (!isAdmin && msg.sender_role === 'customer');
                                    return (
                                        <div key={msg.id} className={`message-wrapper ${isMine ? 'mine' : 'theirs'}`}>
                                            <div className="message-bubble">
                                                <div className="message-sender">
                                                    {msg.sender_name} • {new Date(msg.created_at).toLocaleTimeString('sv-SE', { hour: '2-digit', minute: '2-digit' })}
                                                </div>
                                                <div className="message-content">{msg.content}</div>
                                            </div>
                                        </div>
                                    );
                                })}
                                <div ref={messagesEndRef} />
                            </div>

                            {activeConversation.status !== 'closed' ? (
                                <form onSubmit={handleSendMessage} className="chat-input-area">
                                    <input
                                        type="text"
                                        value={newMessage}
                                        onChange={(e) => setNewMessage(e.target.value)}
                                        placeholder="Skriv ett meddelande..."
                                    />
                                    <button type="submit" disabled={sending || !newMessage.trim()} className="msg-btn primary">
                                        <Send size={18} />
                                    </button>
                                </form>
                            ) : (
                                <div className="resolved-banner">
                                    Detta ärende är markerat som löst. Kontakta oss gärna igen om du har fler frågor.
                                </div>
                            )}
                        </>
                    ) : (
                        <div className="empty-state">
                            <MessageCircle size={64} />
                            <p>Välj en konversation</p>
                        </div>
                    )}
                </div>
            </div>

            {/* Delete Confirmation Modal */}
            {showDeleteConfirm !== null && (
                <div className="modal-overlay">
                    <div className="modal-content">
                        <div className="modal-header danger">
                            <AlertTriangle size={24} />
                            <span>Ta bort konversation?</span>
                        </div>
                        <p className="modal-text">
                            Detta kommer permanent radera konversationen och alla meddelanden.
                        </p>
                        <div className="modal-actions">
                            <button onClick={() => setShowDeleteConfirm(null)} className="msg-btn">
                                Avbryt
                            </button>
                            <button onClick={() => handleDeleteConversation(showDeleteConfirm)} className="msg-btn danger">
                                Ta bort
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Resolve Confirmation Modal */}
            {showResolveConfirm !== null && (
                <div className="modal-overlay">
                    <div className="modal-content">
                        <div className="modal-header success">
                            <CheckCircle size={24} />
                            <span>Markera som löst?</span>
                        </div>
                        <p className="modal-text">
                            Kunden kommer få ett mejl att ärendet är löst. Konversationen döljs från din vy.
                        </p>
                        <div className="modal-actions">
                            <button onClick={() => setShowResolveConfirm(null)} className="msg-btn">
                                Avbryt
                            </button>
                            <button onClick={() => handleResolveConversation(showResolveConfirm)} className="msg-btn success">
                                Markera löst
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
