"use client";

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

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

function timeLeft(unix: number) {
  const now = Math.floor(Date.now() / 1000);
  const diff = unix - now;
  if (diff <= 0) return { label: "Expired", urgent: true };
  const days = Math.floor(diff / 86400);
  if (days >= 1) return { label: `${days}d left`, urgent: days <= 2 };
  const hours = Math.floor(diff / 3600);
  if (hours >= 1) return { label: `${hours}h left`, urgent: true };
  const minutes = Math.max(1, Math.floor(diff / 60));
  return { label: `${minutes}m left`, urgent: true };
}

export function ClosingSoonCard({ 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.3,
      });

      const rows = root.querySelectorAll("[data-closing-row]");
      if (rows.length > 0) {
        gsap.from(rows, {
          x: 24,
          opacity: 0,
          duration: 0.45,
          stagger: 0.07,
          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-orange-light/10 text-orange-light">
            <FireIcon className="size-5" />
          </span>
          <div>
            <h2 className="text-base font-bold text-dark dark:text-white">
              Closing Soon
            </h2>
            <p className="text-xs text-dark-6">
              Tenders with looming deadlines
            </p>
          </div>
        </div>
        <Link
          href="/tenders"
          className="hidden items-center gap-1 text-xs font-medium text-primary hover:underline sm:inline-flex"
        >
          View 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-center gap-3 px-5 py-3.5"
              >
                <div className="size-10 rounded-lg bg-gray-2 dark:bg-dark-3" />
                <div className="flex-1 space-y-2">
                  <div className="h-3 w-3/4 rounded bg-gray-2 dark:bg-dark-3" />
                  <div className="h-2 w-1/2 rounded bg-gray-2 dark:bg-dark-3" />
                </div>
                <div className="h-6 w-16 rounded-full bg-gray-2 dark:bg-dark-3" />
              </li>
            ))
          : tenders.map((t) => {
              const deadline = t.submission_deadline || t.tender_deadline || 0;
              const tl = timeLeft(deadline);
              const country = (t.country_code || "??").toUpperCase();
              return (
                <li key={t.id} data-closing-row>
                  <Link
                    href={`/tenders/${t.id}`}
                    className="group flex items-center gap-3 px-5 py-3.5 transition-colors hover:bg-gray-2 dark:hover:bg-dark-2"
                  >
                    <div
                      className={cn(
                        "inline-flex size-10 shrink-0 items-center justify-center rounded-lg text-xs font-bold text-white shadow-sm",
                        tl.urgent
                          ? "bg-gradient-to-br from-orange-light to-error"
                          : "bg-gradient-to-br from-[#5750F1] to-[#0ABEF9]",
                      )}
                    >
                      {country.slice(0, 2)}
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="line-clamp-1 text-sm font-semibold text-dark transition-colors group-hover:text-primary dark:text-white">
                        {t.title || "Untitled tender"}
                      </p>
                      <p className="mt-0.5 flex items-center gap-1.5 text-xs text-dark-6">
                        <ClockIcon className="size-3" />
                        {deadline
                          ? new Date(deadline * 1000).toLocaleDateString("en", {
                              month: "short",
                              day: "numeric",
                            })
                          : "No deadline"}
                        {t.buyer_name && (
                          <>
                            <span className="opacity-50">•</span>
                            <span className="truncate">{t.buyer_name}</span>
                          </>
                        )}
                      </p>
                    </div>
                    <span
                      className={cn(
                        "shrink-0 rounded-full px-2.5 py-1 text-[11px] font-semibold tabular-nums",
                        tl.urgent
                          ? "bg-orange-light/15 text-orange-light"
                          : "bg-primary/10 text-primary",
                      )}
                    >
                      {tl.label}
                    </span>
                  </Link>
                </li>
              );
            })}
        {!isLoading && tenders.length === 0 && (
          <li className="px-5 py-10 text-center text-sm text-dark-6">
            No upcoming deadlines.
          </li>
        )}
      </ul>
    </div>
  );
}
