"use client";

import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  DocumentTextIcon,
  CheckCircleIcon,
  ServerIcon,
  ChatBubbleLeftRightIcon,
  ArrowTrendingUpIcon,
  ChevronRightIcon,
} from "@heroicons/react/24/outline";
import type { Activity } from "@customer-portal/domain/dashboard";
import { formatActivityDate, getActivityNavigationPath } from "../utils/dashboard.utils";
import { cn } from "@/shared/utils";
import { motionVariants } from "@/components/atoms";

const containerVariants = motionVariants.staggerContainer(0.05);
const itemVariants = motionVariants.slideLeftSmall;

interface ActivityFeedProps {
  activities: Activity[];
  maxItems?: number;
  isLoading?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

const ICON_COMPONENTS: Record<
  Activity["type"],
  React.ComponentType<React.SVGProps<SVGSVGElement>>
> = {
  invoice_created: DocumentTextIcon,
  invoice_paid: CheckCircleIcon,
  service_activated: ServerIcon,
  case_created: ChatBubbleLeftRightIcon,
  case_closed: CheckCircleIcon,
};

const ICON_STYLES: Record<Activity["type"], { bg: string; color: string }> = {
  invoice_created: { bg: "bg-info/10", color: "text-info" },
  invoice_paid: { bg: "bg-success/10", color: "text-success" },
  service_activated: { bg: "bg-primary/10", color: "text-primary" },
  case_created: { bg: "bg-warning/10", color: "text-warning" },
  case_closed: { bg: "bg-success/10", color: "text-success" },
};

interface ActivityItemProps {
  activity: Activity;
  isLast?: boolean;
}

function ActivityItem({ activity, isLast = false }: ActivityItemProps) {
  const router = useRouter();
  const Icon = ICON_COMPONENTS[activity.type] ?? DocumentTextIcon;
  const styles = ICON_STYLES[activity.type] ?? { bg: "bg-muted", color: "text-muted-foreground" };
  const timeAgo = formatActivityDate(activity.date);
  const navPath = getActivityNavigationPath(activity);
  const isClickable = Boolean(navPath);

  const content = (
    <div className="flex items-start gap-3 py-3">
      {/* Icon with timeline connector */}
      <div className="relative flex-shrink-0">
        <div
          className={cn(
            "h-8 w-8 rounded-lg flex items-center justify-center",
            styles.bg,
            isClickable && "group-hover:scale-105 transition-transform"
          )}
        >
          <Icon className={cn("h-4 w-4", styles.color)} />
        </div>
        {/* Timeline connector */}
        {!isLast && (
          <div className="absolute top-10 left-1/2 -translate-x-1/2 w-px h-[calc(100%-0.5rem)] bg-border/60" />
        )}
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0 pt-0.5">
        <p
          className={cn(
            "text-sm font-medium text-foreground leading-snug",
            isClickable && "group-hover:text-primary transition-colors"
          )}
        >
          {activity.title}
        </p>
        <p className="text-xs text-muted-foreground mt-0.5">{timeAgo}</p>
      </div>

      {/* Arrow for clickable items */}
      {isClickable && (
        <ChevronRightIcon className="h-4 w-4 text-muted-foreground/40 group-hover:text-primary group-hover:translate-x-0.5 transition-all flex-shrink-0 mt-1" />
      )}
    </div>
  );

  if (isClickable) {
    return (
      <button
        type="button"
        onClick={() => router.push(navPath!)}
        className="group w-full text-left rounded-lg hover:bg-muted/50 transition-colors px-2 -mx-2"
      >
        {content}
      </button>
    );
  }

  return <div className="px-2 -mx-2">{content}</div>;
}

function ActivityItemSkeleton({ isLast = false }: { isLast?: boolean }) {
  return (
    <div className="flex items-start gap-3 py-3 px-2 -mx-2">
      <div className="relative flex-shrink-0">
        <div className="h-8 w-8 rounded-lg cp-skeleton-shimmer" />
        {!isLast && (
          <div className="absolute top-10 left-1/2 -translate-x-1/2 w-px h-[calc(100%-0.5rem)] bg-muted" />
        )}
      </div>
      <div className="flex-1 min-w-0 pt-0.5 space-y-1.5">
        <div className="h-4 cp-skeleton-shimmer rounded w-3/4" />
        <div className="h-3 cp-skeleton-shimmer rounded w-16" />
      </div>
    </div>
  );
}

function EmptyActivity() {
  return (
    <div className="relative overflow-hidden rounded-xl bg-gradient-to-br from-muted/30 to-muted/10 border border-border/40 text-center py-10 px-6">
      {/* Decorative elements */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-12 -right-12 w-24 h-24 rounded-full bg-primary/5 blur-2xl" />
        <div className="absolute -bottom-12 -left-12 w-24 h-24 rounded-full bg-info/5 blur-2xl" />
      </div>

      <div className="relative">
        <div className="w-14 h-14 rounded-xl bg-muted/50 flex items-center justify-center mx-auto mb-4">
          <ArrowTrendingUpIcon className="h-7 w-7 text-muted-foreground/50" />
        </div>
        <h4 className="text-sm font-semibold text-foreground">No recent activity</h4>
        <p className="text-xs text-muted-foreground mt-1 max-w-[200px] mx-auto">
          Your account activity will appear here as you use our services.
        </p>
      </div>
    </div>
  );
}

/**
 * ActivityFeed - Beautiful activity timeline for dashboard
 */
export function ActivityFeed({
  activities,
  maxItems = 5,
  isLoading = false,
  className,
  style,
}: ActivityFeedProps) {
  if (isLoading) {
    return (
      <div className={cn("space-y-4", className)} style={style}>
        <div className="flex items-center justify-between">
          <h3 className="text-base font-semibold text-foreground">Recent Activity</h3>
        </div>
        <div className="bg-surface border border-border/60 rounded-xl p-4">
          {Array.from({ length: 3 }).map((_, i) => (
            <ActivityItemSkeleton key={i} isLast={i === 2} />
          ))}
        </div>
      </div>
    );
  }

  const visibleActivities = activities.slice(0, maxItems);

  return (
    <div className={cn("space-y-4", className)} style={style}>
      <div className="flex items-center justify-between">
        <h3 className="text-base font-semibold text-foreground">Recent Activity</h3>
      </div>

      {visibleActivities.length === 0 ? (
        <EmptyActivity />
      ) : (
        <motion.div
          className="bg-surface border border-border/60 rounded-xl p-4"
          initial="hidden"
          animate="visible"
          variants={containerVariants}
        >
          {visibleActivities.map((activity, index) => (
            <motion.div key={activity.id} variants={itemVariants}>
              <ActivityItem activity={activity} isLast={index === visibleActivities.length - 1} />
            </motion.div>
          ))}
        </motion.div>
      )}
    </div>
  );
}
