import React, { useState, useEffect } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Bell, Check, Clock, ChevronLeft, ChevronRight } from 'lucide-react';
import { notificationService, Notification } from '@/services/notification.service';
import { useNavigate } from 'react-router-dom';
import { formatDistanceToNow } from 'date-fns';

export const NotificationsPage: React.FC = () => {
    const [notifications, setNotifications] = useState<Notification[]>([]);
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const limit = 15;
    const navigate = useNavigate();

    const fetchNotifications = async (currentPage: number) => {
        try {
            setLoading(true);
            const res: any = await notificationService.getNotifications(currentPage, limit);
            if (res.success) {
                setNotifications(res.data);
                if (res.pagination) {
                    setTotalPages(res.pagination.totalPages);
                }
            }
        } catch (error) {
            console.error('Failed to fetch notifications', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchNotifications(page);
    }, [page]);

    const handleMarkAsRead = async (id: string, e: React.MouseEvent) => {
        e.stopPropagation();
        await notificationService.markAsRead(id);
        fetchNotifications(page);
    };

    const handleMarkAllAsRead = async () => {
        await notificationService.markAllAsRead();
        fetchNotifications(page);
    };

    const handleNotificationClick = async (notif: Notification) => {
        if (!notif.isRead) {
            await notificationService.markAsRead(notif.id);
        }
        if (notif.link) {
            // Support both relative or absolute links dynamically
            const url = notif.link;
            try {
                const parsedUrl = new URL(url);
                if (parsedUrl.origin === window.location.origin) {
                    navigate(parsedUrl.pathname + parsedUrl.search + parsedUrl.hash);
                } else {
                    window.open(url, '_blank');
                }
            } catch (e) {
                navigate(url);
            }
        } else {
            fetchNotifications(page); // refresh list manually if no link
        }
    };

    return (
        <div className="p-6 max-w-5xl mx-auto">
            <div className="flex justify-between items-center mb-6">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                        <Bell className="w-6 h-6 text-blue-600" />
                        Notifications Center
                    </h1>
                    <p className="text-gray-500 text-sm mt-1">View and manage all your alerts</p>
                </div>
                <Button 
                    variant="outline" 
                    onClick={handleMarkAllAsRead}
                    disabled={loading || !notifications.some(n => !n.isRead)}
                >
                    <Check className="w-4 h-4 mr-2" />
                    Mark all as read
                </Button>
            </div>

            <Card className="shadow-sm border-gray-200">
                <CardContent className="p-0">
                    {loading ? (
                        <div className="flex justify-center items-center h-64">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                        </div>
                    ) : notifications.length === 0 ? (
                        <div className="flex flex-col items-center justify-center h-64 text-gray-500">
                            <Bell className="w-12 h-12 text-gray-300 mb-4" />
                            <p className="text-lg font-medium">No notifications yet</p>
                            <p className="text-sm">When you get updates, they'll show up here.</p>
                        </div>
                    ) : (
                        <div className="divide-y divide-gray-100">
                            {notifications.map(notif => (
                                <div 
                                    key={notif.id} 
                                    className={`p-4 hover:bg-gray-50 transition-colors flex items-start gap-4 cursor-pointer ${!notif.isRead ? 'bg-blue-50/50' : ''}`}
                                    onClick={() => handleNotificationClick(notif)}
                                >
                                    <div className="mt-1 flex-shrink-0 cursor-pointer" onClick={(e) => handleMarkAsRead(notif.id, e)}>
                                        {!notif.isRead ? (
                                            <div className="w-3 h-3 bg-blue-600 rounded-full shadow-sm"></div>
                                        ) : (
                                            <div className="w-3 h-3 border-2 border-gray-300 rounded-full"></div>
                                        )}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <div className="flex justify-between items-start mb-1">
                                            <h4 className={`text-sm font-semibold ${!notif.isRead ? 'text-gray-900' : 'text-gray-700'}`}>
                                                {notif.title}
                                            </h4>
                                            <div className="flex items-center text-xs text-gray-500 whitespace-nowrap ml-4">
                                                <Clock className="w-3 h-3 mr-1" />
                                                {formatDistanceToNow(new Date(notif.createdAt), { addSuffix: true })}
                                            </div>
                                        </div>
                                        <p className="text-sm text-gray-600 line-clamp-2">{notif.message}</p>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Pagination Controls */}
            {!loading && totalPages > 1 && (
                <div className="flex items-center justify-between mt-6 px-4">
                    <p className="text-sm text-gray-600">
                        Showing page <span className="font-medium text-gray-900">{page}</span> of{' '}
                        <span className="font-medium text-gray-900">{totalPages}</span>
                    </p>
                    <div className="flex items-center gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            disabled={page === 1}
                            onClick={() => setPage(p => Math.max(1, p - 1))}
                        >
                            <ChevronLeft className="w-4 h-4" />
                            Previous
                        </Button>
                        <Button
                            variant="outline"
                            size="sm"
                            disabled={page === totalPages}
                            onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                        >
                            Next
                            <ChevronRight className="w-4 h-4" />
                        </Button>
                    </div>
                </div>
            )}
        </div>
    );
};

export default NotificationsPage;
