"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { Bell, CheckCircle2, XCircle, AlertCircle, Clock, Check, CheckCheck, ThumbsUp, ThumbsDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import type { NotificationType } from "@/lib/types";

interface NotificationItem {
  id: string;
  type: NotificationType;
  message: string;
  postId: string | null;
  read: boolean;
  createdAt: string;
}

const TYPE_CONFIG: Record<NotificationType, { icon: typeof CheckCircle2; color: string; bgColor: string }> = {
  POST_PUBLISHED: { icon: CheckCircle2, color: "text-green-600", bgColor: "bg-green-50" },
  POST_FAILED: { icon: XCircle, color: "text-red-600", bgColor: "bg-red-50" },
  APPROVAL_NEEDED: { icon: AlertCircle, color: "text-amber-600", bgColor: "bg-amber-50" },
  POST_SCHEDULED: { icon: Clock, color: "text-blue-600", bgColor: "bg-blue-50" },
  POST_APPROVED: { icon: ThumbsUp, color: "text-emerald-600", bgColor: "bg-emerald-50" },
  POST_REJECTED: { icon: ThumbsDown, color: "text-orange-600", bgColor: "bg-orange-50" },
};

function timeAgo(dateStr: string): string {
  const now = Date.now();
  const d = new Date(dateStr).getTime();
  const diffMs = now - d;
  const mins = Math.floor(diffMs / 60000);
  if (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 7) return `${days}d ago`;
  return new Date(dateStr).toLocaleDateString();
}

export function NotificationCenter() {
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  // BUG-F-R2-05 fix: debounce toggle to prevent Sheet animation timeout
  const toggleCooldown = useRef(false);
  const handleToggle = (next: boolean) => {
    if (toggleCooldown.current) return;
    toggleCooldown.current = true;
    setOpen(next);
    setTimeout(() => { toggleCooldown.current = false; }, 400);
  };
  const unreadCount = notifications.filter((n) => !n.read).length;

  const fetchNotifications = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/v1/notifications?limit=50");
      if (res.ok) {
        const data = await res.json();
        setNotifications(data);
      }
    } catch {
      // Silently fail
    } finally {
      setLoading(false);
    }
  }, []);

  // Fetch on mount and when panel opens
  useEffect(() => {
    fetchNotifications();
  }, [fetchNotifications]);

  useEffect(() => {
    if (open) fetchNotifications();
  }, [open, fetchNotifications]);

  // Poll every 30s for new notifications
  useEffect(() => {
    const interval = setInterval(fetchNotifications, 30000);
    return () => clearInterval(interval);
  }, [fetchNotifications]);

  const markAsRead = async (id: string) => {
    try {
      await fetch(`/api/v1/notifications/${id}/read`, { method: "POST" });
      setNotifications((prev) =>
        prev.map((n) => (n.id === id ? { ...n, read: true } : n))
      );
    } catch {
      // Silently fail
    }
  };

  const markAllRead = async () => {
    try {
      await fetch("/api/v1/notifications/read-all", { method: "POST" });
      setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
    } catch {
      // Silently fail
    }
  };

  return (
    <Sheet open={open} onOpenChange={handleToggle}>
      <SheetTrigger
        render={
          <button className="relative min-h-[44px] min-w-[44px] flex items-center justify-center rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors" aria-label="Notifications">
            <Bell className="h-[18px] w-[18px]" />
            {unreadCount > 0 && (
              <span className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-medium text-white leading-none">
                {unreadCount > 99 ? "99+" : unreadCount}
              </span>
            )}
          </button>
        }
      />
      <SheetContent side="right" className="w-96 p-0 bg-white">
        <SheetHeader className="border-b border-gray-100 px-4 py-3">
          <div className="flex items-center justify-between">
            <SheetTitle className="text-base font-semibold text-gray-900">
              Notifications
            </SheetTitle>
            {unreadCount > 0 && (
              <Button
                variant="ghost"
                size="sm"
                className="h-7 text-xs text-gray-500 hover:text-gray-700"
                onClick={markAllRead}
              >
                <CheckCheck className="h-3.5 w-3.5 mr-1" />
                Mark all read
              </Button>
            )}
          </div>
        </SheetHeader>

        <div className="overflow-y-auto max-h-[calc(100vh-80px)]">
          {loading && notifications.length === 0 ? (
            <div className="py-12 text-center text-sm text-gray-500">Loading...</div>
          ) : notifications.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16">
              <Bell className="h-10 w-10 text-gray-200 mb-3" />
              <p className="text-sm font-medium text-gray-500">No notifications yet</p>
              <p className="text-xs text-gray-400 mt-1">
                You&apos;ll see updates when posts are published, scheduled, or need attention.
              </p>
            </div>
          ) : (
            <div className="divide-y divide-gray-50">
              {notifications.map((notif) => {
                const config = TYPE_CONFIG[notif.type] ?? TYPE_CONFIG.POST_PUBLISHED;
                const Icon = config.icon;
                return (
                  <div
                    key={notif.id}
                    className={`flex gap-3 px-4 py-3 transition-colors ${
                      notif.read ? "bg-white" : "bg-blue-50/30"
                    }`}
                  >
                    <div className={`mt-0.5 rounded-md p-1.5 ${config.bgColor} shrink-0`}>
                      <Icon className={`h-3.5 w-3.5 ${config.color}`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className={`text-sm ${notif.read ? "text-gray-600" : "text-gray-900 font-medium"}`}>
                        {notif.message}
                      </p>
                      <p className="text-xs text-gray-400 mt-0.5">{timeAgo(notif.createdAt)}</p>
                    </div>
                    {!notif.read && (
                      <button
                        onClick={() => markAsRead(notif.id)}
                        className="shrink-0 p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"
                        title="Mark as read"
                      >
                        <Check className="h-3.5 w-3.5" />
                      </button>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </SheetContent>
    </Sheet>
  );
}
