import { useState, useRef, useEffect } from "react";
import {
  Bell,
  CheckCheck,
  Info,
  AlertTriangle,
  AlertCircle,
  CheckCircle,
} from "lucide-react";
import { useNavigate } from "react-router-dom";

const LIST_API = "http://openplate.my.id/api/notifikasi/list.php";
const READ_API = "http://openplate.my.id/api/notifikasi/mark_read.php";
const READ_ALL_API = "http://openplate.my.id/api/notifikasi/mark_all_read.php";

const typeIcon = {
  info: <Info className="w-4 h-4 text-blue-500" />,
  warning: <AlertTriangle className="w-4 h-4 text-amber-500" />,
  danger: <AlertCircle className="w-4 h-4 text-red-500" />,
  alert: <AlertCircle className="w-4 h-4 text-red-500" />,
  success: <CheckCircle className="w-4 h-4 text-green-500" />,
};

const formatTime = (value) => {
  if (!value) return "Baru saja";

  const date = new Date(String(value).replace(" ", "T"));
  const now = new Date();
  const diff = Math.floor((now - date) / 1000);

  if (Number.isNaN(diff)) return "Baru saja";
  if (diff < 60) return "Baru saja";
  if (diff < 3600) return `${Math.floor(diff / 60)} menit lalu`;
  if (diff < 86400) return `${Math.floor(diff / 3600)} jam lalu`;

  return date.toLocaleDateString("id-ID", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
};

const getNotifType = (item) => {
  const text = `${item.judul || ""} ${item.pesan || ""}`.toLowerCase();

  if (text.includes("tidak valid") || text.includes("bermasalah")) {
    return "danger";
  }

  if (text.includes("valid") || text.includes("selesai")) {
    return "success";
  }

  if (text.includes("tindak lanjut") || text.includes("diproses")) {
    return "warning";
  }

  if (text.includes("pengaduan baru") || text.includes("menunggu validasi")) {
    return "warning";
  }

  return "info";
};

export default function NotificationBell() {
  const [notifications, setNotifications] = useState([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  const ref = useRef(null);
  const navigate = useNavigate();

  const getRole = () => {
    const role = localStorage.getItem("role");
    return role && role !== "masyarakat" ? role : "publik";
  };

  const getSppgId = () => {
    return localStorage.getItem("sppg_id") || "";
  };

  const loadNotifications = async () => {
    try {
      const role = getRole();

      if (role === "publik") {
        setNotifications([]);
        return;
      }

      const sppgId = getSppgId();

      const url = `${LIST_API}?role=${encodeURIComponent(
        role
      )}&sppg_id=${encodeURIComponent(sppgId)}`;

      const res = await fetch(url);

      if (!res.ok) {
        throw new Error(`HTTP Error ${res.status}`);
      }

      const result = await res.json();

      if (result.success && Array.isArray(result.data)) {
        const mapped = result.data.map((item) => ({
          id: item.id,
          type: getNotifType(item),
          title: item.judul || "Notifikasi",
          message: item.pesan || "-",
          link: item.link || null,
          isRead: Number(item.is_read) === 1,
          time: formatTime(item.created_at),
          created_at: item.created_at,
        }));

        setNotifications(mapped);
      } else {
        setNotifications([]);
      }
    } catch (err) {
      console.error("Gagal mengambil notifikasi:", err);
      setNotifications([]);
    }
  };

  useEffect(() => {
    loadNotifications();

    const interval = setInterval(() => {
      loadNotifications();
    }, 5000);

    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    const handler = (e) => {
      if (ref.current && !ref.current.contains(e.target)) {
        setOpen(false);
      }
    };

    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const unreadCount = notifications.filter((n) => !n.isRead).length;

  const markRead = async (id) => {
    try {
      const formData = new FormData();
      formData.append("id", id);

      await fetch(READ_API, {
        method: "POST",
        body: formData,
      });

      setNotifications((prev) =>
        prev.map((n) => (String(n.id) === String(id) ? { ...n, isRead: true } : n))
      );
    } catch (err) {
      console.error("Gagal menandai notifikasi dibaca:", err);
    }
  };

  const markAllRead = async () => {
    try {
      setLoading(true);

      const role = getRole();
      const sppgId = getSppgId();

      const formData = new FormData();
      formData.append("role", role);
      formData.append("sppg_id", sppgId);

      await fetch(READ_ALL_API, {
        method: "POST",
        body: formData,
      });

      setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
    } catch (err) {
      console.error("Gagal menandai semua notifikasi dibaca:", err);
    } finally {
      setLoading(false);
    }
  };

  const handleClickNotification = async (notif) => {
    await markRead(notif.id);
    setOpen(false);

    if (notif.link) {
      navigate(notif.link);
    }
  };

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={() => {
          setOpen(!open);
          loadNotifications();
        }}
        className="relative p-2 rounded-full hover:bg-muted transition-colors"
        aria-label="Buka notifikasi"
      >
        <Bell className="w-5 h-5 text-foreground/70" />

        {unreadCount > 0 && (
          <span className="absolute -top-0.5 -right-0.5 bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center min-w-[18px] min-h-[18px] px-1">
            {unreadCount > 99 ? "99+" : unreadCount}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-80 sm:w-96 bg-card border border-border rounded-xl shadow-xl z-50 overflow-hidden">
          <div className="flex items-center justify-between px-4 py-3 border-b border-border">
            <div>
              <p className="font-bold text-sm text-foreground">Notifikasi</p>
              <p className="text-xs text-muted-foreground">
                Update otomatis setiap 5 detik
              </p>
            </div>

            {unreadCount > 0 && (
              <button
                type="button"
                disabled={loading}
                onClick={markAllRead}
                className="flex items-center gap-1 text-xs text-primary hover:underline disabled:opacity-50"
              >
                <CheckCheck className="w-3.5 h-3.5" />
                Tandai semua dibaca
              </button>
            )}
          </div>

          <div className="max-h-80 overflow-y-auto divide-y divide-border">
            {notifications.length === 0 ? (
              <div className="px-4 py-8 text-center">
                <p className="text-sm font-medium text-foreground">
                  Tidak ada notifikasi
                </p>
                <p className="text-xs text-muted-foreground mt-1">
                  Notifikasi pengaduan, validasi, dan tindak lanjut akan muncul di sini.
                </p>
              </div>
            ) : (
              notifications.map((n) => (
                <button
                  key={n.id}
                  type="button"
                  onClick={() => handleClickNotification(n)}
                  className={`w-full text-left px-4 py-3 hover:bg-muted/50 transition-colors flex gap-3 ${
                    !n.isRead ? "bg-primary/5" : ""
                  }`}
                >
                  <div className="mt-0.5 flex-shrink-0">
                    {typeIcon[n.type] || typeIcon.info}
                  </div>

                  <div className="flex-1 min-w-0">
                    <p
                      className={`text-sm font-semibold ${
                        !n.isRead ? "text-foreground" : "text-muted-foreground"
                      }`}
                    >
                      {n.title}
                    </p>

                    <p className="text-xs text-muted-foreground mt-0.5 leading-relaxed line-clamp-3">
                      {n.message}
                    </p>

                    <p className="text-xs text-muted-foreground/70 mt-1">
                      {n.time}
                    </p>
                  </div>

                  {!n.isRead && (
                    <div className="w-2 h-2 bg-primary rounded-full mt-1.5 flex-shrink-0" />
                  )}
                </button>
              ))
            )}
          </div>

          <div className="px-4 py-2 border-t border-border">
            <p className="text-xs text-center text-muted-foreground">
              {notifications.length} notifikasi · {unreadCount} belum dibaca
            </p>
          </div>
        </div>
      )}
    </div>
  );
}