'use client';

import { useMutation, useQuery } from '@tanstack/react-query';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import { NotificationCard, type NotificationAction } from '@/components/ui/notification-card';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { markAllNotificationsAsReadMutation, markNotificationAsReadMutation } from '../api/mutations';
import { notificationsQueryOptions } from '../api/queries';

const MAX_VISIBLE = 5;

function getNotificationAction(href: string | null): NotificationAction[] {
  if (!href) return [];

  return [
    {
      id: 'open',
      label: 'เปิดรายการ',
      type: 'redirect',
      style: 'primary'
    }
  ];
}

export function NotificationCenter() {
  const router = useRouter();
  const { data, isLoading } = useQuery(
    notificationsQueryOptions({
      page: 1,
      limit: MAX_VISIBLE,
      status: 'all'
    })
  );

  const markRead = useMutation({
    ...markNotificationAsReadMutation,
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถอัปเดตการแจ้งเตือนได้');
    }
  });

  const markAllRead = useMutation({
    ...markAllNotificationsAsReadMutation,
    onSuccess: (response) => {
      toast.success(response.message);
    },
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถอัปเดตการแจ้งเตือนได้');
    }
  });

  const count = data?.unread_count ?? 0;
  const notifications = data?.notifications ?? [];

  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant='ghost' size='icon' className='relative size-9'>
          <Icons.notification className='h-4 w-4' />
          {count > 0 && (
            <span className='bg-destructive text-destructive-foreground absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-medium'>
              {count > 9 ? '9+' : count}
            </span>
          )}
          <span className='sr-only'>การแจ้งเตือน</span>
        </Button>
      </PopoverTrigger>
      <PopoverContent
        align='end'
        className='w-[min(24rem,calc(100vw-1rem))] p-0'
        sideOffset={8}
      >
        <div className='flex flex-wrap items-center justify-between gap-2 px-4 py-3'>
          <Link href='/dashboard/notifications' className='group flex min-w-0 items-center gap-1'>
            <h4 className='text-sm font-semibold group-hover:underline'>การแจ้งเตือน</h4>
            <Icons.chevronRight className='text-muted-foreground h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5' />
          </Link>
          <div className='flex flex-wrap items-center justify-end gap-2'>
            {count > 0 && (
              <span className='bg-muted text-muted-foreground rounded-full px-2 py-0.5 text-xs'>
                {count} รายการใหม่
              </span>
            )}
            {count > 0 && (
              <Button
                variant='ghost'
                size='sm'
                className='text-muted-foreground h-auto px-2 py-1 text-xs'
                onClick={() => markAllRead.mutate()}
                disabled={markAllRead.isPending}
              >
                อ่านทั้งหมด
              </Button>
            )}
          </div>
        </div>
        <Separator />
        <ScrollArea className='h-[400px]'>
          {isLoading ? (
            <div className='flex flex-col items-center justify-center py-12'>
              <Icons.spinner className='text-muted-foreground h-6 w-6 animate-spin' />
            </div>
          ) : notifications.length === 0 ? (
            <div className='flex flex-col items-center justify-center py-12'>
              <Icons.notification className='text-muted-foreground/40 mb-2 h-8 w-8' />
              <p className='text-muted-foreground text-sm'>ยังไม่มีการแจ้งเตือน</p>
            </div>
          ) : (
            <div className='flex flex-col gap-1 p-2'>
              {notifications.map((notification) => (
                <NotificationCard
                  key={notification.id}
                  id={notification.id}
                  title={notification.title}
                  body={notification.message}
                  status={notification.is_read ? 'read' : 'unread'}
                  createdAt={notification.created_at}
                  actions={getNotificationAction(notification.href)}
                  onMarkAsRead={(id) => markRead.mutate(id)}
                  onAction={(notificationId) => {
                    const target = notifications.find((item) => item.id === notificationId);
                    if (!target?.href) return;

                    if (!target.is_read) {
                      markRead.mutate(notificationId, {
                        onSuccess: () => router.push(target.href!)
                      });
                      return;
                    }

                    router.push(target.href);
                  }}
                />
              ))}
            </div>
          )}
        </ScrollArea>
      </PopoverContent>
    </Popover>
  );
}
