'use client';

import { useState, useEffect, useRef } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import { useGet } from '@/hooks/use-get';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Headphones, Send, Loader2, RefreshCcw, History as HistoryIcon, MessagesSquare, XCircle } from 'lucide-react';
import axios from 'axios';
import { BASE_URL } from '@/utils/url';
import { USER_TOKEN_CL } from '@/utils/data/user-client';
import { toast } from '@/hooks/use-toast';
import { cn } from '@/lib/cn';
import { format } from 'date-fns';
import { ar, enUS } from 'date-fns/locale';

interface ResponseOption {
    id: number;
    support_question_id: number;
    response: string;
    suggestion: string;
    next_support_question_id: number | null;
}

interface ChatMessage {
    id: number;
    sender: 'system' | 'client';
    message: string;
    created_at: string;
}

export function SupportChat({ onBack, activeView }: { onBack?: () => void, activeView?: string }) {
    const t = useTranslations();
    const locale = useLocale();
    const isRtl = locale === 'ar';
    const { data: user } = useGet({ url: '/user' });
    const [sessionId, setSessionId] = useState<string>('');
    const [currentQuestionId, setCurrentQuestionId] = useState<number | null>(null);
    const [history, setHistory] = useState<{ type: 'system' | 'client'; text: string; options?: ResponseOption[] }[]>([]);
    const [isChatActive, setIsChatActive] = useState(false);
    const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
    const [inputMessage, setInputMessage] = useState('');
    const [isSending, setIsSending] = useState(false);
    const [isLoadingInitial, setIsLoadingInitial] = useState(true);
    const [chatId, setChatId] = useState<number | null>(null);
    const scrollBottomRef = useRef<HTMLDivElement>(null);

    const checkOpened = async () => {
        let foundTicket = false;
        try {
            const resp = await axios.get(`${BASE_URL}/support-sequences/opened`, {
                headers: { Authorization: `Bearer ${USER_TOKEN_CL()}` }
            });
            
            if (resp.data?.success && resp.data.ticket) {
                const ticket = resp.data.ticket;
                setChatId(ticket.id);
                if (ticket.session_id) {
                    setSessionId(ticket.session_id);
                }
                setIsChatActive(true);
                setChatMessages(resp.data.messages || []);
                foundTicket = true;
            } else {
                setIsChatActive(false);
            }
        } catch (error: any) {
            if (error.response?.status !== 404) {
                console.error("Error checking opened ticket", error);
            }
            setIsChatActive(false);
        } finally {
            if (!foundTicket) {
                const saved = sessionStorage.getItem('mw_support_session');
                if (saved) {
                    setSessionId(saved);
                } else {
                    const newId = `session_${Math.random().toString(36).substr(2, 9)}_${Date.now()}`;
                    sessionStorage.setItem('mw_support_session', newId);
                    setSessionId(newId);
                }
            }
            setIsLoadingInitial(false);
        }
    };

    // Initial check for opened ticket
    useEffect(() => {
        if (activeView === 'chat' || !activeView) {
            checkOpened();
        }
    }, [activeView]);

    // Polling for new messages
    useEffect(() => {
        const interval = setInterval(() => {
            if (isChatActive && (activeView === 'chat' || !activeView)) {
                checkOpened();
            }
        }, 5000); // 5 seconds
        return () => clearInterval(interval);
    }, [isChatActive, activeView]);

    const { data: startData } = useGet({
        url: '/support-sequences/start',
        props: { enabled: !isChatActive && !isLoadingInitial }
    });

    const { data: questionData } = useGet({
        url: currentQuestionId ? `/support-sequences/${currentQuestionId}` : '',
        props: { enabled: !!currentQuestionId }
    });

    useEffect(() => {
        if (!isChatActive && startData?.success && startData.data?.length > 0 && history.length === 0) {
            const first = startData.data[0];
            setHistory([{ type: 'system', text: first.question, options: first.responses }]);
            
            // If the very first question has no predefined options, immediately start chat mode
            // so the user can enter free text.
            if (!first.responses || first.responses.length === 0) {
                startChat();
            }
        }
    }, [startData, history.length, isChatActive]);

    useEffect(() => {
        if (questionData?.success) {
            const next = questionData.data;
            setHistory(prev => [...prev, { type: 'system', text: next.question, options: next.responses }]);
            
            // If a sequenced question arrives with no predefined options to click, an open-ended
            // response is expected. We must start the chat to show the text input form.
            if (!next.responses || next.responses.length === 0) {
                startChat();
            }
        }
    }, [questionData]);

    useEffect(() => {
        const timer = setTimeout(() => {
            if (scrollBottomRef.current) {
                scrollBottomRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
        }, 100);
        return () => clearTimeout(timer);
    }, [history, chatMessages, isChatActive, isSending]);

    const fullName = [user?.first_name, user?.fourth_name].filter(Boolean).join(' ') || user?.username || t('anonymous');

    const handleOptionClick = async (option: ResponseOption, questionText: string) => {
        setHistory(prev => {
            const newHistory = [...prev];
            if (newHistory.length > 0 && newHistory[newHistory.length - 1].type === 'system') {
                newHistory[newHistory.length - 1].options = undefined;
            }
            return [...newHistory, { type: 'client', text: option.response }];
        });

        try {
            await axios.post(`${BASE_URL}/support-sequences/ticket/send`, {
                session_id: sessionId,
                name: fullName,
                email: user?.email,
                question: questionText,
                response: option.response
            }, {
                headers: { Authorization: `Bearer ${USER_TOKEN_CL()}` }
            });
        } catch (error) {
            console.error('Failed to send ticket update', error);
        }

        if (option.next_support_question_id) {
            setCurrentQuestionId(option.next_support_question_id);
        } else {
            startChat();
        }
    };

    const startChat = async () => {
        setIsChatActive(true);
        try {
            const resp = await axios.post(`${BASE_URL}/support-sequences/chat/start`, {
                name: fullName,
                email: user?.email,
                session_id: sessionId
            }, {
                headers: { Authorization: `Bearer ${USER_TOKEN_CL()}` }
            });
            if (resp.data?.success) {
                setChatMessages(resp.data.messages || []);
                if (resp.data.id) setChatId(resp.data.id);
            }
        } catch (error) {
            console.error('Failed to start chat', error);
        }
    };

    const handleSendMessage = async () => {
        if (!inputMessage.trim() || isSending) return;
        setIsSending(true);
        const userMsg = inputMessage;
        setInputMessage('');

        try {
            const resp = await axios.post(`${BASE_URL}/support-sequences/chat/send`, {
                session_id: sessionId,
                message: userMsg
            }, {
                headers: { Authorization: `Bearer ${USER_TOKEN_CL()}` }
            });
            if (resp.data?.success) {
                setChatMessages(resp.data.messages);
            }
        } catch (error) {
            console.error('Failed to send message', error);
        } finally {
            setIsSending(false);
        }
    };

    const resetSupport = () => {
        const newId = `session_${Math.random().toString(36).substr(2, 9)}_${Date.now()}`;
        sessionStorage.setItem('mw_support_session', newId);
        setSessionId(newId);
        setHistory([]);
        setCurrentQuestionId(null);
        setIsChatActive(false);
        setChatMessages([]);
    };

    const handleCloseTicket = async () => {
        if (!chatId || isSending) return;
        setIsSending(true);
        try {
            const resp = await axios.post(`${BASE_URL}/support-sequences/ticket/${chatId}/close`, {}, {
                headers: { Authorization: `Bearer ${USER_TOKEN_CL()}` }
            });
            if (resp.data?.success) {
                toast({
                    title: isRtl ? "تم إغلاق التذكرة بنجاح" : "Ticket closed successfully",
                    variant: "success"
                });
                resetSupport();
            } else {
                toast({
                    title: isRtl ? "فشل إغلاق التذكرة" : "Failed to close ticket",
                    description: resp.data?.message,
                    variant: "destructive"
                });
            }
        } catch (error: any) {
            toast({
                title: isRtl ? "فشل إغلاق التذكرة" : "Failed to close ticket",
                description: error.response?.data?.message || error.message,
                variant: "destructive"
            });
        } finally {
            setIsSending(false);
        }
    };

    return (
        <Card className="w-full h-[700px] flex flex-col shadow-none rounded-xl border-zinc-200 overflow-hidden bg-white" dir={isRtl ? 'rtl' : 'ltr'}>
            <CardHeader className="bg-zinc-50/50 border-b border-zinc-200 flex flex-row items-center justify-between p-4 shrink-0">
                <div className="flex items-center gap-4">
                    <div className="bg-white p-2 rounded-lg border border-zinc-200 shadow-sm">
                        <Headphones className="size-6 text-purple-600" />
                    </div>
                    <div>
                        <CardTitle className="text-base font-bold text-zinc-900 tracking-tight">{t('routes.support')}</CardTitle>
                        <div className="flex items-center gap-1.5 ">
                            <span className="size-2 bg-emerald-500 rounded-full animate-pulse" />
                            <span className="text-[10px] font-bold text-emerald-600 uppercase tracking-widest">{t('custom.system-online')}</span>
                        </div>
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    {isChatActive && chatId && (
                        <Button 
                            variant="destructive" 
                            size="sm" 
                            onClick={handleCloseTicket}
                            disabled={isSending}
                            className="h-8 rounded-lg gap-2 text-[10px] font-black uppercase tracking-widest px-3 mr-2"
                        >
                            {isSending ? <Loader2 className="size-3 animate-spin" /> : <XCircle className="size-3" />}
                            {isRtl ? "إغلاق التذكرة" : "Close Ticket"}
                        </Button>
                    )}
                    <Button variant="ghost" size="icon" onClick={onBack} title={t('custom.view-history')} className="text-zinc-500 hover:text-zinc-900">
                        <HistoryIcon className="size-4" />
                    </Button>
                    <Button variant="ghost" size="icon" onClick={resetSupport} title="Reset Chat" className="text-zinc-500 hover:text-zinc-900">
                        <RefreshCcw className="size-4" />
                    </Button>
                </div>
            </CardHeader>

            <CardContent className="flex-1 overflow-hidden p-0 bg-white relative">
                <ScrollArea className="h-full px-6 py-8">
                    <div className="space-y-6">
                        {isLoadingInitial ? (
                            <div className="flex flex-col items-center justify-center py-20">
                                <Loader2 className="size-8 animate-spin text-primary-tw-400" />
                                <p className="text-zinc-400 text-xs mt-4 uppercase tracking-widest font-bold">Resuming Session...</p>
                            </div>
                        ) : !isChatActive && history.length === 0 ? (
                            <div className="flex flex-col items-center justify-center py-20 text-center animate-in fade-in zoom-in-95 duration-700">
                                <div className="bg-zinc-50 p-6 rounded-full mb-4 border border-zinc-100">
                                    <MessagesSquare className="size-8 text-zinc-200" />
                                </div>
                                <h3 className="text-zinc-900 font-bold text-lg">Mwaheb Smart Assistant</h3>
                                <p className="text-zinc-400 text-sm max-w-[240px]">How can we help you navigate our platform today?</p>
                            </div>
                        ) : null}

                        {!isLoadingInitial && (
                            <>
                                {/* SEQUENCE HISTORY */}
                                {history.map((item, idx) => (
                                    <div key={`hist-${idx}`} className={cn("flex flex-col gap-2", item.type === 'client' ? "items-end" : "items-start")}>
                                        <div className={cn(
                                            "max-w-[85%] rounded-2xl px-4 py-3 text-sm md:text-base",
                                            item.type === 'client' 
                                                ? "bg-primary-tw-600 text-white rounded-tr-none shadow-sm" 
                                                : "bg-zinc-50 text-zinc-700 rounded-tl-none border border-zinc-100"
                                        )}>
                                            <p className="leading-relaxed" dir="auto">{item.text}</p>
                                        </div>
                                        
                                        {item.options && (
                                            <div className="grid gap-2 mt-2 w-full max-w-[100%] animate-in fade-in slide-in-from-bottom-2 duration-300">
                                                {item.options.map((opt) => (
                                                    <button
                                                        key={opt.id}
                                                        onClick={() => handleOptionClick(opt, item.text)}
                                                        className="flex flex-col items-start p-4 bg-white border border-zinc-200 hover:border-primary-tw-400 hover:bg-zinc-50 rounded-xl transition-all text-start shadow-sm"
                                                        dir="auto"
                                                    >
                                                        <span className="font-bold text-zinc-900 text-sm">{opt.response}</span>
                                                        {opt.suggestion && (
                                                            <span className="text-[10px] uppercase font-bold text-zinc-400 mt-1">{opt.suggestion}</span>
                                                        )}
                                                    </button>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                ))}

                                {/* CHAT MESSAGES */}
                                {isChatActive && chatMessages.map((msg, idx) => (
                                    <div key={`chat-${idx}`} className={cn("flex flex-col gap-1.5", msg.sender === 'client' ? "items-end" : "items-start")}>
                                        <div className={cn(
                                            "max-w-[85%] rounded-2xl px-4 py-3 text-sm md:text-base",
                                            msg.sender === 'client' 
                                                ? "bg-primary-tw-600 text-white rounded-tr-none shadow-sm" 
                                                : "bg-zinc-100 text-zinc-700 rounded-tl-none border border-zinc-200"
                                        )}>
                                            <p className="leading-relaxed" dir="auto">{msg.message}</p>
                                        </div>
                                        <span className="text-[9px] font-medium text-zinc-400 px-1 uppercase tracking-widest">
                                            {new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                        </span>
                                    </div>
                                ))}
                            </>
                        )}

                        {isSending && (
                            <div className="flex items-center gap-2 text-zinc-400 p-2 bg-zinc-50 rounded-full w-fit px-4 border border-zinc-100 animate-pulse">
                                <Loader2 className="size-3 animate-spin" />
                                <span className="text-[10px] font-bold uppercase tracking-widest">{t('custom.sending')}</span>
                            </div>
                        )}
                        <div ref={scrollBottomRef} />
                    </div>
                </ScrollArea>
            </CardContent>

            {isChatActive && (
                <CardFooter className="p-4 bg-zinc-50/50 border-t border-zinc-200 static block">
                    <div className="flex w-full items-center gap-3">
                        <Input
                            placeholder={t('placeholder.content')}
                            value={inputMessage}
                            onChange={(e) => setInputMessage(e.target.value)}
                            onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
                            className="bg-white border-zinc-200 focus-visible:ring-primary-tw-400 rounded-xl px-5 h-12 flex-1"
                        />
                        <Button 
                            size="icon" 
                            onClick={handleSendMessage} 
                            disabled={!inputMessage.trim() || isSending}
                            className="bg-primary-tw-600 hover:bg-primary-tw-700 size-12 rounded-xl shadow-md shadow-primary-tw-100 transition-all active:scale-95 rotate-180 flex-shrink-0"
                        >
                            {isSending ? <Loader2 className="size-5 animate-spin" /> : <Send className={cn("size-5", isRtl ? "rotate-90" : "rotate-270")} />}
                        </Button>
                    </div>
                </CardFooter>
            )}
        </Card>
    );
}

