"use client";

import { useEffect, useRef, useState } from "react";
import { getApiUrl } from '@/lib/api';

interface Notification {
  id: number;
  type: string;
  title: string;
  message: string;
  entityType: string;
  entityId: number;
  isRead: boolean;
  createdAt: string;
}

function entityHref(entityType: string, entityId: number) {
  switch (entityType) {
    case "SERVICE_CALL":
      return `/service-calls/${entityId}`;
    case "MACHINE":
      return `/machines/${entityId}`;
    case "PART":
      return `/parts`;
    default:
      return "#";
  }
}

export default function Header() {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  function loadNotifications() {
    fetch(getApiUrl("/api/notifications"))
      .then((res) => res.json())
      .then((data) => {
        setNotifications(data);
        setUnreadCount(data.filter((n: Notification) => !n.isRead).length);
      })
      .catch((err) => console.error(err));
  }

  useEffect(() => {
    loadNotifications();
    const interval = setInterval(loadNotifications, 60000);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  function markRead(id: number) {
    fetch(getApiUrl(`/api/notifications/${id}/read`), {
      method: "PATCH",
    }).then(loadNotifications);
  }

  function markAllRead() {
    fetch(getApiUrl("/api/notifications/read-all"), {
      method: "PATCH",
    }).then(loadNotifications);
  }

  function formatTime(date: string) {
    return new Date(date).toLocaleString("en-GB", {
      day: "2-digit",
      month: "short",
      hour: "2-digit",
      minute: "2-digit",
    });
  }

  return (
    <header className="h-20 bg-white border-b border-slate-200 px-10 flex items-center justify-between">
      <div>
        <h1 className="text-xl font-bold text-slate-900">Dashboard</h1>
        <p className="text-sm text-slate-500">Super Admin overview</p>
      </div>

      <div className="flex items-center gap-4">
        <input
          placeholder="Search..."
          className="w-80 rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
        />

        <div className="relative" ref={ref}>
          <button
            onClick={() => setOpen((prev) => !prev)}
            className="relative rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700"
          >
            Notifications
            {unreadCount > 0 && (
              <span className="absolute -right-2 -top-2 flex h-5 min-w-5 items-center justify-center rounded-full bg-[#EE302B] px-1 text-xs font-bold text-white">
                {unreadCount}
              </span>
            )}
          </button>

          {open && (
            <div className="absolute right-0 z-50 mt-2 w-96 rounded-2xl border border-slate-200 bg-white shadow-lg">
              <div className="flex items-center justify-between border-b border-slate-100 px-5 py-3">
                <span className="font-bold text-slate-900">Notifications</span>
                {unreadCount > 0 && (
                  <button
                    onClick={markAllRead}
                    className="text-xs font-semibold text-[#1296E8]"
                  >
                    Mark all read
                  </button>
                )}
              </div>

              <div className="max-h-96 overflow-y-auto">
                {notifications.length === 0 ? (
                  <p className="px-5 py-8 text-center text-sm text-slate-500">
                    No notifications.
                  </p>
                ) : (
                  notifications.slice(0, 20).map((n) => (
                    <a
                      key={n.id}
                      href={entityHref(n.entityType, n.entityId)}
                      onClick={() => !n.isRead && markRead(n.id)}
                      className={`block border-b border-slate-50 px-5 py-3 text-sm hover:bg-slate-50 ${
                        n.isRead ? "" : "bg-[#1296E8]/5"
                      }`}
                    >
                      <p className="font-semibold text-slate-900">{n.title}</p>
                      <p className="mt-0.5 text-slate-600">{n.message}</p>
                      <p className="mt-1 text-xs text-slate-400">
                        {formatTime(n.createdAt)}
                      </p>
                    </a>
                  ))
                )}
              </div>
            </div>
          )}
        </div>

        <div className="rounded-xl bg-[#EE302B] px-4 py-2.5 text-sm font-semibold text-white">
          Super Admin
        </div>
      </div>
    </header>
  );
}
