import { useQuery, useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import type { Notification } from "@shared/schema";
import { Header } from "@/components/Header";
import { MobileNav } from "@/components/MobileNav";
import { NotificationItem } from "@/components/NotificationItem";
import { EmptyState } from "@/components/EmptyState";
import { Bell } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

export default function Notifications() {
  const { data: notifications = [], isLoading } = useQuery<Notification[]>({
    queryKey: ["/api/notifications"],
  });

  const markSeenMutation = useMutation({
    mutationFn: async (id: string) => {
      await apiRequest("PATCH", `/api/notifications/${id}/seen`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/notifications"] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      await apiRequest("DELETE", `/api/notifications/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/notifications"] });
    },
  });

  const unseenNotifications = notifications.filter((n) => !n.seen);
  const allNotifications = notifications;

  const handleDismiss = (id: string) => {
    deleteMutation.mutate(id);
  };

  const handleMarkAllRead = async () => {
    await Promise.all(
      unseenNotifications.map((n) => markSeenMutation.mutateAsync(n.id))
    );
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p className="text-muted-foreground">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background pb-20 md:pb-8">
      <Header />

      <main className="container mx-auto px-4 md:px-6 py-6 max-w-4xl space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-3xl font-bold">Notifications</h1>
          {unseenNotifications.length > 0 && (
            <Button
              variant="outline"
              size="sm"
              onClick={handleMarkAllRead}
              data-testid="button-mark-all-read"
            >
              Mark all as read
            </Button>
          )}
        </div>

        <Tabs defaultValue="all" className="w-full">
          <TabsList className="w-full md:w-auto">
            <TabsTrigger value="all" className="flex-1 md:flex-none" data-testid="tab-all">
              All ({allNotifications.length})
            </TabsTrigger>
            <TabsTrigger value="unread" className="flex-1 md:flex-none" data-testid="tab-unread">
              Unread ({unseenNotifications.length})
            </TabsTrigger>
          </TabsList>

          <TabsContent value="all" className="space-y-3 mt-6">
            {allNotifications.length === 0 ? (
              <EmptyState
                icon={Bell}
                title="No notifications"
                description="You're all caught up! We'll notify you when there are updates."
              />
            ) : (
              allNotifications.map((notification) => (
                <NotificationItem
                  key={notification.id}
                  id={notification.id}
                  type={notification.type as "ai-suggestion" | "reminder"}
                  planName={notification.planId ? `Plan #${notification.planId.substring(0, 8)}` : "General"}
                  message={notification.message}
                  seen={notification.seen}
                  createdAt={new Date(notification.createdAt).toLocaleString()}
                  onDismiss={() => handleDismiss(notification.id)}
                />
              ))
            )}
          </TabsContent>

          <TabsContent value="unread" className="space-y-3 mt-6">
            {unseenNotifications.length === 0 ? (
              <EmptyState
                icon={Bell}
                title="No unread notifications"
                description="You've read all your notifications. Great job staying organized!"
              />
            ) : (
              unseenNotifications.map((notification) => (
                <NotificationItem
                  key={notification.id}
                  id={notification.id}
                  type={notification.type as "ai-suggestion" | "reminder"}
                  planName={notification.planId ? `Plan #${notification.planId.substring(0, 8)}` : "General"}
                  message={notification.message}
                  seen={notification.seen}
                  createdAt={new Date(notification.createdAt).toLocaleString()}
                  onDismiss={() => handleDismiss(notification.id)}
                />
              ))
            )}
          </TabsContent>
        </Tabs>
      </main>

      <MobileNav />
    </div>
  );
}
