"use client";

import { useGetNotificationDetails } from "@/hooks/queries/useNotificationQueries";
import { sanitizeHtmlWithStyles } from "@/lib/utils";
import { BreadcrumbItem } from "@/types/shared";
import { capitalize, unixToDate } from "@/utils/shared";
import gsap from "gsap";
import { use, useLayoutEffect, useMemo, useRef } from "react";

interface IParams {
  params: Promise<{ id: string }>;
}

export interface IDetailItem {
  label: string;
  value: string;
  kind?: "text" | "status";
  tone?: string;
}

const prefersReducedMotion = () =>
  typeof window !== "undefined" &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

export const useNotificationDetailsPresenter = ({ params }: IParams) => {
  const { id } = use(params);
  const { data, isLoading } = useGetNotificationDetails(id);
  const notification = data?.data;

  const rootRef = useRef<HTMLDivElement>(null);

  const breadcrumbItems: BreadcrumbItem[] = [
    { href: "/", name: "Dashboard" },
    { href: "/notification-history", name: "Notification history" },
    { href: `/notification-history/${id}`, name: "Notification details" },
  ];

  const meta = useMemo(() => {
    if (!notification) return null;
    return {
      title: notification.title || "Notification",
      messageHtml: sanitizeHtmlWithStyles(notification.message || ""),
      hasMessage: !!notification.message,
      image: notification.image,
      priority: notification.priority,
      type: notification.type,
      status: notification.status,
      link: notification.link,
      createdAt: unixToDate({ unix: notification.created_at, hasTime: true }),
      recipient: notification.recipient?.full_name,
    };
  }, [notification]);

  const details: IDetailItem[] = useMemo(() => {
    if (!notification) return [];
    return [
      {
        label: "Recipient",
        value: notification.recipient?.full_name || "—",
      },
      { label: "Event type", value: notification.event_type || "—" },
      {
        label: "Status",
        value: capitalize(notification.status || "—"),
        kind: "status",
        tone: notification.status,
      },
      {
        label: "Priority",
        value: capitalize(notification.priority || "—"),
        kind: "status",
        tone: notification.priority,
      },
      {
        label: "Channel type",
        value: capitalize(notification.type || "—"),
        kind: "status",
        tone: notification.type,
      },
      {
        label: "Seen",
        value: notification.seen ? "Yes" : "No",
        kind: "status",
        tone: notification.seen ? "success" : "failed",
      },
      {
        label: "Seen at",
        value: unixToDate({ unix: notification.seen_at ?? 0, hasTime: true }),
      },
      {
        label: "Scheduled",
        value: notification.is_scheduled ? "Yes" : "No",
      },
    ];
  }, [notification]);

  // Complex GSAP intro + ambient motion, scoped to the page root.
  useLayoutEffect(() => {
    if (isLoading || !notification) return;

    const root = rootRef.current;
    if (!root) return;

    const ctx = gsap.context((self) => {
      if (prefersReducedMotion()) return;

      const q = self.selector!;

      // Entrance timeline
      const tl = gsap.timeline({ defaults: { ease: "power3.out" } });

      tl.from(root, { y: 28, duration: 0.7 }, 0)
        .from(
          q("[data-anim='breadcrumb']"),
          { y: -12, opacity: 0, duration: 0.5 },
          0.05,
        )
        .from(
          q("[data-anim='hero']"),
          { y: 40, opacity: 0, duration: 0.8 },
          0.1,
        )
        .from(
          q("[data-anim='hero-icon']"),
          {
            scale: 0,
            rotate: -120,
            opacity: 0,
            duration: 0.8,
            ease: "back.out(2)",
          },
          0.3,
        )
        .from(
          q("[data-title-inner]"),
          { y: 32, opacity: 0, duration: 0.7, ease: "back.out(1.6)" },
          0.4,
        )
        .from(
          q("[data-anim='badge']"),
          {
            y: 16,
            scale: 0.8,
            opacity: 0,
            duration: 0.5,
            stagger: 0.08,
            ease: "back.out(1.8)",
          },
          0.55,
        )
        .from(
          q("[data-anim='card']"),
          {
            y: 36,
            opacity: 0,
            scale: 0.94,
            duration: 0.6,
            stagger: 0.07,
            ease: "back.out(1.4)",
          },
          0.5,
        )
        .from(
          q("[data-anim='message']"),
          { y: 30, opacity: 0, duration: 0.7 },
          0.75,
        );

      // Ambient aurora rotation
      const aurora = q("[data-anim='aurora']");
      if (aurora.length) {
        gsap.to(aurora, {
          rotate: 360,
          duration: 44,
          ease: "none",
          repeat: -1,
        });
      }

      // Floating orbs
      gsap.to(q("[data-orb='a']"), {
        x: 40,
        y: -28,
        scale: 1.18,
        duration: 7,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
      });
      gsap.to(q("[data-orb='b']"), {
        x: -34,
        y: 26,
        scale: 1.12,
        duration: 8.5,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
      });
      gsap.to(q("[data-orb='c']"), {
        x: 24,
        y: 18,
        scale: 1.08,
        duration: 9.5,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
      });

      // Title shine sweep
      const shine = q("[data-anim='shine']");
      if (shine.length) {
        const shineTl = gsap.timeline({ repeat: -1, repeatDelay: 3.5 });
        shineTl
          .set(shine, { xPercent: -160, opacity: 0 })
          .to(shine, { opacity: 1, duration: 0.2, delay: 1.6 })
          .to(shine, { xPercent: 260, duration: 1.8, ease: "power2.inOut" }, "<")
          .to(shine, { opacity: 0, duration: 0.2 });
      }

      // Card hover lift + magnetic mouse parallax on the hero orbs
      const cards = q("[data-anim='card']");
      cards.forEach((card: Element) => {
        const el = card as HTMLElement;
        const enter = () =>
          gsap.to(el, { y: -6, duration: 0.35, ease: "power2.out" });
        const leave = () =>
          gsap.to(el, { y: 0, duration: 0.45, ease: "power2.out" });
        el.addEventListener("mouseenter", enter);
        el.addEventListener("mouseleave", leave);
      });

      const onMove = (e: MouseEvent) => {
        const r = root.getBoundingClientRect();
        const px = (e.clientX - r.left) / r.width - 0.5;
        const py = (e.clientY - r.top) / r.height - 0.5;
        gsap.to(q("[data-orb='a']"), {
          xPercent: px * 22,
          yPercent: py * 18,
          duration: 1.2,
          ease: "power2.out",
          overwrite: "auto",
        });
        gsap.to(q("[data-orb='b']"), {
          xPercent: px * -18,
          yPercent: py * 20,
          duration: 1.3,
          ease: "power2.out",
          overwrite: "auto",
        });
        gsap.to(q("[data-orb='c']"), {
          xPercent: px * 14,
          yPercent: py * -14,
          duration: 1.4,
          ease: "power2.out",
          overwrite: "auto",
        });
      };
      root.addEventListener("mousemove", onMove);

      return () => root.removeEventListener("mousemove", onMove);
    }, rootRef);

    return () => ctx.revert();
  }, [isLoading, notification]);

  return {
    isLoading,
    rootRef,
    breadcrumbItems,
    notification,
    meta,
    details,
  };
};
