import React, { useState, useEffect, useRef } from 'react';
import { useForm, router } from '@inertiajs/react';
import { AdminLayout } from '../AdminLayout';
import { SEOHead } from '@/components/SEOHead';
import {
    MessageSquare,
    Send,
    CheckCircle2,
    XCircle,
    Search,
    User,
    UserPlus,
    LogOut,
    Mail,
    Sparkles,
    ShieldAlert,
    Building2,
    Users,
    Info,
    Loader2,
    Check,
    Copy,
    Target,
    Cpu,
    FileText,

} from 'lucide-react';
import { playNotificationSound } from '@/lib/sound';
import { toast } from 'sonner';
import { FormattedChatMessage } from '@/Components/FormattedChatMessage';


interface ChatDepartment {
    id: number;
    name: string;
    slug: string;
    description?: string;
}

interface StaffUser {
    id: number;
    name: string;
    email: string;
    role: string;
    avatar?: string;
}

interface ChatMessage {
    id: number;
    sender_type: 'visitor' | 'admin';
    sender_name: string;
    message: string;
    created_at: string;
}

interface ChatSession {
    id: number;
    session_token: string;
    department_id?: number;
    department?: ChatDepartment;
    visitor_name: string;
    visitor_email: string;
    status: 'active' | 'closed';
    ip?: string;
    user_agent?: string;
    last_activity_at: string;
    unread_count?: number;
    messages: ChatMessage[];
    active_participants?: StaffUser[];
}

interface CurrentUser {
    id: number;
    name: string;
    email: string;
    role: string;
    is_super_admin: boolean;
}

interface ChatIndexProps {
    sessions: ChatSession[];
    departments: ChatDepartment[];
    staffMembers: StaffUser[];
    currentUser: CurrentUser;
}

