// 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 { Plus } from "lucide-react";
import SupportRequestModal from '@/components/SupportChat/SupportRequestModal';
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 PharmacySupportDashboard() {
    const { toast } = useToast();
    const [tickets, setTickets] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const user = useAuthStore((state) => state.user);
    const [newTickets, setNewTickets] = useState([]);
    const [notificationsEnabled, setNotificationsEnabled] = useState(true);
    const [isOpen, setIsOpen] = useState(false);

    // Fetch initial tickets
    useEffect(() => {
        const fetchTickets = async () => {
            try {
                const data = await authFetch('/api/support/my-tickets');
                console.log('Fetched tickets:', data);

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

        fetchTickets();
    }, [toast]);


    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 className="bg-blue-500 text-white hover:bg-blue-400 cursor-pointer" onClick={() => setIsOpen(true)}>
                        <Plus className="mr-2 h-4 w-4" /> New Ticket
                    </Button>
                    <SupportRequestModal isOpen={isOpen} onClose={() => setIsOpen(false)} />
                </div>
            </div>

            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <MessageSquare className="h-5 w-5" />
                        <span>My 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>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>
                                            <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">
                                                <Button
                                                    variant="outline"
                                                    size="sm"
                                                    asChild
                                                    className="cursor-pointer"
                                                >
                                                    <Link href={`/dashboard/pharmacy/support/tickets/${ticket.id}`}>View</Link>
                                                </Button>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>
        </div>
    );
}