import {
  Avatar,
  Dropdown,
  MenuProps,
  Space,
  Typography,
  Breadcrumb,
} from "antd";
import { useAuth } from "../../hooks/useAuth";
import { Bell, ChevronDown, LogOut, Menu, UserRound, Home, CheckCircle2, XCircle, Info, CheckCircle } from "lucide-react";
import { useNavigate, useLocation, Link } from "react-router-dom";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { ROUTE_LABELS } from "@/router/AppRouter";
import { Badge, List, Button } from "antd";
import { useEffect, useState } from "react";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";

dayjs.extend(relativeTime);

interface HeaderProps {
  onMenuClick: () => void;
}

const Header: React.FC<HeaderProps> = ({ onMenuClick }) => {
  const { user, logout, isInstitution } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const [notifications, setNotifications] = useState<any[]>([]);
  
  const fetchNotifications = async () => {
    try {
      const res = await API_Instance.get(`${API_Constants.notifications}?type=link&limit=100`);
      setNotifications(res.data.data);
    } catch (err) {
      console.error("Failed to fetch notifications", err);
    }
  };

  useEffect(() => {
    if (user) {
      fetchNotifications();
      const interval = setInterval(() => {
        fetchNotifications();
      }, 10000); // Every 10 seconds
      
      return () => clearInterval(interval);
    }
  }, [user]);

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

  const handleMarkAsReadOnly = async (notif: any) => {
    if (!notif.isRead) {
      try {
        await API_Instance.patch(`${API_Constants.notifications}/${notif.id}/read`);
        setNotifications(prev => prev.filter(n => n.id !== notif.id));
      } catch (err) {
        console.error("Failed to mark as read", err);
      }
    }
  };

  const handleNotificationClick = async (notif: any) => {
    await handleMarkAsReadOnly(notif);
    if (notif.redirectUrl) {
      navigate(notif.redirectUrl);
    }
  };

  const handleClearAll = async (e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      await API_Instance.patch(`${API_Constants.notifications}/read-all`);
      setNotifications([]);
    } catch (err) {
      console.error("Failed to clear all", err);
    }
  };

  const getNotificationIcon = (title: string) => {
    const t = title.toLowerCase();
    if (t.includes('approved')) return <CheckCircle2 size={16} className="text-green-500" />;
    if (t.includes('rejected')) return <XCircle size={16} className="text-red-500" />;
    return <Info size={16} className="text-blue-500" />;
  };

  const getNotificationColor = (title: string) => {
    const t = title.toLowerCase();
    if (t.includes('approved')) return 'bg-emerald-50/50 hover:bg-emerald-50';
    if (t.includes('rejected')) return 'bg-rose-50/50 hover:bg-rose-50';
    return 'bg-sky-50/50 hover:bg-sky-50';
  };

  const renderDescription = (desc: string) => {
    if (!desc) return null;
    const parts = desc.split(/"([^"]+)"/g);
    return (
      <span className="text-[13px] leading-snug text-slate-500">
        {parts.map((part, i) => {
          if (i % 2 === 1) {
            return <strong key={i} className="text-slate-700 font-semibold">"{part}"</strong>;
          }
          if (part.includes("Reason: ")) {
            const split = part.split("Reason: ");
            return (
              <span key={i}>
                {split[0]}
              </span>
            );
          }
          return <span key={i}>{part}</span>;
        })}
      </span>
    );
  };

  const renderNotificationDropdown = () => (
    <div className="bg-white rounded-lg shadow-lg border border-slate-100 overflow-hidden flex flex-col w-[340px]">
      {unreadNotifications.length > 0 ? (
        <>
          <div className="flex justify-between items-center px-3 py-3 border-b border-slate-100 bg-white" onClick={(e) => e.stopPropagation()}>
            <span className="font-semibold text-slate-700">Notifications</span>
            <Button type="text" size="small" onClick={handleClearAll} className="text-xs text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-md flex items-center px-0">
              <CheckCircle size={14} /> Clear All
            </Button>
          </div>
          <div className="max-h-96 overflow-y-auto custom-scrollbar flex flex-col">
            {unreadNotifications.map((item: any) => (
              <div 
                key={item.id}
                className={`cursor-pointer px-3 py-3 border-b border-slate-100/50 transition-colors ${getNotificationColor(item.title)} flex items-start gap-3`}
                onClick={() => handleMarkAsReadOnly(item)}
              >
                <div className="mt-0.5 shadow-sm shrink-0">
                  {getNotificationIcon(item.title)}
                </div>
                <div className="flex flex-col flex-grow w-full">
                  <span className="text-sm font-semibold text-slate-800">{item.title}</span>
                  <div className="flex flex-col mt-1">
                    {renderDescription(item.description)}
                    <div className="flex justify-between items-center mt-2.5">
                      <span className="text-[11px] font-medium text-slate-400">{dayjs(item.createdAt).fromNow()}</span>
                      {item.redirectUrl && (
                        <span 
                          className="text-[12px] font-semibold text-blue-600 hover:text-blue-700 hover:underline cursor-pointer"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleNotificationClick(item);
                          }}
                        >
                          View
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </>
      ) : (
        <div className="p-8 text-center flex flex-col items-center justify-center gap-2 bg-white">
          <div className="h-12 w-12 rounded-full bg-slate-50 flex items-center justify-center">
            <Bell size={24} className="text-slate-300" />
          </div>
          <span className="text-slate-500 text-sm font-medium">No new notifications</span>
          <span className="text-slate-400 text-xs">You're all caught up!</span>
        </div>
      )}
    </div>
  );

  const fullName = isInstitution
    ? `${user?.institutionName}`
    : `${user?.firstName} ${user?.lastName || ""}`;

  const fullNameTag = isInstitution
    ? `${user?.institutionName
      ?.split(" ")
      ?.map((word: string) => word[0].toUpperCase())
      .join("") || ""
    }`
    : `${user?.firstName?.[0]?.toUpperCase() || ""}${user?.lastName?.[0]?.toUpperCase() || ""
    }`;

  const handleLogout = () => {
    logout();
    navigate(ROUTE_CONSTANTS.Login);
  };

  const items: MenuProps["items"] = [
    {
      label: (
        <Space className="flex items-center !text-[gray]">
          <UserRound className="h-4 w-4" />
          <Typography.Text className="!text-[gray]">Profile</Typography.Text>
        </Space>
      ),
      key: "0",
      onClick: () => navigate(ROUTE_CONSTANTS.Profile),
    },
    {
      type: "divider",
    },
    {
      label: (
        <Space className="flex items-center !text-[gray]">
          <LogOut className="h-4 w-4" />
          <Typography.Text className="!text-[gray]">Logout</Typography.Text>
        </Space>
      ),
      key: "3",
      onClick: handleLogout,
    },
  ];

  // Dynamic Breadcrumb Logic
  const breadcrumbItems = () => {
    const pathSnippets = location.pathname.split("/").filter(Boolean);

    // Precompute route metadata once
    const routeMatchers = Object.entries(ROUTE_CONSTANTS).map(([key, route]) => {
      const parts = route.split("/").filter(Boolean);

      return {
        route,
        parts,
        label: ROUTE_LABELS[route],
        regex: new RegExp(`^${route.replace(/:[^/]+/g, "[^/]+")}$`),
      };
    });

    const extraBreadcrumbItems = [];
    let currentPath = "";

    for (let i = 0; i < pathSnippets.length; i++) {
      const snippet = pathSnippets[i];
      currentPath += `/${snippet}`;

      // O(1)-style single pass over precomputed routes
      const dynamicMatch = routeMatchers.find(({ parts }) => {
        return (
          parts[i]?.startsWith(":") &&
          parts.slice(0, i).every((part, idx) => {
            return part.startsWith(":") || part === pathSnippets[idx];
          })
        );
      });

      // Dynamic segment: update previous breadcrumb label only
      if (dynamicMatch && extraBreadcrumbItems.length) {
        const matchedLabel = routeMatchers.find(({ regex }) => regex.test(currentPath));

        if (matchedLabel?.label) {
          extraBreadcrumbItems[extraBreadcrumbItems.length - 1] = {
            ...extraBreadcrumbItems[extraBreadcrumbItems.length - 1],
            title: matchedLabel.label,
          };
        }

        continue;
      }

      const title =
        ROUTE_LABELS[currentPath] ??
        snippet.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase());

      extraBreadcrumbItems.push({
        key: currentPath,
        title: i === pathSnippets.length - 1 ? (title) : (<Link to={currentPath}>{title}</Link>),
        label: title,
      });
    }
    return [
      {
        key: "dashboard",
        title: (
          <Link to="/">
            <Space size={4}>
              <Home size={14} />
              <span>Dashboard</span>
            </Space>
          </Link>
        ),
      },
      ...extraBreadcrumbItems.map((item, idx) => {
        if (idx === extraBreadcrumbItems.length - 1) {
          return {
            ...item,
            title: item.label,
          };
        }
        return item;
      }),
    ];
  };

  return (
    <header className="flex items-center justify-between h-16 px-6 bg-white border-b">
      <div className="flex items-center">
        <button
          onClick={onMenuClick}
          className="md:hidden mr-4 text-gray-600"
          aria-label="Open sidebar"
        >
          <Menu className="h-6 w-6" />
        </button>
        <div className="hidden sm:block">
          <Breadcrumb items={breadcrumbItems()} />
        </div>
      </div>
      <div className="flex items-center space-x-4">
        {/* Notifications Dropdown */}
        <Dropdown 
          dropdownRender={renderNotificationDropdown} 
          trigger={["click"]} 
          placement="bottomRight"
          overlayStyle={{ padding: 0 }}
          overlayClassName="notification-dropdown-overlay"
        >
          <div className="cursor-pointer flex items-center justify-center p-2 rounded-full hover:bg-slate-100 transition-colors mr-2">
            <Badge count={unreadCount} size="small" offset={[2, 0]}>
              <Bell className="h-5 w-5 text-slate-600" />
            </Badge>
          </div>
        </Dropdown>

        <Dropdown menu={{ items }} trigger={["click"]}>
          <div className="flex items-center group cursor-pointer">
            <Avatar className="bg-[#22C55E] flex items-center justify-center font-bold">
              {fullNameTag}
            </Avatar>
            <div className="ml-3 hidden md:block">
              <p className="text-sm font-semibold text-gray-800 leading-tight">
                {fullName}
              </p>
              <p className="text-[10px] uppercase font-bold text-gray-400 tracking-wider">
                {user?.role}
              </p>
            </div>
            <ChevronDown className="h-4 w-4 ml-2 text-gray-400 transition-transform group-hover:translate-y-0.5" />
          </div>
        </Dropdown>
      </div>
    </header>
  );
};

export default Header;

