"use client";

import { TTenderDetails } from "@/lib/api";
import { cn } from "@/lib/utils";
import gsap from "gsap";
import Link from "next/link";
import { useLayoutEffect, useRef } from "react";
import { ArrowRightIcon, SparkleIcon } from "./icons";

type Props = {
  tenders: TTenderDetails[];
  isLoading: boolean;
};

function relativeTime(unix: number) {
  if (!unix) return "—";
  const diff = Math.floor(Date.now() / 1000) - unix;
  if (diff < 60) return "just now";
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  const days = Math.floor(diff / 86400);
  if (days < 30) return `${days}d ago`;
  return new Date(unix * 1000).toLocaleDateString();
}

function statusTone(status: string) {
  const s = (status || "").toLowerCase();
  switch (s) {
    case "active":
      return "bg-green-light-7 text-green dark:bg-green/20 dark:text-green-light-3";
    case "awarded":
      return "bg-blue-light-5 text-blue dark:bg-blue/20 dark:text-blue-light-3";
    case "expired":
      return "bg-orange-light/10 text-orange-light";
    case "cancelled":
      return "bg-error-light-5 text-error dark:bg-error/20 dark:text-error-light";
    case "draft":
      return "bg-gray-2 text-dark-5 dark:bg-dark-3 dark:text-dark-6";
    default:
      return "bg-gray-2 text-dark-5 dark:bg-dark-3 dark:text-dark-6";
  }
}

export function RecentTenders({ tenders, isLoading }: Props) {
  const rootRef = useRef<HTMLDivElement>(null);

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

    const reduced =
      typeof window !== "undefined" &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const ctx = gsap.context(() => {
      if (reduced) return;
      gsap.from(root, {
        opacity: 0,
        y: 24,
        duration: 0.6,
        ease: "power3.out",
        delay: 0.35,
      });

      const rows = root.querySelectorAll("[data-recent-row]");
      if (rows.length > 0) {
        gsap.from(rows, {
          x: -24,
          opacity: 0,
          duration: 0.5,
          stagger: 0.06,
          delay: 0.55,
          ease: "power2.out",
        });
      }
    }, root);
    return () => ctx.revert();
  }, [tenders.length, isLoading]);

  return (
    <div
      ref={rootRef}
      className="flex h-full flex-col overflow-hidden rounded-2xl bg-white shadow-1 ring-1 ring-stroke dark:bg-gray-dark dark:shadow-card dark:ring-stroke-dark"
    >
      <div className="flex items-center justify-between border-b border-stroke px-5 py-4 dark:border-stroke-dark">
        <div className="flex items-center gap-2">
          <span className="inline-flex size-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
            <SparkleIcon className="size-5" />
          </span>
          <div>
            <h2 className="text-base font-bold text-dark dark:text-white">
              Recent Tenders
            </h2>
            <p className="text-xs text-dark-6">Latest entries in the system</p>
          </div>
        </div>
        <Link
          href="/tenders"
          className="hidden items-center gap-1 text-xs font-medium text-primary hover:underline sm:inline-flex"
        >
          Browse all <ArrowRightIcon className="size-3.5" />
        </Link>
      </div>

      <ul className="flex-1 divide-y divide-stroke dark:divide-stroke-dark">
        {isLoading
          ? Array.from({ length: 5 }).map((_, i) => (
              <li
                key={i}
                className="flex animate-pulse items-start gap-3 px-5 py-3.5"
              >
                <div className="mt-1 size-2 rounded-full bg-gray-2 dark:bg-dark-3" />
                <div className="flex-1 space-y-2">
                  <div className="h-3 w-2/3 rounded bg-gray-2 dark:bg-dark-3" />
                  <div className="h-2 w-1/3 rounded bg-gray-2 dark:bg-dark-3" />
                </div>
              </li>
            ))
          : tenders.map((t) => {
              const ts =
                t.created_at || t.publication_date || t.notice_dispatch_at || 0;
              return (
                <li key={t.id} data-recent-row>
                  <Link
                    href={`/tenders/${t.id}`}
                    className="group relative flex items-start gap-3 px-5 py-3.5 transition-colors hover:bg-gray-2 dark:hover:bg-dark-2"
                  >
                    <span className="relative mt-1.5 flex size-2 shrink-0">
                      <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-60" />
                      <span className="relative inline-flex size-2 rounded-full bg-primary" />
                    </span>
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <span className="rounded bg-gray-2 px-1.5 py-0.5 font-mono text-[10px] uppercase text-dark-5 dark:bg-dark-3 dark:text-dark-6">
                          {t.country_code || "??"}
                        </span>
                        <span
                          className={cn(
                            "rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase",
                            statusTone(t.status),
                          )}
                        >
                          {t.status || "—"}
                        </span>
                        <time className="ml-auto shrink-0 text-[11px] text-dark-6">
                          {relativeTime(ts)}
                        </time>
                      </div>
                      <p className="mt-1.5 line-clamp-2 text-sm font-medium text-dark transition-colors group-hover:text-primary dark:text-white">
                        {t.title || "Untitled tender"}
                      </p>
                      {t.buyer_organization?.name && (
                        <p className="mt-0.5 line-clamp-1 text-xs text-dark-6">
                          {t.buyer_organization.name}
                        </p>
                      )}
                    </div>
                  </Link>
                </li>
              );
            })}
        {!isLoading && tenders.length === 0 && (
          <li className="px-5 py-10 text-center text-sm text-dark-6">
            No tenders yet.
          </li>
        )}
      </ul>
    </div>
  );
}
