import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { 
  Bell, 
  Check, 
  Trash2, 
  CheckCheck, 
  Mail, 
  AlertCircle, 
  Info, 
  Trophy,
  DollarSign,
  Calendar,
  TrendingUp,
  Sparkles
} from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { useToast } from "@/hooks/use-toast";
import { Link } from "wouter";

interface Notification {
  id: number;
  userId: string;
  organizationId: number | null;
  type: string;
  title: string;
  message: string;
  link: string | null;
  isRead: boolean;
  readAt: string | null;
  metadata: any;
  createdAt: string;
}

export default function NotificationsPage() {
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState<"all" | "unread">("all");

  const { data: allNotifications = [], isLoading: isLoadingAll } = useQuery<Notification[]>({
    queryKey: ["/api/notifications"],
  });

  const { data: unreadNotifications = [], isLoading: isLoadingUnread } = useQuery<Notification[]>({
    queryKey: ["/api/notifications/unread"],
  });

  const markAsReadMutation = useMutation({
    mutationFn: async (id: number) => {
      return apiRequest("POST", `/api/notifications/${id}/read`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/notifications"] });
      queryClient.invalidateQueries({ queryKey: ["/api/notifications/unread"] });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to mark notification as read",
        variant: "destructive",
      });
    },
  });

  const markAllAsReadMutation = useMutation({
    mutationFn: async () => {
      return apiRequest("POST", "/api/notifications/read-all");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/notifications"] });
      queryClient.invalidateQueries({ queryKey: ["/api/notifications/unread"] });
      toast({
        title: "Success",
        description: "All notifications marked as read",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to mark all notifications as read",
        variant: "destructive",
      });
    },
  });

  const deleteNotificationMutation = useMutation({
    mutationFn: async (id: number) => {
      return apiRequest("DELETE", `/api/notifications/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/notifications"] });
      queryClient.invalidateQueries({ queryKey: ["/api/notifications/unread"] });
      toast({
        title: "Success",
        description: "Notification deleted",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to delete notification",
        variant: "destructive",
      });
    },
  });

  const getNotificationIcon = (type: string) => {
    switch (type) {
      case "success":
        return <Check className="h-5 w-5 text-green-500" />;
      case "warning":
        return <AlertCircle className="h-5 w-5 text-amber-500" />;
      case "error":
        return <AlertCircle className="h-5 w-5 text-red-500" />;
      case "match":
        return <Trophy className="h-5 w-5 text-blue-500" />;
      case "payment":
        return <DollarSign className="h-5 w-5 text-green-500" />;
      case "attendance":
        return <Calendar className="h-5 w-5 text-purple-500" />;
      case "performance":
        return <TrendingUp className="h-5 w-5 text-indigo-500" />;
      default:
        return <Info className="h-5 w-5 text-blue-500" />;
    }
  };

  const getNotificationColor = (type: string) => {
    switch (type) {
      case "success":
        return "bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-900/50";
      case "warning":
        return "bg-amber-50 dark:bg-amber-950/30 border-amber-200 dark:border-amber-900/50";
      case "error":
        return "bg-red-50 dark:bg-red-950/30 border-red-200 dark:border-red-900/50";
      case "match":
        return "bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900/50";
      case "payment":
        return "bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-900/50";
      case "attendance":
        return "bg-purple-50 dark:bg-purple-950/30 border-purple-200 dark:border-purple-900/50";
      case "performance":
        return "bg-indigo-50 dark:bg-indigo-950/30 border-indigo-200 dark:border-indigo-900/50";
      default:
        return "bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900/50";
    }
  };

  const notifications = activeTab === "all" ? allNotifications : unreadNotifications;
  const isLoading = activeTab === "all" ? isLoadingAll : isLoadingUnread;

  const NotificationCard = ({ notification }: { notification: Notification }) => {
    const content = (
      <Card
        className={`p-4 transition-all hover:shadow-md border-l-4 ${
          !notification.isRead
            ? `${getNotificationColor(notification.type)} shadow-sm`
            : "bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800"
        }`}
      >
        <div className="flex items-start gap-4">
          <div className={`p-3 rounded-xl ${!notification.isRead ? "bg-white dark:bg-slate-800/50" : "bg-slate-50 dark:bg-slate-800/30"}`}>
            {getNotificationIcon(notification.type)}
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-start justify-between gap-2">
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <h3 className="font-semibold text-slate-900 dark:text-white text-sm">
                    {notification.title}
                  </h3>
                  {!notification.isRead && (
                    <Badge className="h-5 px-1.5 text-[10px] bg-blue-500">New</Badge>
                  )}
                </div>
                <p className="text-sm text-slate-600 dark:text-slate-400 line-clamp-2">
                  {notification.message}
                </p>
                <p className="text-xs text-slate-500 dark:text-slate-500 mt-2">
                  {formatDistanceToNow(new Date(notification.createdAt), { addSuffix: true })}
                </p>
              </div>
              <div className="flex items-center gap-1 flex-shrink-0">
                {!notification.isRead && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      markAsReadMutation.mutate(notification.id);
                    }}
                    className="h-8 w-8 p-0 hover:bg-blue-100 dark:hover:bg-blue-900/30"
                    data-testid={`button-mark-read-${notification.id}`}
                    aria-label="Mark as read"
                  >
                    <Check className="h-4 w-4 text-blue-600 dark:text-blue-400" />
                  </Button>
                )}
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    deleteNotificationMutation.mutate(notification.id);
                  }}
                  className="h-8 w-8 p-0 hover:bg-red-100 dark:hover:bg-red-900/30"
                  data-testid={`button-delete-${notification.id}`}
                  aria-label="Delete notification"
                >
                  <Trash2 className="h-4 w-4 text-red-600 dark:text-red-400" />
                </Button>
              </div>
            </div>
          </div>
        </div>
      </Card>
    );

    if (notification.link) {
      return (
        <Link to={notification.link}>
          <div className="cursor-pointer">{content}</div>
        </Link>
      );
    }

    return content;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 dark:from-slate-950 dark:via-slate-900 dark:to-slate-950">
      <div className="container mx-auto px-4 py-8 max-w-4xl">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-2">
            <div className="relative">
              <div className="absolute inset-0 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl blur-md opacity-50"></div>
              <div className="relative w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
                <Bell className="text-white w-6 h-6" />
              </div>
            </div>
            <div>
              <h1 className="text-3xl font-bold text-slate-900 dark:text-white">Notifications</h1>
              <p className="text-sm text-slate-600 dark:text-slate-400">
                Stay updated with your latest activities
              </p>
            </div>
          </div>
        </div>

        {/* Tabs and Actions */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
          <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as "all" | "unread")} className="w-full sm:w-auto">
            <TabsList className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700">
              <TabsTrigger value="all" className="gap-2" data-testid="tab-all">
                <Mail className="h-4 w-4" />
                All
                <Badge variant="secondary" className="ml-1 h-5 min-w-5 px-1.5 text-xs">
                  {allNotifications.length}
                </Badge>
              </TabsTrigger>
              <TabsTrigger value="unread" className="gap-2" data-testid="tab-unread">
                <Sparkles className="h-4 w-4" />
                Unread
                {unreadNotifications.length > 0 && (
                  <Badge className="ml-1 h-5 min-w-5 px-1.5 text-xs bg-blue-500">
                    {unreadNotifications.length}
                  </Badge>
                )}
              </TabsTrigger>
            </TabsList>
          </Tabs>

          {unreadNotifications.length > 0 && (
            <Button
              onClick={() => markAllAsReadMutation.mutate()}
              disabled={markAllAsReadMutation.isPending}
              className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white shadow-lg"
              data-testid="button-mark-all-read"
            >
              <CheckCheck className="h-4 w-4 mr-2" />
              Mark All as Read
            </Button>
          )}
        </div>

        {/* Notifications List */}
        {isLoading ? (
          <div className="space-y-4">
            {[...Array(5)].map((_, i) => (
              <Card key={i} className="p-4 animate-pulse">
                <div className="flex items-start gap-4">
                  <div className="w-12 h-12 bg-slate-200 dark:bg-slate-800 rounded-xl"></div>
                  <div className="flex-1 space-y-2">
                    <div className="h-4 bg-slate-200 dark:bg-slate-800 rounded w-3/4"></div>
                    <div className="h-3 bg-slate-200 dark:bg-slate-800 rounded w-full"></div>
                    <div className="h-3 bg-slate-200 dark:bg-slate-800 rounded w-1/4"></div>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        ) : notifications.length > 0 ? (
          <div className="space-y-3">
            {notifications.map((notification) => (
              <NotificationCard key={notification.id} notification={notification} />
            ))}
          </div>
        ) : (
          <Card className="p-12 text-center bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
            <div className="flex flex-col items-center gap-4">
              <div className="relative">
                <div className="absolute inset-0 bg-gradient-to-br from-blue-500/20 to-purple-600/20 rounded-full blur-xl"></div>
                <div className="relative w-20 h-20 bg-gradient-to-br from-blue-500/10 to-purple-600/10 rounded-full flex items-center justify-center">
                  <Bell className="w-10 h-10 text-slate-400 dark:text-slate-600" />
                </div>
              </div>
              <div>
                <h3 className="text-lg font-semibold text-slate-900 dark:text-white mb-1">
                  {activeTab === "unread" ? "No unread notifications" : "No notifications yet"}
                </h3>
                <p className="text-sm text-slate-600 dark:text-slate-400">
                  {activeTab === "unread"
                    ? "You're all caught up! All notifications have been read."
                    : "When you receive notifications, they'll appear here."}
                </p>
              </div>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}
