import { useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { AlertCircle, Bell, CheckCheck, CheckCircle, Info, Loader2, Mail } from 'lucide-react';
import { toast } from 'sonner';
import { notificationList, notificationMarkAllRead, notificationMarkRead } from '@/client';
import {getApiErrorMessage} from '@/lib/api-error';

export function SettingsActivity() {
    const queryClient = useQueryClient();
    const [limit] = useState(20);

    // Fetch notifications
    const { data: notificationsData, isLoading } = useQuery({
        queryKey: ['userNotifications'],
        queryFn: async () => {
            const resp = await notificationList({ query: { limit } });
            return resp.data?.data ?? null;
        },
    });

    // Mark notification as read mutation
    const markAsReadMutation = useMutation({
        mutationFn: async (notificationId: string) => {
            await notificationMarkRead({ path: { notification_id: notificationId } });
        },
        onSuccess: () => {
            toast.success('Notification marked as read');
            queryClient.invalidateQueries({ queryKey: ['userNotifications'] });
        },
        onError: (err: unknown) => {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            toast.error(getApiErrorMessage(err, 'Failed to mark notification as read'));
        },
    });

    // Mark all as read mutation
    const markAllAsReadMutation = useMutation({
        mutationFn: async () => {
            await notificationMarkAllRead();
        },
        onSuccess: () => {
            toast.success('All notifications marked as read');
            queryClient.invalidateQueries({ queryKey: ['userNotifications'] });
        },
        onError: (err: unknown) => {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            toast.error(getApiErrorMessage(err, 'Failed to mark all notifications as read'));
        },
    });

    const formatDate = (dateString: string) => {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);

        if (diffMins < 1) return 'Just now';
        if (diffMins < 60) return `${diffMins} minute${diffMins > 1 ? 's' : ''} ago`;
        if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
        if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;

        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
        });
    };

    const getNotificationIcon = (notification: { title?: string }) => {
        const title = (notification.title || '').toLowerCase();

        if (title.includes('security') || title.includes('alert')) {
            return <AlertCircle className="h-5 w-5 text-red-500" />;
        }
        if (title.includes('success') || title.includes('completed')) {
            return <CheckCircle className="h-5 w-5 text-green-500" />;
        }
        if (title.includes('mail') || title.includes('message')) {
            return <Mail className="h-5 w-5 text-blue-500" />;
        }
        return <Info className="h-5 w-5 text-blue-500" />;
    };

    const notifications = notificationsData?.notifications || [];
    const unreadNotifications = notifications.filter((n) => !n.is_read);
    const hasUnread = unreadNotifications.length > 0;

    return (
        <div className="flex-1 lg:max-w-4xl space-y-6 p-4 md:p-8 pt-6">
            <div className="flex flex-col space-y-8 lg:flex-row lg:items-center lg:justify-between lg:space-y-0">
                <div className="space-y-0.5">
                    <h2 className="text-2xl font-bold tracking-tight">Activity</h2>
                    <p className="text-muted-foreground">View your recent activity and notifications.</p>
                </div>
                {hasUnread && (
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={() => markAllAsReadMutation.mutate()}
                        disabled={markAllAsReadMutation.isPending}
                    >
                        <CheckCheck className="h-4 w-4 mr-2" />
                        Mark All as Read
                    </Button>
                )}
            </div>
            <Separator className="my-6" />

            <Card>
                <CardHeader>
                    <div className="flex items-center justify-between">
                        <CardTitle className="flex items-center gap-2">
                            <Bell className="h-5 w-5" />
                            Recent Notifications
                        </CardTitle>
                        {hasUnread && <Badge variant="destructive">{unreadNotifications.length} unread</Badge>}
                    </div>
                </CardHeader>
                <CardContent>
                    {isLoading ? (
                        <div className="flex items-center justify-center py-12">
                            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                        </div>
                    ) : !notifications || notifications.length === 0 ? (
                        <div className="text-center py-12">
                            <Bell className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                            <p className="text-muted-foreground">No notifications yet. You'll see your activity here.</p>
                        </div>
                    ) : (
                        <div className="space-y-4">
                            {notifications.map((notification, index) => {
                                const notificationId = notification.id || String(index);
                                return (
                                    <>
                                        {index > 0 && <Separator />}
                                        <div className={`py-4 ${!notification.is_read ? 'bg-primary/5 -mx-6 px-6 rounded-md' : ''}`}>
                                            <div className="flex items-start gap-4">
                                                {notification.user_info ? (
                                                    <>
                                                        <Avatar className="h-9 w-9 mt-0.5">
                                                            {notification.user_info.avatar_url ? (
                                                                <AvatarImage
                                                                    src={notification.user_info.avatar_url}
                                                                    alt={notification.user_info.username}
                                                                />
                                                            ) : null}
                                                            <AvatarFallback className="text-xs">
                                                                {notification.user_info.username[0]?.toUpperCase() ?? '?'}
                                                            </AvatarFallback>
                                                        </Avatar>
                                                        <div className="flex-1 space-y-1">
                                                            <div className="flex items-start justify-between gap-4">
                                                                <div className="flex-1">
                                                                    <div className="flex items-center gap-2">
                                                                        <p className="font-medium">
                                                                            <span className="text-foreground">@{notification.user_info.username}</span>
                                                                            {' — '}
                                                                            {notification.title || 'Notification'}
                                                                        </p>
                                                                        {!notification.is_read && (
                                                                            <Badge variant="default" className="h-5 px-1.5 text-xs">
                                                                                New
                                                                            </Badge>
                                                                        )}
                                                                    </div>
                                                                    <p className="text-sm text-muted-foreground mt-1">
                                                                        {notification.content || 'No content'}
                                                                    </p>
                                                                </div>
                                                                {!notification.is_read && (
                                                                    <Button
                                                                        variant="ghost"
                                                                        size="sm"
                                                                        onClick={() => markAsReadMutation.mutate(notificationId)}
                                                                        disabled={markAsReadMutation.isPending}
                                                                    >
                                                                        <CheckCheck className="h-4 w-4" />
                                                                    </Button>
                                                                )}
                                                            </div>
                                                            <p className="text-xs text-muted-foreground">
                                                                {notification.created_at ? formatDate(notification.created_at) : 'Unknown date'}
                                                            </p>
                                                        </div>
                                                    </>
                                                ) : (
                                                    <>
                                                        <div className="mt-1">{getNotificationIcon(notification)}</div>
                                                        <div className="flex-1 space-y-1">
                                                            <div className="flex items-start justify-between gap-4">
                                                                <div className="flex-1">
                                                                    <div className="flex items-center gap-2">
                                                                        <p className="font-medium">{notification.title || 'Notification'}</p>
                                                                        {!notification.is_read && (
                                                                            <Badge variant="default" className="h-5 px-1.5 text-xs">
                                                                                New
                                                                            </Badge>
                                                                        )}
                                                                    </div>
                                                                    <p className="text-sm text-muted-foreground mt-1">
                                                                        {notification.content || 'No content'}
                                                                    </p>
                                                                </div>
                                                                {!notification.is_read && (
                                                                    <Button
                                                                        variant="ghost"
                                                                        size="sm"
                                                                        onClick={() => markAsReadMutation.mutate(notificationId)}
                                                                        disabled={markAsReadMutation.isPending}
                                                                    >
                                                                        <CheckCheck className="h-4 w-4" />
                                                                    </Button>
                                                                )}
                                                            </div>
                                                            <p className="text-xs text-muted-foreground">
                                                                {notification.created_at ? formatDate(notification.created_at) : 'Unknown date'}
                                                            </p>
                                                        </div>
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    </>
                                );
                            })}
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    );
}
