"use client";

import Link from "next/link";
import { useMemo } from "react";
import { cn, replaceStageIdsInText, toPlainText } from "@/lib/utils";
import { Card } from "@/components/ui/card";
import { NoDataFound } from "@/components/ui/no-data-found";
import { useDashboardActivityFeedQuery } from "@/features/dashboard/hooks/use-dashboard-section-queries";
import { isDashboardSectionLoading } from "@/features/dashboard/hooks/dashboard-query-status";
import type { ActivityFeedItem } from "@/api/rtk/dashboard-api";
import { useGetPipelinesQuery } from "@/api/rtk/pipelines-api";
import { buildStageIdToNameMap } from "@/lib/pipeline-stage-map";
import { ChevronRight } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

const LATEST_COUNT = 4;

function ActivityFeedSkeletonRow() {
  return (
    <div className={cn("flex gap-[9px] py-3 first:pt-0 last:pb-0")}>
      <Skeleton className="h-7 w-7 shrink-0 rounded-[7px] bg-border/60" />
      <div className="flex-1 space-y-1.5">
        <Skeleton className="h-3.5 w-3/4 rounded bg-border/70" />
        <Skeleton className="h-2.5 w-12 rounded bg-border/50" />
      </div>
    </div>
  );
}

export function ActivityFeedCardSkeleton() {
  return (
    <Card className="flex h-full flex-col gap-0 overflow-hidden p-5">
      <div className="mb-6 flex items-start justify-between">
        <div className="flex flex-col gap-2">
          <Skeleton className="h-4 w-28 rounded bg-border/70" />
          <Skeleton className="h-3 w-36 rounded bg-border/50" />
        </div>
        <Skeleton className="h-2 w-2 rounded-full bg-border/60" />
      </div>
      <div className="flex flex-1 flex-col divide-y divide-border">
        {Array.from({ length: LATEST_COUNT }).map((_, i) => (
          <ActivityFeedSkeletonRow key={i} />
        ))}
      </div>
      <div className="mt-3 border-t border-border pt-3">
        <Skeleton className="mx-auto h-3 w-32 rounded bg-border/50" />
      </div>
    </Card>
  );
}

export function ActivityFeedCard() {
  const { data: activityFeed, isPending, isFetching } =
    useDashboardActivityFeedQuery();
  const { data: pipelines = [] } = useGetPipelinesQuery();
  const stageIdToName = useMemo(
    () => buildStageIdToNameMap(pipelines),
    [pipelines],
  );

  const showSkeleton = isDashboardSectionLoading(
    isPending,
    isFetching,
    activityFeed,
  );

  if (showSkeleton) {
    return <ActivityFeedCardSkeleton />;
  }

  const allActivities: ActivityFeedItem[] = activityFeed ?? [];
  const activities = allActivities.slice(0, LATEST_COUNT);
  const hasMore = allActivities.length > LATEST_COUNT;

  return (
    <Card className="gap-0 p-5 h-full overflow-hidden flex flex-col">
      <div className="flex justify-between items-start mb-6">
        <div className="flex flex-col">
          <h3 className="text-[13px] font-bold text-text font-['Lexend']">
            Activity Feed
          </h3>
          <p className="text-[11px] text-gray-700 font-normal mt-0.5">
            Live team actions · Today
          </p>
        </div>
        <div className="w-2 h-2 rounded-full bg-green shadow-[0_0_0_3px_rgba(34,197,94,0.25)] animate-pulse" />
      </div>

      <div className="flex flex-col flex-1 divide-y divide-border">
        {activities.length === 0 ? (
          <NoDataFound message="No recent activity" />
        ) : (
          activities.map((act) => (
            <div
              key={act.id}
              className={cn("flex gap-[9px] py-3 first:pt-0 last:pb-0")}
            >
              <div className="w-7 h-7 rounded-[7px] bg-[#F9FAFB] flex items-center justify-center text-[13px] shrink-0 border border-border/40">
                {act.icon}
              </div>
              <div className="flex flex-1 flex-col overflow-hidden">
                <div className="text-[11.5px] text-text leading-4 line-clamp-2">
                  <span className="font-bold">{act.rep}</span>{" "}
                  {toPlainText(
                    replaceStageIdsInText(act.action, stageIdToName),
                  )}{" "}
                  <span className="text-accent font-semibold">
                    {toPlainText(
                      replaceStageIdsInText(act.client, stageIdToName),
                    )}
                  </span>
                </div>
                <span className="text-[10px] text-gray-700 font-['Lexend_Deca'] mt-0.5">
                  {act.time}
                </span>
              </div>
            </div>
          ))
        )}
      </div>

      {(hasMore || activities.length > 0) && (
        <Link
          href="/activities"
          className="mt-3 pt-3 border-t border-border flex items-center justify-center gap-1 text-[11px] font-semibold text-accent hover:text-accent/80 transition-colors font-['Lexend_Deca']"
        >
          View all activities
          <ChevronRight className="size-3.5" />
        </Link>
      )}
    </Card>
  );
}
