'use client';

import { useState, useEffect, useRef } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import { useGet } from '@/hooks/use-get';
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { 
    History, 
    MessageSquare, 
    ChevronRight, 
    ChevronLeft, 
    Clock, 
    Calendar,
    User,
    Mail,
    SearchX,
    FileText,
    MessagesSquare,
    ArrowUpRight,
    XCircle,
    Loader2,
    ChevronDown,
    ChevronUp,
    Send
} from 'lucide-react';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/cn';
import { format } from 'date-fns';
import { ar, enUS } from 'date-fns/locale';
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';

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

interface SupportResponse {
    question: string;
    response: string;
}

interface SupportTicket {
    id: number;
    name: string;
    email: string;
    responses: SupportResponse[];
    messages: SupportMessage[];
    is_close: boolean;
    session_id: string | null;
    created_at: string;
    updated_at: string;
}

export function SupportHistory({ 
    onResume,
    activeView
}: { 
    onResume?: () => void;
    activeView?: string;
}) {
    const t = useTranslations();
    const locale = useLocale();
    const isRtl = locale === 'ar';
    const [selectedTicket, setSelectedTicket] = useState<SupportTicket | null>(null);
    const [isClosing, setIsClosing] = useState(false);
    const [isSending, setIsSending] = useState(false);
    const [messageInput, setMessageInput] = useState('');
    const [showAllIntake, setShowAllIntake] = useState(false);
    const scrollBottomRef = useRef<HTMLDivElement>(null);

    const { data: historyData, isLoading, refetch } = useGet({
        url: '/support-sequences/history/list'
    });

    useEffect(() => {
        if (activeView === 'history') {
            setSelectedTicket(null);
            refetch();
        }
    }, [activeView, refetch]);

    // Polling for updates
    useEffect(() => {
        const interval = setInterval(() => {
            if (activeView === 'history' || selectedTicket) {
                refetch();
            }
        }, 5000); // 5 seconds
        return () => clearInterval(interval);
    }, [activeView, selectedTicket, refetch]);

    const tickets: SupportTicket[] = historyData?.data || [];

    // Sync selected ticket with list updates
    useEffect(() => {
        if (selectedTicket) {
            const updated = tickets.find(t => t.id === selectedTicket.id);
            if (updated) setSelectedTicket(updated);
        }
    }, [tickets]);

    const formatDate = (dateStr: string) => {
        try {
            return format(new Date(dateStr), 'PPP p', { 
                locale: isRtl ? ar : enUS 
            });
        } catch (e) {
            return dateStr;
        }
    };

    // Auto-scroll when ticket selected or intake expanded
    useEffect(() => {
        if (selectedTicket && scrollBottomRef.current) {
            setTimeout(() => {
                scrollBottomRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }, 100);
        }
    }, [selectedTicket, showAllIntake, selectedTicket?.messages.length]);

    const handleSendMessage = async () => {
        if (!messageInput.trim() || isSending) return;
        setIsSending(true);
        try {
            const sid = selectedTicket?.session_id || `session_${selectedTicket?.id}`;
            const resp = await axios.post(`${BASE_URL}/support-sequences/chat/send`, {
                session_id: sid,
                message: messageInput
            }, {
                headers: { Authorization: `Bearer ${USER_TOKEN_CL()}` }
            });
            if (resp.data?.success) {
                setMessageInput('');
                refetch();
            }
        } catch (error: any) {
            console.error('Failed to send message', error);
            toast({
                title: isRtl ? "فشل إرسال الرسالة" : "Failed to send message",
                description: error.response?.data?.message || error.message,
                variant: 'destructive'
            });
        } finally {
            setIsSending(false);
        }
    };

    const handleCloseTicket = async (ticketId: number) => {
        if (isClosing) return;
        setIsClosing(true);
        try {
            const resp = await axios.post(`${BASE_URL}/support-sequences/ticket/${ticketId}/close`, {}, {
                headers: { Authorization: `Bearer ${USER_TOKEN_CL()}` }
            });
            if (resp.data?.success) {
                toast({
                    title: isRtl ? "تم إغلاق التذكرة بنجاح" : "Ticket closed successfully",
                    variant: "success"
                });
                refetch();
                setSelectedTicket(prev => prev ? { ...prev, is_close: true } : null);
            } 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 {
            setIsClosing(false);
        }
    };

    if (selectedTicket) {
        const intakeResponses = selectedTicket.responses || [];
        const visibleIntake = showAllIntake ? intakeResponses : intakeResponses.slice(0, 2);

        return (
            <div className="space-y-6 animate-in fade-in duration-500" dir={isRtl ? 'rtl' : 'ltr'}>
                <div className="flex items-center justify-between bg-white p-4 rounded-xl border border-zinc-200 shadow-sm">
                    <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => setSelectedTicket(null)}
                        className="gap-2 text-zinc-600 hover:text-zinc-900"
                    >
                        {isRtl ? <ChevronRight className="size-4" /> : <ChevronLeft className="size-4" />}
                        {t('custom.go-back')}
                    </Button>
                    <div className="flex items-center gap-3">
                        {!selectedTicket.is_close && (
                            <>
                                <Button 
                                    variant="destructive" 
                                    size="sm" 
                                    onClick={() => handleCloseTicket(selectedTicket.id)}
                                    disabled={isClosing}
                                    className="rounded-lg gap-2 text-[10px] font-black uppercase tracking-widest px-4"
                                >
                                    {isClosing ? <Loader2 className="size-3 animate-spin" /> : <XCircle className="size-3" />}
                                    {isRtl ? "إغلاق التذكرة" : "Close Ticket"}
                                </Button>
                            </>
                        )}
                        <div className="flex items-center gap-3 ml-2 rtl:ml-0 rtl:mr-2">
                            <span className="text-xs font-medium text-zinc-400 whitespace-nowrap">ID: #{selectedTicket.id}</span>
                            <Badge variant={selectedTicket.is_close ? "secondary" : "default"} className={cn(
                                "rounded-full px-3 py-0.5 text-[10px] font-semibold uppercase tracking-wider",
                                selectedTicket.is_close ? "bg-zinc-100 text-zinc-500 border-zinc-200" : "bg-emerald-100 text-emerald-700 border-emerald-200"
                            )}>
                                {selectedTicket.is_close ? t('custom.resolved') : t('custom.active')}
                            </Badge>
                        </div>
                    </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
                    {/* Metadata & Intake */}
                    <div className="lg:col-span-1 space-y-6">
                        <Card className="rounded-xl border-zinc-200 shadow-none">
                            <CardHeader className="p-4 border-b border-zinc-100">
                                <CardTitle className="text-sm font-semibold flex items-center gap-2">
                                    <FileText className="size-4 text-purple-600" />
                                    {t('custom.ticket-details')}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="p-4 space-y-4">
                                <div className="space-y-1">
                                    <p className="text-[10px] text-zinc-400 font-bold uppercase tracking-tight">{t('custom.requester')}</p>
                                    <p className="text-sm font-medium text-zinc-900 truncate">{selectedTicket.name}</p>
                                </div>
                                <div className="space-y-1">
                                    <p className="text-[10px] text-zinc-400 font-bold uppercase tracking-tight">{t('auth.email')}</p>
                                    <p className="text-sm font-medium text-zinc-900 truncate italic underline">{selectedTicket.email}</p>
                                </div>
                                <div className="space-y-1">
                                    <p className="text-[10px] text-zinc-400 font-bold uppercase tracking-tight">{t('custom.created-at')}</p>
                                    <p className="text-sm font-medium text-zinc-900">{formatDate(selectedTicket.created_at)}</p>
                                </div>
                            </CardContent>
                        </Card>

                        {intakeResponses.length > 0 && (
                            <Card className="rounded-xl border-zinc-200 shadow-none">
                                <CardHeader className="p-4 border-b border-zinc-100">
                                    <CardTitle className="text-sm font-semibold flex items-center gap-2">
                                        <MessagesSquare className="size-4 text-purple-600" />
                                        {t('custom.initial-intake')}
                                    </CardTitle>
                                </CardHeader>
                                <CardContent className="p-4 space-y-4">
                                    {visibleIntake.map((resp, i) => (
                                        <div key={i} className="space-y-2 pb-4 last:pb-0 last:border-0 border-b border-zinc-50">
                                            <p className="text-xs font-semibold text-zinc-500 italic">Q: {resp.question}</p>
                                            <p className="bg-zinc-50/80 p-3 rounded-lg text-sm text-zinc-900 border border-zinc-100 font-medium leading-relaxed">
                                                {resp.response}
                                            </p>
                                        </div>
                                    ))}
                                    
                                    {intakeResponses.length > 2 && (
                                        <Button 
                                            variant="ghost" 
                                            size="sm" 
                                            onClick={() => setShowAllIntake(!showAllIntake)}
                                            className="w-full text-[10px] font-bold text-purple-600 hover:text-purple-700 hover:bg-purple-50 justify-between uppercase tracking-widest mt-2"
                                        >
                                            {showAllIntake ? t('custom.show-less') : t('custom.show-more')}
                                            {showAllIntake ? <ChevronUp className="size-3" /> : <ChevronDown className="size-3" />}
                                        </Button>
                                    )}
                                </CardContent>
                            </Card>
                        )}
                    </div>

                    {/* Chat Log */}
                    <div className="lg:col-span-3">
                        <Card className="rounded-xl border-zinc-200 shadow-none h-[700px] flex flex-col overflow-hidden bg-white">
                            <CardHeader className="p-4 border-b border-zinc-100 bg-zinc-50/50">
                                <CardTitle className="text-zinc-900 text-base font-bold flex items-center gap-2">
                                    <History className="size-4 text-purple-600" />
                                    {t('custom.conversation-history')}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="flex-1 p-0 overflow-hidden relative">
                                <ScrollArea className="h-full p-6">
                                    <div className="space-y-6">
                                        {selectedTicket.messages.map((msg, idx) => (
                                            <div key={idx} className={cn("flex flex-col gap-1.5", msg.sender === 'client' ? "items-end" : "items-start")}>
                                                <div className={cn(
                                                    "max-w-[80%] rounded-2xl px-4 py-3",
                                                    msg.sender === 'client' 
                                                        ? "bg-primary-tw-600 text-white rounded-tr-none shadow-sm" 
                                                        : "bg-white text-zinc-700 rounded-tl-none border border-zinc-200"
                                                )}>
                                                    <p className="text-sm md:text-base leading-relaxed">{msg.message}</p>
                                                </div>
                                                <span className="text-[9px] font-medium text-zinc-400 uppercase tracking-widest px-1">
                                                    {formatDate(msg.created_at)}
                                                </span>
                                            </div>
                                        ))}
                                        <div ref={scrollBottomRef} />
                                    </div>
                                </ScrollArea>
                            </CardContent>
                            {!selectedTicket.is_close && (
                                <CardFooter className="p-4 border-t border-zinc-200 bg-zinc-50/50">
                                    <div className="flex w-full items-center gap-3">
                                        <Input
                                            placeholder={t('placeholder.content')}
                                            value={messageInput}
                                            onChange={(e) => setMessageInput(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"
                                        />
                                        <Button 
                                            size="icon" 
                                            onClick={handleSendMessage} 
                                            disabled={!messageInput.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>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="w-full space-y-6 animate-in fade-in duration-500" dir={isRtl ? 'rtl' : 'ltr'}>
            <div className="flex items-center justify-between gap-4">
                <div className="flex-1">
                    <h1 className="text-2xl font-bold text-zinc-900 flex items-center gap-3">
                        <History className="size-6 text-purple-600" />
                        {t('custom.support-history-title')}
                    </h1>
                    <p className="text-zinc-500 text-sm mt-1">{t('custom.support-history-desc')}</p>
                </div>
            
            </div>

            {isLoading ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {[1, 2, 3].map(i => (
                        <div key={i} className="h-48 bg-zinc-100 animate-pulse rounded-xl border border-zinc-200" />
                    ))}
                </div>
            ) : tickets.length === 0 ? (
                <Card className="w-full border-2 border-dashed border-zinc-200 bg-white/50 p-16 text-center rounded-2xl">
                    <div className="bg-zinc-100 p-4 rounded-full w-fit mx-auto mb-6">
                        <SearchX className="size-10 text-zinc-300" />
                    </div>
                    <h3 className="text-xl font-bold text-zinc-900">{t('custom.no-history-found')}</h3>
                    <p className="text-zinc-500 max-w-sm mx-auto mt-2 text-sm">{t('custom.no-history-desc')}</p>
                </Card>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {tickets.map((ticket) => (
                        <Card 
                            key={ticket.id} 
                            className="group border-zinc-200 shadow-none hover:shadow-lg hover:shadow-zinc-200 transition-all cursor-pointer rounded-xl overflow-hidden bg-white"
                            onClick={() => setSelectedTicket(ticket)}
                        >
                            <CardHeader className="p-5 pb-2">
                                <div className="flex justify-between items-start mb-4">
                                    <Badge variant={ticket.is_close ? "secondary" : "default"} className={cn(
                                        "px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider",
                                        ticket.is_close ? "bg-zinc-100 text-zinc-500 border-zinc-200" : "bg-emerald-100 text-emerald-700 border-emerald-200"
                                    )}>
                                        {ticket.is_close ? t('custom.resolved') : t('custom.active')}
                                    </Badge>
                                    <span className="text-[10px] font-bold text-zinc-400 bg-zinc-50 px-2 py-1 rounded border border-zinc-100">#{ticket.id}</span>
                                </div>
                                <CardTitle className="text-base font-bold text-zinc-900 group-hover:text-primary-tw-600 transition-colors line-clamp-1">
                                    {ticket.messages[0]?.message || "Support Inquiry"}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="p-5 pt-2">
                                <div className="flex items-center gap-2 text-zinc-400 text-xs font-semibold mb-6">
                                    <Calendar className="size-3.5" />
                                    {formatDate(ticket.created_at)}
                                </div>
                                <div className="flex items-center justify-between text-xs font-bold p-3 bg-zinc-50 rounded-lg group-hover:bg-zinc-100/80 transition-colors">
                                    <div className="flex items-center gap-2 text-zinc-500">
                                        <MessagesSquare className="size-3.5 text-purple-600" />
                                        {t('custom.messages-count')}
                                    </div>
                                    <span className="text-zinc-900 bg-white px-2 py-0.5 rounded border border-zinc-200 shadow-sm">{ticket.messages?.length || 0}</span>
                                </div>
                            </CardContent>
                            <CardFooter className="p-4 pt-0 border-t border-zinc-50 bg-zinc-50/30">
                                <Button variant="ghost" className="w-full justify-between group/btn text-zinc-500 hover:text-primary-tw-600 font-bold text-xs uppercase tracking-wider h-auto py-3">
                                    {t('custom.view-history')}
                                    <ArrowUpRight className="size-4 opacity-0 group-hover:opacity-100 transition-all -translate-y-1 translate-x-1" />
                                </Button>
                            </CardFooter>
                        </Card>
                    ))}
                </div>
            )}
        </div>
    );
}
