// app/support/dashboard/page.js
'use client';
import { useState, useEffect } from 'react';
import { useSocket } from '@/context/SocketContext';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { format } from 'date-fns';
import { Loader2, Bell, BellOff, MessageSquare, User } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
import { authFetch } from '@/lib/api';
import { useAuthStore } from '@/stores/authStore';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

const STATUS_MAP = {
    open: { label: 'Open', color: 'bg-orange-100 text-orange-800' },
    assigned: { label: 'Assigned', color: 'bg-blue-100 text-blue-800' },
    in_progress: { label: 'In Progress', color: 'bg-yellow-100 text-yellow-800' },
    resolved: { label: 'Resolved', color: 'bg-green-100 text-green-800' },
    closed: { label: 'Closed', color: 'bg-purple-100 text-purple-800' }
};

const PRIORITY_MAP = {
    low: { label: 'Low', color: 'bg-gray-100 text-gray-800' },
    medium: { label: 'Medium', color: 'bg-blue-100 text-blue-800' },
    high: { label: 'High', color: 'bg-yellow-100 text-yellow-800' },
    urgent: { label: 'Urgent', color: 'bg-red-100 text-red-800' }
};

export default function SupportDashboard() {
    const router = useRouter();
    const { socket } = useSocket();
    const { toast } = useToast();
    const [tickets, setTickets] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const user = useAuthStore((state) => state.user);
    const [newTickets, setNewTickets] = useState([]);
    // const [newTicketSound] = useState(typeof Audio !== 'undefined' ? new Audio('/sounds/notification.mp3') : null);
    const [notificationsEnabled, setNotificationsEnabled] = useState(true);

    // Fetch initial tickets
    useEffect(() => {
        const fetchTickets = async () => {
            try {
                const data = await authFetch('/api/support/tickets');

                setTickets(data);
            } catch (error) {
                toast({
                    title: 'Error',
                    description: 'Failed to load support tickets',
                    variant: 'destructive'
                });
            } finally {
                setIsLoading(false);
            }
        };

        fetchTickets();
    }, [toast]);

    // Socket event listeners
    useEffect(() => {
        if (!socket) return;

        const handleNewTicket = (newTicket) => {
            console.log('New ticket received:', newTicket);
            setTickets(prev => {
                if (prev.some(t => t.id === newTicket.id)) return prev;
                return [newTicket, ...prev]
            });

            setNewTickets(prev => [...prev, newTicket.id]);

            setTimeout(() => {
                setNewTickets(prev => prev.filter(id => id !== newTicket.id));
            }, 5000);

            // if (notificationsEnabled && newTicketSound) {
            //     newTicketSound.play().catch(e => console.error('Audio playback failed:', e));
            //     toast({
            //         title: 'New Support Ticket',
            //         description: `${newTicket.userInfo.name} - ${newTicket.subject}`,
            //         action: (
            //             <Button
            //                 variant="ghost"
            //                 size="sm"
            //                 onClick={() => handleAcceptTicket(newTicket)}
            //             >
            //                 Accept
            //             </Button>
            //         )
            //     });
            // }
        };

        const handleTicketUpdate = (updatedTicket) => {
            setTickets(prev => prev.map(ticket =>
                ticket.id === updatedTicket.id ? updatedTicket : ticket
            ));
        };

        const handleInitialTickets = (initialTickets) => {
            setTickets(initialTickets);
        };

        socket.emit('join-admin-room');
        socket.emit('request-initial-tickets');

        socket.on('new-ticket', handleNewTicket);
        socket.on('ticket-updated', handleTicketUpdate);
        socket.on('initial-tickets', handleInitialTickets);
        socket.off('initial-tickets', handleInitialTickets);


        return () => {
            socket.off('new-ticket', handleNewTicket);
            socket.off('ticket-updated', handleTicketUpdate);
        };
    }, [socket, notificationsEnabled, toast]);

    // useEffect(() => {
    //     if (!socket) return;
    //     const handleReconnect = () => {
    //         socket.emit('join-admin-room');
    //         socket.emit('request-initial-tickets');
    //     };

    //     socket.on('reconnect', handleReconnect);
    //     return () => socket.off('reconnect', handleReconnect);
    // }, [socket]);

    const handleAcceptTicket = async (ticket) => {
        try {
            const response = await authFetch(`/api/support/tickets/${ticket.id}/accept`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ agentId: user.id }),
                credentials: 'include' // For http-only cookies
            });

            // if (!response.ok) throw new Error('Failed to accept ticket');

            const updatedTicket = await response;

            // Update local state
            setTickets(prev => prev.map(t =>
                t.id === updatedTicket.id ? updatedTicket : t
            ));

            toast({
                title: 'Ticket Accepted',
                description: `You are now assigned to ticket #${ticket.id.slice(0, 6)}`,
                variant: 'default'
            });

            // Join the ticket room
            socket.emit('accept-ticket', { ticketId: ticket.id });

            router.push(`/dashboard/admin/support/tickets/${ticket.id}`);


        } catch (error) {
            toast({
                title: 'Error',
                description: error.message,
                variant: 'destructive'
            });
        }
    };

    const toggleNotifications = () => {
        setNotificationsEnabled(prev => !prev);
        toast({
            title: `Notifications ${notificationsEnabled ? 'Disabled' : 'Enabled'}`,
            variant: 'default'
        });
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-64">
                <Loader2 className="h-8 w-8 animate-spin" />
            </div>
        );
    }

    return (
        <div className="container mx-auto p-4 space-y-6">
            <div className="flex justify-between items-center">
                <h1 className="text-2xl font-bold">Support Tickets</h1>
                <div className="flex gap-2">
                    <Button
                        variant="outline"
                        size="icon"
                        onClick={toggleNotifications}
                        title={notificationsEnabled ? 'Disable notifications' : 'Enable notifications'}
                    >
                        {notificationsEnabled ? <Bell className="h-4 w-4" /> : <BellOff className="h-4 w-4" />}
                    </Button>
                </div>
            </div>

            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <MessageSquare className="h-5 w-5" />
                        <span>Active Tickets</span>
                        <Badge variant="secondary" className="ml-auto">
                            {tickets.length} total
                        </Badge>
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>ID</TableHead>
                                <TableHead>Subject</TableHead>
                                <TableHead>User</TableHead>
                                <TableHead>Status</TableHead>
                                <TableHead>Priority</TableHead>
                                <TableHead>Created</TableHead>
                                <TableHead>Actions</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {tickets.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                                        No active support tickets
                                    </TableCell>
                                </TableRow>
                            ) : (
                                tickets.map((ticket) => (
                                    <TableRow key={ticket.id} className={newTickets.includes(ticket.id) ? 'animate-pulse bg-blue-50' : ''}>
                                        <TableCell className="font-medium">
                                            #{ticket.id.slice(0, 6)}
                                            {newTickets.includes(ticket.id) && (
                                                <span className="ml-2 inline-block h-2 w-2 rounded-full bg-blue-500"></span>
                                            )}
                                        </TableCell>
                                        <TableCell className="max-w-[200px] truncate">{ticket.subject}</TableCell>
                                        <TableCell>
                                            <div className="flex items-center gap-2">
                                                <User className="h-4 w-4 text-gray-500" />
                                                <span>{ticket.user?.firstName || 'Unknown'}</span>
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <Badge className={STATUS_MAP[ticket.status].color}>
                                                {STATUS_MAP[ticket.status].label}
                                            </Badge>
                                        </TableCell>
                                        <TableCell>
                                            <Badge className={PRIORITY_MAP[ticket.priority || 'medium'].color}>
                                                {PRIORITY_MAP[ticket.priority || 'medium'].label}
                                            </Badge>
                                        </TableCell>
                                        <TableCell>
                                            {format(new Date(ticket.createdAt), 'MMM d, HH:mm')}
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex gap-2">
                                                {ticket.status === 'open' && (
                                                    <Button
                                                        variant="outline"
                                                        size="sm"
                                                        onClick={() => handleAcceptTicket(ticket)}
                                                        className="cursor-pointer"
                                                    >
                                                        Accept
                                                    </Button>
                                                )}
                                                <Button
                                                    variant="outline"
                                                    size="sm"
                                                    asChild
                                                    className="cursor-pointer"
                                                >
                                                    <Link href={`/dashboard/admin/support/tickets/${ticket.id}`}>View</Link>
                                                </Button>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>
        </div>
    );
}