export default function Index({
    sessions = [],
    departments = [],
    staffMembers = [],
    currentUser,
}: ChatIndexProps) {
    const [selectedSessionId, setSelectedSessionId] = useState<number | null>(
        sessions.length > 0 ? sessions[0].id : null
    );
    const [searchQuery, setSearchQuery] = useState('');
    const [departmentFilter, setDepartmentFilter] = useState<string>('all');
    const [statusFilter, setStatusFilter] = useState<string>('all');
    const [sessionList, setSessionList] = useState<ChatSession[]>(sessions);
    const [currentMessages, setCurrentMessages] = useState<ChatMessage[]>([]);
    const [replyText, setReplyText] = useState('');
    const [isSending, setIsSending] = useState(false);

    // Modals
    const [showInviteModal, setShowInviteModal] = useState(false);
    const [selectedInviteUserId, setSelectedInviteUserId] = useState<number | ''>('');
    const [isInviting, setIsInviting] = useState(false);

    const [showTranscriptModal, setShowTranscriptModal] = useState(false);
    const [transcriptEmail, setTranscriptEmail] = useState('');
    const [transcriptNotes, setTranscriptNotes] = useState('');
    const [isSendingTranscript, setIsSendingTranscript] = useState(false);

    // AI Summary Modal & State
    const [showAiSummaryModal, setShowAiSummaryModal] = useState(false);
    const [isSummarizing, setIsSummarizing] = useState(false);
    const [aiSummaryData, setAiSummaryData] = useState<any>(null);
    const [hasCopiedSummary, setHasCopiedSummary] = useState(false);
    const [visitorTyping, setVisitorTyping] = useState(false);

    const messagesEndRef = useRef<HTMLDivElement>(null);
    const prevMsgLength = useRef<number>(0);
    const lastAdminTypingSent = useRef<number>(0);


    const selectedSession = sessionList.find((s) => s.id === selectedSessionId);

    const handleGenerateAiSummary = async () => {
        if (!selectedSession) return;
        setIsSummarizing(true);
        try {
            const res = await fetch(`/admin/chat/${selectedSession.id}/summarize`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
            });
            const json = await res.json();
            if (json.success && json.data) {
                setAiSummaryData(json.data);
                setShowAiSummaryModal(true);
                toast.success('AI conversation summary generated!');
            } else {
                toast.error(json.message || 'Could not generate summary.');
            }
        } catch (err: any) {
            toast.error('Network error generating AI summary.');
        } finally {
            setIsSummarizing(false);
        }
    };

    const copySummaryToClipboard = () => {
        if (!aiSummaryData || !selectedSession) return;
        const text = `Live Chat Summary - ${selectedSession.visitor_name || 'Visitor'} (${selectedSession.visitor_email || ''})
Department: ${selectedSession.department?.name || 'General Support'} | Status: ${selectedSession.status}
Visitor Intent: ${aiSummaryData.visitor_intent || 'N/A'}
Sentiment: ${aiSummaryData.sentiment || 'Neutral'}

Executive Summary:
${aiSummaryData.summary || ''}

Technologies / Scope:
${aiSummaryData.technologies_discussed?.join(', ') || 'N/A'}

Action Items:
${aiSummaryData.key_action_items?.map((item: string) => `- ${item}`).join('\n') || 'None'}

Contact Details: ${aiSummaryData.contact_details || 'N/A'}`;

        navigator.clipboard.writeText(text);
        setHasCopiedSummary(true);
        toast.success('Summary copied to clipboard!');
        setTimeout(() => setHasCopiedSummary(false), 2500);
    };


    useEffect(() => {
        setSessionList(sessions);
    }, [sessions]);

    useEffect(() => {
        if (selectedSession) {
            setCurrentMessages(selectedSession.messages || []);
            setTranscriptEmail(selectedSession.visitor_email || '');
        } else {
            setCurrentMessages([]);
        }
    }, [selectedSessionId]);

    // Polling active chat session every 3 seconds
    useEffect(() => {
        if (!selectedSessionId) return;

        const pollSession = async () => {
            try {
                const res = await fetch(`/admin/chat/${selectedSessionId}/poll`);
                const data = await res.json();
                if (data.success) {
                    const newMsgs: ChatMessage[] = data.messages || [];
                    if (newMsgs.length > prevMsgLength.current) {
                        const lastMsg = newMsgs[newMsgs.length - 1];
                        if (lastMsg && lastMsg.sender_type === 'visitor' && prevMsgLength.current > 0) {
                            playNotificationSound();
                            if (typeof Notification !== 'undefined' && Notification.permission === 'granted' && document.hidden) {
                                new Notification(`New message from ${data.session?.visitor_name || 'Visitor'}`, {
                                    body: lastMsg.message.substring(0, 120),
                                    icon: '/favicon.ico',
                                });
                            }
                        }
                    }
                    prevMsgLength.current = newMsgs.length;
                    setCurrentMessages(newMsgs);

                    setVisitorTyping(!!data.visitor_typing);
                    setSessionList((prev) =>
                        prev.map((s) =>
                            s.id === selectedSessionId
                                ? {
                                      ...s,
                                      status: data.session.status,
                                      department: data.session.department,
                                      active_participants: data.session.active_participants,
                                      unread_count: 0,
                                  }
                                : s
                        )
                    );
                }
            } catch (e) {
                console.error('Error polling chat messages', e);
            }
        };

        pollSession();
        const interval = setInterval(pollSession, 3000);
        return () => clearInterval(interval);
    }, [selectedSessionId]);

    const handleAdminTyping = (text: string) => {
        setReplyText(text);
        if (!selectedSessionId) return;

        const now = Date.now();
        if (now - lastAdminTypingSent.current > 2000) {
            lastAdminTypingSent.current = now;
            fetch(`/admin/chat/${selectedSessionId}/typing`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
            }).catch(() => {});
        }
    };


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

    // Filtering
    const filteredSessions = sessionList.filter((s) => {
        const matchesSearch =
            s.visitor_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
            s.visitor_email.toLowerCase().includes(searchQuery.toLowerCase());

        const matchesDepartment =
            departmentFilter === 'all' ||
            (s.department_id && String(s.department_id) === departmentFilter);

        const matchesStatus =
            statusFilter === 'all' || s.status === statusFilter;

        return matchesSearch && matchesDepartment && matchesStatus;
    });

    const isCurrentStaffActive = selectedSession?.active_participants?.some(
        (p) => p.id === currentUser?.id
    );

    const otherActiveStaffCount =
        selectedSession?.active_participants?.filter((p) => p.id !== currentUser?.id).length || 0;

    // Send Reply
    const handleSendReply = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!replyText.trim() || !selectedSessionId) return;

        const text = replyText.trim();
        setReplyText('');
        setIsSending(true);

        try {
            const res = await fetch(`/admin/chat/${selectedSessionId}/reply`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
                body: JSON.stringify({ message: text }),
            });
            const data = await res.json();
            if (data.success) {
                setCurrentMessages((prev) => [...prev, data.message]);
                if (data.session) {
                    setSessionList((prev) =>
                        prev.map((s) => (s.id === selectedSessionId ? { ...s, active_participants: data.session.active_participants } : s))
                    );
                }
            }
        } catch (e) {
            console.error('Failed to send admin reply', e);
        } finally {
            setIsSending(false);
        }
    };

    // Join Chat
    const handleJoinChat = async () => {
        if (!selectedSessionId) return;
        try {
            const res = await fetch(`/admin/chat/${selectedSessionId}/join`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
            });
            const data = await res.json();
            if (data.success) {
                toast.success('You joined the live chat session.');
                if (data.session) {
                    setSessionList((prev) =>
                        prev.map((s) => (s.id === selectedSessionId ? { ...s, active_participants: data.session.active_participants } : s))
                    );
                }
            } else {
                toast.error(data.error || 'Failed to join chat.');
            }
        } catch (e) {
            toast.error('Failed to join chat.');
        }
    };

    // Invite Staff
    const handleInviteStaff = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!selectedSessionId || !selectedInviteUserId) return;

        setIsInviting(true);
        try {
            const res = await fetch(`/admin/chat/${selectedSessionId}/invite`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
                body: JSON.stringify({ user_id: selectedInviteUserId }),
            });
            const data = await res.json();
            if (data.success) {
                toast.success('Staff member invited to the conversation.');
                setShowInviteModal(false);
                setSelectedInviteUserId('');
                if (data.session) {
                    setSessionList((prev) =>
                        prev.map((s) => (s.id === selectedSessionId ? { ...s, active_participants: data.session.active_participants } : s))
                    );
                }
            } else {
                toast.error(data.error || 'Failed to invite staff.');
            }
        } catch (e) {
            toast.error('Failed to invite staff.');
        } finally {
            setIsInviting(false);
        }
    };

    // Leave Chat
    const handleLeaveChat = async () => {
        if (!selectedSessionId) return;

        try {
            const res = await fetch(`/admin/chat/${selectedSessionId}/leave`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
            });
            const data = await res.json();
            if (data.success) {
                toast.success('You have left the conversation.');
                if (data.session) {
                    setSessionList((prev) =>
                        prev.map((s) => (s.id === selectedSessionId ? { ...s, active_participants: data.session.active_participants } : s))
                    );
                }
            } else {
                toast.error(data.error || 'Cannot leave chat right now.');
            }
        } catch (e) {
            toast.error('Failed to leave chat.');
        }
    };

    // Send Transcript Email
    const handleSendTranscript = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!selectedSessionId || !transcriptEmail.trim()) return;

        setIsSendingTranscript(true);
        try {
            const res = await fetch(`/admin/chat/${selectedSessionId}/send-transcript`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                },
                body: JSON.stringify({
                    recipient_email: transcriptEmail.trim(),
                    staff_notes: transcriptNotes.trim() || undefined,
                }),
            });
            const data = await res.json();
            if (data.success) {
                toast.success(data.message || 'Transcript emailed successfully!');
                setShowTranscriptModal(false);
                setTranscriptNotes('');
            } else {
                toast.error(data.error || 'Failed to send transcript email.');
            }
        } catch (e) {
            toast.error('Failed to dispatch transcript email.');
        } finally {
            setIsSendingTranscript(false);
        }
    };


    const handleToggleStatus = (sessionId: number) => {
        router.post(
            `/admin/chat/${sessionId}/toggle-status`,
            {},
            {
                preserveScroll: true,
                onSuccess: () => {
                    setSessionList((prev) =>
                        prev.map((s) =>
                            s.id === sessionId ? { ...s, status: s.status === 'closed' ? 'active' : 'closed' } : s
                        )
                    );
                },
            }
        );
    };

    return (
        <AdminLayout title="Live Chat Command Center">
            <SEOHead title="Live Chat Command Center | Tech in Soul Admin" description="Live multi-department chat inbox with staff collaboration and transcript emailing." />

            <div className="h-[calc(100vh-180px)] glass-card rounded-2xl border border-slate-800 flex overflow-hidden">
                {/* Left Sidebar - Chat Sessions List */}
                <div className="w-80 sm:w-96 border-r border-slate-800 flex flex-col bg-[#060B18]/70 shrink-0">
                    <div className="p-4 border-b border-slate-800 space-y-2.5">
                        <div className="flex items-center justify-between">
                            <h3 className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
                                <MessageSquare className="w-4 h-4 text-[#00F2FE]" /> Live Inbox
                            </h3>
                            <div className="flex items-center gap-1.5">
                                {typeof Notification !== 'undefined' && Notification.permission !== 'granted' && (
                                    <button
                                        type="button"
                                        onClick={() => {
                                            Notification.requestPermission().then((perm) => {
                                                if (perm === 'granted') {
                                                    toast.success('Desktop push notifications enabled!');
                                                }
                                            });
                                        }}
                                        className="text-[10px] font-bold text-[#00F2FE] hover:underline bg-[#00F2FE]/10 px-2 py-0.5 rounded-lg border border-[#00F2FE]/20"
                                        title="Enable browser push notifications for background alerts"
                                    >
                                        🔔 Alerts
                                    </button>
                                )}
                                <span className="text-[11px] text-slate-400 bg-[#0B132B] px-2.5 py-0.5 rounded-full border border-slate-800">
                                    {filteredSessions.length} Sessions
                                </span>
                            </div>
                        </div>


                        {/* Search */}
                        <div className="relative">
                            <Search className="w-3.5 h-3.5 text-slate-500 absolute left-3 top-2.5" />
                            <input
                                type="text"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                placeholder="Search name or email..."
                                className="w-full bg-[#0B132B] border border-slate-800 rounded-xl pl-9 pr-3 py-1.5 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-[#00F2FE]"
                            />
                        </div>

                        {/* Filter Bar */}
                        <div className="grid grid-cols-2 gap-2 text-[11px]">
                            <select
                                value={departmentFilter}
                                onChange={(e) => setDepartmentFilter(e.target.value)}
                                className="bg-[#0B132B] border border-slate-800 rounded-lg px-2 py-1 text-slate-300 focus:outline-none focus:border-[#00F2FE]"
                            >
                                <option value="all">All Departments</option>
                                {departments.map((d) => (
                                    <option key={d.id} value={String(d.id)}>
                                        {d.name}
                                    </option>
                                ))}
                            </select>

                            <select
                                value={statusFilter}
                                onChange={(e) => setStatusFilter(e.target.value)}
                                className="bg-[#0B132B] border border-slate-800 rounded-lg px-2 py-1 text-slate-300 focus:outline-none focus:border-[#00F2FE]"
                            >
                                <option value="all">All Statuses</option>
                                <option value="active">Active Only</option>
                                <option value="closed">Closed / Solved</option>
                            </select>
                        </div>
                    </div>

                    <div className="flex-grow overflow-y-auto divide-y divide-slate-800/50">
                        {filteredSessions.length === 0 ? (
                            <div className="p-8 text-center text-slate-400 text-xs">No chat sessions match your filters.</div>
                        ) : (
                            filteredSessions.map((session) => {
                                const isSelected = session.id === selectedSessionId;
                                const lastMsg = session.messages?.[session.messages.length - 1];

                                return (
                                    <button
                                        key={session.id}
                                        onClick={() => setSelectedSessionId(session.id)}
                                        className={`w-full text-left p-3.5 transition-all flex items-start justify-between gap-2.5 ${
                                            isSelected ? 'bg-[#00F2FE]/10 border-l-4 border-l-[#00F2FE]' : 'hover:bg-slate-800/30'
                                        }`}
                                    >
                                        <div className="min-w-0 flex-grow">
                                            <div className="flex items-center gap-1.5 flex-wrap">
                                                <h4 className="text-xs font-bold text-white truncate">{session.visitor_name}</h4>
                                                {session.department && (
                                                    <span className="text-[9px] text-[#00F2FE] bg-[#00F2FE]/10 border border-[#00F2FE]/20 px-1.5 py-0.2 rounded">
                                                        {session.department.name}
                                                    </span>
                                                )}
                                                {session.status === 'closed' ? (
                                                    <span className="text-[9px] text-slate-400 bg-slate-800 px-1.5 py-0.2 rounded">Closed</span>
                                                ) : (
                                                    <span className="text-[9px] text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-1.5 py-0.2 rounded">Active</span>
                                                )}
                                            </div>
                                            <p className="text-[11px] text-slate-400 truncate mt-0.5">{session.visitor_email}</p>
                                            {lastMsg && (
                                                <p className="text-[10px] text-slate-500 truncate mt-1 italic">
                                                    "{lastMsg.message}"
                                                </p>
                                            )}
                                        </div>

                                        {session.unread_count && session.unread_count > 0 ? (
                                            <span className="px-2 py-0.5 rounded-full bg-[#00F2FE] text-[#060B18] font-extrabold text-[10px] shrink-0">
                                                {session.unread_count}
                                            </span>
                                        ) : null}
                                    </button>
                                );
                            })
                        )}
                    </div>
                </div>

                {/* Right Chat Thread View */}
                <div className="flex-grow flex flex-col bg-[#0B132B]/40">
                    {selectedSession ? (
                        <>
                            {/* Thread Header with Staff Collaboration Actions */}
                            <div className="p-3.5 border-b border-slate-800 bg-[#0B132B]/90 flex flex-wrap items-center justify-between gap-3">
                                <div>
                                    <div className="flex items-center gap-2 flex-wrap">
                                        <h3 className="text-sm font-bold text-white flex items-center gap-2">
                                            {selectedSession.visitor_name}
                                        </h3>
                                        <span className="text-xs text-slate-400">({selectedSession.visitor_email})</span>
                                        {selectedSession.department && (
                                            <span className="text-[10px] font-bold text-[#00F2FE] bg-[#00F2FE]/10 border border-[#00F2FE]/30 px-2 py-0.5 rounded-full flex items-center gap-1">
                                                <Building2 className="w-3 h-3" /> {selectedSession.department.name}
                                            </span>
                                        )}
                                    </div>
                                    <p className="text-[10px] text-slate-400 flex items-center gap-2.5 mt-0.5">
                                        <span>IP: {selectedSession.ip || 'Unknown'}</span>
                                        <span>•</span>
                                        <span>Last Active: {new Date(selectedSession.last_activity_at).toLocaleTimeString()}</span>
                                    </p>
                                </div>

                                {/* Actions Bar */}
                                <div className="flex items-center gap-2 flex-wrap">
                                    {/* Active Staff List */}
                                    <div className="flex items-center -space-x-1.5 mr-1" title="Active Staff in this chat">
                                        {selectedSession.active_participants && selectedSession.active_participants.length > 0 ? (
                                            selectedSession.active_participants.map((staff) => (
                                                <div
                                                    key={staff.id}
                                                    title={`Staff: ${staff.name}`}
                                                    className="w-6 h-6 rounded-full bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] font-bold text-[10px] flex items-center justify-center border-2 border-[#0B132B]"
                                                >
                                                    {staff.name.substring(0, 2).toUpperCase()}
                                                </div>
                                            ))
                                        ) : (
                                            <span className="text-[10px] text-slate-500 italic">No staff assigned</span>
                                        )}
                                    </div>

                                    {/* Join Button */}
                                    {!isCurrentStaffActive && (
                                        <button
                                            onClick={handleJoinChat}
                                            className="px-2.5 py-1.5 bg-[#00F2FE]/15 hover:bg-[#00F2FE]/25 text-[#00F2FE] border border-[#00F2FE]/30 rounded-lg text-xs font-bold transition-all flex items-center gap-1"
                                        >
                                            <UserPlus className="w-3.5 h-3.5" /> Join Chat
                                        </button>
                                    )}

                                    {/* Invite Button */}
                                    <button
                                        onClick={() => setShowInviteModal(true)}
                                        className="px-2.5 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 rounded-lg text-xs font-medium transition-all flex items-center gap-1"
                                    >
                                        <Users className="w-3.5 h-3.5" /> Invite
                                    </button>

                                    {/* Leave Button */}
                                    {isCurrentStaffActive && (
                                        <button
                                            onClick={handleLeaveChat}
                                            title={
                                                otherActiveStaffCount > 0 || currentUser.is_super_admin
                                                    ? 'Leave this chat session'
                                                    : 'Another staff must join before you can leave'
                                            }
                                            className="px-2.5 py-1.5 bg-rose-500/10 hover:bg-rose-500/20 text-rose-300 border border-rose-500/20 rounded-lg text-xs font-medium transition-all flex items-center gap-1"
                                        >
                                            <LogOut className="w-3.5 h-3.5" /> Leave
                                        </button>
                                    )}

                                    {/* AI Summary Button */}
                                    <button
                                        onClick={handleGenerateAiSummary}
                                        disabled={isSummarizing}
                                        className="px-2.5 py-1.5 bg-gradient-to-r from-purple-600/20 to-indigo-600/20 hover:from-purple-600/30 hover:to-indigo-600/30 text-purple-300 border border-purple-500/30 rounded-lg text-xs font-bold transition-all flex items-center gap-1 shadow-sm disabled:opacity-50"
                                    >
                                        {isSummarizing ? (
                                            <>
                                                <Loader2 className="w-3.5 h-3.5 animate-spin text-purple-400" /> Analyzing...
                                            </>
                                        ) : (
                                            <>
                                                <Sparkles className="w-3.5 h-3.5 text-yellow-300" /> AI Summary
                                            </>
                                        )}
                                    </button>

                                    {/* Email Transcript Button */}
                                    <button
                                        onClick={() => setShowTranscriptModal(true)}
                                        className="px-2.5 py-1.5 bg-indigo-500/15 hover:bg-indigo-500/25 text-indigo-300 border border-indigo-500/30 rounded-lg text-xs font-medium transition-all flex items-center gap-1"
                                    >
                                        <Mail className="w-3.5 h-3.5" /> Send Transcript
                                    </button>

                                    {/* Toggle Active/Closed */}
                                    <button
                                        onClick={() => handleToggleStatus(selectedSession.id)}
                                        className={`px-2.5 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1 ${
                                            selectedSession.status === 'closed'
                                                ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 hover:bg-emerald-500/30'
                                                : 'bg-rose-500/20 text-rose-300 border border-rose-500/30 hover:bg-rose-500/30'
                                        }`}
                                    >
                                        {selectedSession.status === 'closed' ? (
                                            <>
                                                <CheckCircle2 className="w-3.5 h-3.5" /> Re-open
                                            </>
                                        ) : (
                                            <>
                                                <XCircle className="w-3.5 h-3.5" /> Close
                                            </>
                                        )}
                                    </button>
                                </div>
                            </div>


                            {/* Thread Messages */}
                            <div className="flex-grow p-6 overflow-y-auto space-y-3.5">
                                {currentMessages.length === 0 ? (
                                    <div className="text-center text-slate-400 text-xs py-12">No messages in this chat session yet.</div>
                                ) : (
                                    currentMessages.map((msg) => {
                                        const isAdmin = msg.sender_type === 'admin';
                                        const isSystem = msg.sender_name === 'System' || msg.message.startsWith('⚑') || msg.message.startsWith('👋') || msg.message.startsWith('📩') || msg.message.startsWith('🚪') || msg.message.startsWith('📧');

                                        if (isSystem) {
                                            return (
                                                <div key={msg.id} className="text-center my-2">
                                                    <span className="text-[11px] text-slate-400 bg-[#060B18]/90 border border-slate-800 px-3.5 py-1 rounded-full inline-block shadow-sm">
                                                        {msg.message} &bull; <span className="text-[10px] text-slate-500">{new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                                                    </span>
                                                </div>
                                            );
                                        }

                                        return (
                                            <div
                                                key={msg.id}
                                                className={`flex flex-col ${isAdmin ? 'items-end' : 'items-start'}`}
                                            >
                                                <div className="flex items-center gap-2 mb-1">
                                                    <span className="text-[11px] font-bold text-slate-300">{msg.sender_name}</span>
                                                    <span className="text-[10px] text-slate-400">
                                                        {new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                                    </span>
                                                </div>
                                                <div
                                                    className={`max-w-[75%] px-4 py-3 rounded-2xl text-xs leading-relaxed ${
                                                        isAdmin
                                                            ? 'bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] font-medium rounded-tr-none shadow-md shadow-cyan-500/10'
                                                            : 'bg-[#1C2541] text-slate-100 border border-slate-700/60 rounded-tl-none shadow-md shadow-black/20'
                                                    }`}
                                                >
                                                    <FormattedChatMessage content={msg.message} isVisitor={isAdmin} />
                                                </div>

                                            </div>
                                        );
                                    })
                                )}
                                {visitorTyping && selectedSession && (
                                    <div className="flex items-center gap-2 px-3.5 py-2 bg-[#1C2541] border border-amber-500/30 rounded-2xl rounded-tl-none text-xs text-amber-300 animate-pulse w-fit shadow-md">
                                        <div className="flex gap-1 items-center">
                                            <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-bounce" style={{ animationDelay: '0ms' }} />
                                            <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-bounce" style={{ animationDelay: '150ms' }} />
                                            <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-bounce" style={{ animationDelay: '300ms' }} />
                                        </div>
                                        <span className="text-[11px] font-medium text-slate-200">{selectedSession.visitor_name || 'Visitor'} is typing...</span>
                                    </div>
                                )}
                                <div ref={messagesEndRef} />
                            </div>

                            {/* Thread Reply Input Box */}
                            <form onSubmit={handleSendReply} className="p-3.5 border-t border-slate-800 bg-[#060B18]/80 flex items-center gap-3">
                                <input
                                    type="text"
                                    value={replyText}
                                    onChange={(e) => handleAdminTyping(e.target.value)}
                                    placeholder={`Reply as ${currentUser?.name || 'Support Agent'}...`}
                                    className="flex-grow bg-[#0B132B] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                />
                                <button
                                    type="submit"
                                    disabled={!replyText.trim() || isSending}
                                    className="btn-aqua px-5 py-2.5 rounded-xl font-bold text-xs flex items-center gap-2 shrink-0 disabled:opacity-40"
                                >
                                    <Send className="w-3.5 h-3.5" /> Send Reply
                                </button>
                            </form>

                        </>
                    ) : (
                        <div className="flex-grow flex flex-col items-center justify-center text-slate-400 text-xs space-y-2">
                            <MessageSquare className="w-10 h-10 text-[#00F2FE]/40" />
                            <p>Select a live chat session from the left inbox to view conversation.</p>
                        </div>
                    )}
                </div>
            </div>

            {/* Modal: Invite Staff */}
            {showInviteModal && selectedSession && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 animate-in fade-in">
                    <div className="bg-[#0B132B] border border-slate-800 w-full max-w-md rounded-2xl p-6 shadow-2xl space-y-4">
                        <div className="flex items-center justify-between border-b border-slate-800 pb-3">
                            <h4 className="text-sm font-bold text-white flex items-center gap-2">
                                <Users className="w-4 h-4 text-[#00F2FE]" /> Invite Staff to Chat #{selectedSession.id}
                            </h4>
                            <button onClick={() => setShowInviteModal(false)} className="text-slate-400 hover:text-white text-xs">
                                ✕
                            </button>
                        </div>

                        <form onSubmit={handleInviteStaff} className="space-y-4">
                            <div>
                                <label className="text-xs font-bold text-slate-300 block mb-1.5">Select Staff Member</label>
                                <select
                                    value={selectedInviteUserId}
                                    onChange={(e) => setSelectedInviteUserId(Number(e.target.value))}
                                    required
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                >
                                    <option value="">-- Choose a colleague --</option>
                                    {staffMembers
                                        .filter((s) => s.id !== currentUser.id)
                                        .map((staff) => (
                                            <option key={staff.id} value={staff.id}>
                                                {staff.name} ({staff.email}) — {staff.role}
                                            </option>
                                        ))}
                                </select>
                            </div>

                            <p className="text-[11px] text-slate-400">
                                The invited colleague will gain full access to view, participate in, and reply to this conversation.
                            </p>

                            <div className="flex flex-col-reverse sm:flex-row items-center justify-end gap-2.5 pt-2 border-t border-slate-800">
                                <button
                                    type="button"
                                    onClick={() => setShowInviteModal(false)}
                                    className="w-full sm:w-auto px-4 py-2 rounded-xl text-xs font-semibold bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 transition-all text-center"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    disabled={!selectedInviteUserId || isInviting}
                                    className="btn-aqua w-full sm:w-auto px-4 py-2 rounded-xl text-xs font-bold flex items-center justify-center gap-1.5 disabled:opacity-50"
                                >
                                    {isInviting ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <UserPlus className="w-3.5 h-3.5" />}
                                    Invite Staff
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Modal: Send Transcript */}
            {showTranscriptModal && selectedSession && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 animate-in fade-in">
                    <div className="bg-[#0B132B] border border-slate-800 w-full max-w-md rounded-2xl p-6 shadow-2xl space-y-4">
                        <div className="flex items-center justify-between border-b border-slate-800 pb-3">
                            <h4 className="text-sm font-bold text-white flex items-center gap-2">
                                <Mail className="w-4 h-4 text-[#00F2FE]" /> Email Chat Transcript
                            </h4>
                            <button onClick={() => setShowTranscriptModal(false)} className="text-slate-400 hover:text-white text-xs">
                                ✕
                            </button>
                        </div>

                        <form onSubmit={handleSendTranscript} className="space-y-4">
                            <div>
                                <label className="text-xs font-bold text-slate-300 block mb-1.5">Recipient Email Address *</label>
                                <input
                                    type="email"
                                    required
                                    value={transcriptEmail}
                                    onChange={(e) => setTranscriptEmail(e.target.value)}
                                    placeholder="visitor@company.com"
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                />
                            </div>

                            <div>
                                <label className="text-xs font-bold text-slate-300 block mb-1.5">Staff Notes / Summary (Optional)</label>
                                <textarea
                                    rows={3}
                                    value={transcriptNotes}
                                    onChange={(e) => setTranscriptNotes(e.target.value)}
                                    placeholder="Add any internal note or wrap-up message to accompany the transcript..."
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE] resize-none"
                                />
                            </div>

                            <p className="text-[11px] text-slate-400">
                                This will send an official, styled email containing the complete conversation timeline, timestamps, and department info.
                            </p>

                            <div className="flex flex-col-reverse sm:flex-row items-center justify-end gap-2.5 pt-2 border-t border-slate-800">
                                <button
                                    type="button"
                                    onClick={() => setShowTranscriptModal(false)}
                                    className="w-full sm:w-auto px-4 py-2 rounded-xl text-xs font-semibold bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 transition-all text-center"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    disabled={!transcriptEmail.trim() || isSendingTranscript}
                                    className="btn-aqua w-full sm:w-auto px-4 py-2 rounded-xl text-xs font-bold flex items-center justify-center gap-1.5 disabled:opacity-50"
                                >
                                    {isSendingTranscript ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Send className="w-3.5 h-3.5" />}
                                    Send Transcript Email
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Modal: AI Conversation Intelligence Summary */}
            {showAiSummaryModal && selectedSession && aiSummaryData && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-md p-4 animate-in fade-in">
                    <div className="bg-[#0B132B] border border-purple-500/30 w-full max-w-2xl rounded-3xl p-6 sm:p-8 shadow-2xl space-y-6 relative overflow-hidden max-h-[90vh] flex flex-col">
                        <div className="absolute top-0 right-0 w-64 h-64 bg-purple-600/10 rounded-full blur-3xl -z-0 pointer-events-none" />

                        {/* Modal Header */}
                        <div className="flex items-center justify-between border-b border-slate-800 pb-4 relative z-10 shrink-0">
                            <div className="flex items-center gap-3">
                                <div className="p-2.5 rounded-2xl bg-gradient-to-tr from-purple-600/20 to-indigo-600/20 text-purple-300 border border-purple-500/30">
                                    <Sparkles className="w-5 h-5 text-yellow-300" />
                                </div>
                                <div>
                                    <h3 className="text-base font-bold text-white flex items-center gap-2">
                                        Live Chat AI Summary
                                        <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-purple-500/20 text-purple-300 border border-purple-500/30">
                                            {aiSummaryData.sentiment || 'Analysis'}
                                        </span>
                                    </h3>
                                    <p className="text-xs text-slate-400 font-mono">
                                        Visitor: {selectedSession.visitor_name} ({selectedSession.visitor_email || 'No email'})
                                    </p>
                                </div>
                            </div>
                            <button
                                onClick={() => setShowAiSummaryModal(false)}
                                className="w-8 h-8 rounded-full bg-slate-800/80 hover:bg-slate-700 text-slate-400 hover:text-white flex items-center justify-center text-xs transition-colors"
                            >
                                ✕
                            </button>
                        </div>

                        {/* Modal Content Scroll Area */}
                        <div className="overflow-y-auto space-y-5 pr-1 relative z-10 text-xs">
                            {/* Executive Summary Callout */}
                            <div className="p-4 rounded-2xl bg-[#060B18] border border-slate-800 space-y-2">
                                <div className="flex items-center gap-2 text-[#00F2FE] font-bold text-[11px] uppercase tracking-wider">
                                    <FileText className="w-4 h-4" /> Executive Summary
                                </div>
                                <p className="text-slate-300 leading-relaxed text-xs sm:text-sm">
                                    {aiSummaryData.summary}
                                </p>
                            </div>

                            {/* Core Intent & Sentiment Grid */}
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div className="p-4 rounded-2xl bg-[#060B18] border border-slate-800 space-y-1.5">
                                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500 flex items-center gap-1.5">
                                        <Target className="w-3.5 h-3.5 text-cyan-400" /> Visitor Core Intent
                                    </span>
                                    <p className="text-xs font-semibold text-white">
                                        {aiSummaryData.visitor_intent || 'General inquiry regarding services'}
                                    </p>
                                </div>

                                <div className="p-4 rounded-2xl bg-[#060B18] border border-slate-800 space-y-1.5">
                                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500 flex items-center gap-1.5">
                                        <Info className="w-3.5 h-3.5 text-purple-400" /> Sentiment & Engagement
                                    </span>
                                    <p className="text-xs font-semibold text-purple-300 capitalize">
                                        {aiSummaryData.sentiment || 'Inquiring'}
                                    </p>
                                </div>
                            </div>

                            {/* Technologies Discussed */}
                            {aiSummaryData.technologies_discussed && aiSummaryData.technologies_discussed.length > 0 && (
                                <div className="space-y-2">
                                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                                        <Cpu className="w-3.5 h-3.5 text-[#00F2FE]" /> Key Technologies / Scope Mentioned
                                    </span>
                                    <div className="flex flex-wrap gap-2">
                                        {aiSummaryData.technologies_discussed.map((tech: string, i: number) => (
                                            <span
                                                key={i}
                                                className="px-2.5 py-1 rounded-lg bg-[#060B18] border border-cyan-500/30 text-[#00F2FE] text-xs font-semibold"
                                            >
                                                {tech}
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Action Items */}
                            {aiSummaryData.key_action_items && aiSummaryData.key_action_items.length > 0 && (
                                <div className="space-y-2.5">
                                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                                        <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400" /> Recommended Action Items
                                    </span>
                                    <ul className="space-y-1.5">
                                        {aiSummaryData.key_action_items.map((item: string, i: number) => (
                                            <li key={i} className="flex items-start gap-2 text-slate-300 p-2.5 rounded-xl bg-[#060B18] border border-slate-800">
                                                <span className="w-4 h-4 rounded-full bg-emerald-500/20 text-emerald-400 text-[10px] font-bold flex items-center justify-center shrink-0 mt-0.5">
                                                    {i + 1}
                                                </span>
                                                <span className="leading-snug">{item}</span>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            )}
                        </div>

                        {/* Modal Footer Actions */}
                        <div className="flex flex-col-reverse sm:flex-row items-center justify-between gap-3 pt-4 border-t border-slate-800 relative z-10 shrink-0">
                            <button
                                type="button"
                                onClick={() => setShowAiSummaryModal(false)}
                                className="w-full sm:w-auto px-5 py-2.5 rounded-xl text-xs font-semibold bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 transition-all text-center"
                            >
                                Close
                            </button>

                            <button
                                type="button"
                                onClick={copySummaryToClipboard}
                                className="btn-aqua w-full sm:w-auto px-5 py-2.5 rounded-xl text-xs font-bold flex items-center justify-center gap-2"
                            >
                                {hasCopiedSummary ? (
                                    <>
                                        <Check className="w-4 h-4 text-white" /> Copied to Clipboard!
                                    </>
                                ) : (
                                    <>
                                        <Copy className="w-4 h-4" /> Copy Structured Summary
                                    </>
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </AdminLayout>
    );
}


