'use client';

import { useMutation, useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { Icons } from '@/components/icons';
import PageContainer from '@/components/layout/page-container';
import { Button } from '@/components/ui/button';
import { NotificationCard, type NotificationAction } from '@/components/ui/notification-card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  archiveNotificationMutation,
  markAllNotificationsReadMutation,
  markNotificationReadMutation
} from '../api/mutations';
import { notificationsQueryOptions } from '../api/queries';
import type { NotificationListItem } from '../api/types';

function buildNotificationActions(notification: NotificationListItem): NotificationAction[] {
  const actions: NotificationAction[] = [];

  if (notification.linkUrl) {
    actions.push({
      id: `open:${notification.linkUrl}`,
      label: 'Open',
      type: 'redirect',
      style: 'primary'
    });
  }

  if (notification.status !== 'archived') {
    actions.push({
      id: `archive:${notification.id}`,
      label: 'Archive',
      type: 'api_call',
      style: 'default'
    });
  }

  return actions;
}

export default function NotificationsPage() {
  const router = useRouter();
  const notificationsQuery = useQuery(notificationsQueryOptions({ page: 1, limit: 50, status: 'all' }));
  const markRead = useMutation(markNotificationReadMutation);
  const markAllRead = useMutation(markAllNotificationsReadMutation);
  const archive = useMutation(archiveNotificationMutation);

  const notifications = notificationsQuery.data?.items ?? [];
  const unreadCount = notificationsQuery.data?.unreadCount ?? 0;
  const unreadNotifications = notifications.filter((notification) => notification.status === 'unread');
  const readNotifications = notifications.filter((notification) => notification.status === 'read');
  const archivedNotifications = notifications.filter(
    (notification) => notification.status === 'archived'
  );

  function renderList(items: NotificationListItem[]) {
    if (notificationsQuery.isError) {
      return (
        <div className='flex flex-col items-center justify-center py-16'>
          <Icons.alertCircle className='text-muted-foreground/40 mb-3 h-10 w-10' />
          <p className='text-muted-foreground text-sm'>Unable to load notifications</p>
        </div>
      );
    }

    if (notificationsQuery.isLoading) {
      return (
        <div className='flex flex-col gap-2'>
          {Array.from({ length: 4 }).map((_, index) => (
            <div key={index} className='bg-muted h-24 animate-pulse rounded-2xl' />
          ))}
        </div>
      );
    }

    if (items.length === 0) {
      return (
        <div className='flex flex-col items-center justify-center py-16'>
          <Icons.notification className='text-muted-foreground/40 mb-3 h-10 w-10' />
          <p className='text-muted-foreground text-sm'>No notifications</p>
        </div>
      );
    }

    return (
      <div className='flex flex-col gap-2'>
        {items.map((notification) => (
          <NotificationCard
            key={notification.id}
            id={notification.id}
            title={notification.title}
            body={notification.body}
            status={notification.status}
            createdAt={notification.createdAt}
            actions={buildNotificationActions(notification)}
            onMarkAsRead={(id) => markRead.mutate(id)}
            onAction={async (notificationId, actionId) => {
              if (actionId.startsWith('open:')) {
                await markRead.mutateAsync(notificationId);
                router.push(actionId.replace('open:', ''));
                return;
              }

              if (actionId.startsWith('archive:')) {
                await archive.mutateAsync(notificationId);
              }
            }}
          />
        ))}
      </div>
    );
  }

  return (
    <PageContainer
      pageTitle='Notifications'
      pageDescription='View and manage all your notifications.'
      pageHeaderAction={
        unreadCount > 0 ? (
          <Button
            variant='outline'
            size='sm'
            disabled={markAllRead.isPending}
            onClick={() => markAllRead.mutate()}
          >
            Mark all as read
          </Button>
        ) : undefined
      }
    >
      <Tabs defaultValue='all'>
        <TabsList>
          <TabsTrigger value='all'>All ({notifications.length})</TabsTrigger>
          <TabsTrigger value='unread'>Unread ({unreadNotifications.length})</TabsTrigger>
          <TabsTrigger value='read'>Read ({readNotifications.length})</TabsTrigger>
          <TabsTrigger value='archived'>Archived ({archivedNotifications.length})</TabsTrigger>
        </TabsList>
        <TabsContent value='all' className='mt-4'>
          {renderList(notifications)}
        </TabsContent>
        <TabsContent value='unread' className='mt-4'>
          {renderList(unreadNotifications)}
        </TabsContent>
        <TabsContent value='read' className='mt-4'>
          {renderList(readNotifications)}
        </TabsContent>
        <TabsContent value='archived' className='mt-4'>
          {renderList(archivedNotifications)}
        </TabsContent>
      </Tabs>
    </PageContainer>
  );
}
