"use client";

import { formatShortNumber } from "@/lib/format-number";
import gsap from "gsap";
import { useLayoutEffect, useMemo, useRef } from "react";
import { TenderIcon } from "./icons";

type Props = {
  noticeTypes: { type: string; count: number }[];
  isLoading: boolean;
};

const COLORS = [
  "from-[#5750F1] to-[#7B6CFF]",
  "from-[#0ABEF9] to-[#3C50E0]",
  "from-emerald-500 to-emerald-400",
  "from-orange-light to-amber-400",
  "from-[#F23030] to-[#F56060]",
  "from-[#8155FF] to-[#0ABEF9]",
];

function labelize(s: string) {
  return s
    .replace(/_/g, " ")
    .toLowerCase()
    .replace(/(^|\s)\w/g, (m) => m.toUpperCase());
}

export function NoticeTypeBreakdown({ noticeTypes, isLoading }: Props) {
  const rootRef = useRef<HTMLDivElement>(null);
  const total = useMemo(
    () => noticeTypes.reduce((a, b) => a + b.count, 0) || 1,
    [noticeTypes],
  );

  useLayoutEffect(() => {
    const reduced =
      typeof window !== "undefined" &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const ctx = gsap.context(() => {
      if (reduced) return;
      gsap.from(rootRef.current, {
        opacity: 0,
        y: 24,
        duration: 0.6,
        ease: "power3.out",
        delay: 0.4,
      });
      gsap.fromTo(
        "[data-bar-fill]",
        { width: 0 },
        {
          width: (i, el) => el.getAttribute("data-final-width") + "%",
          duration: 0.9,
          stagger: 0.07,
          delay: 0.6,
          ease: "power2.out",
        },
      );
    }, rootRef);
    return () => ctx.revert();
  }, [noticeTypes.length]);

  return (
    <div
      ref={rootRef}
      className="overflow-hidden rounded-2xl bg-white p-5 shadow-1 ring-1 ring-stroke dark:bg-gray-dark dark:ring-stroke-dark dark:shadow-card md:p-6"
    >
      <div className="mb-5 flex items-center gap-2">
        <span className="inline-flex size-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
          <TenderIcon className="size-5" />
        </span>
        <div>
          <h2 className="text-base font-bold text-dark dark:text-white">
            Notice Type Mix
          </h2>
          <p className="text-xs text-dark-6">Distribution across form types</p>
        </div>
      </div>

      <ul className="space-y-3">
        {(isLoading
          ? Array.from({ length: 5 }).map((_, i) => ({
              type: "—",
              count: 0,
              i,
            }))
          : noticeTypes.map((n, i) => ({ ...n, i }))
        ).map((n) => {
          const pct = isLoading ? 0 : Math.round((n.count / total) * 100);
          return (
            <li key={`${n.type}-${n.i}`} className="space-y-1.5">
              <div className="flex items-center justify-between text-sm">
                <span className="truncate font-medium text-dark dark:text-white">
                  {isLoading ? "Loading…" : labelize(n.type)}
                </span>
                <span className="tabular-nums text-xs font-semibold text-dark-5 dark:text-dark-6">
                  {isLoading
                    ? "—"
                    : `${formatShortNumber(n.count, { plus: true })} · ${pct}%`}
                </span>
              </div>
              <div className="relative h-2.5 w-full overflow-hidden rounded-full bg-gray-2 dark:bg-dark-3">
                <div
                  data-bar-fill
                  data-final-width={pct}
                  className={`relative h-full overflow-hidden rounded-full bg-gradient-to-r ${COLORS[n.i % COLORS.length]} shadow-sm`}
                  style={{ width: 0 }}
                >
                  <span
                    aria-hidden
                    className="absolute inset-y-0 -left-1/3 w-1/3 animate-[shimmer_2.4s_ease-in-out_infinite] bg-gradient-to-r from-transparent via-white/40 to-transparent"
                  />
                </div>
              </div>
            </li>
          );
        })}
        {!isLoading && noticeTypes.length === 0 && (
          <li className="py-6 text-center text-sm text-dark-6">
            No notice data available.
          </li>
        )}
      </ul>
    </div>
  );
}
