"use client";

import Link from "next/link";
import {
  CheckCircleIcon,
  Squares2X2Icon,
  DocumentTextIcon,
  ChatBubbleLeftRightIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";
import { TaskCard, TaskCardSkeleton } from "./TaskCard";
import type { DashboardTask } from "../hooks/useDashboardTasks";
import {
  useCreateInvoiceSsoLink,
  useCreatePaymentMethodsSsoLink,
} from "@/features/billing/hooks/useBilling";
import { useState } from "react";
import { logger } from "@/core/logger";

interface TaskListProps {
  tasks: DashboardTask[];
  isLoading?: boolean;
  maxTasks?: number;
}

/**
 * Beautiful empty state when all tasks are completed
 */
function AllCaughtUp() {
  return (
    <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-success/10 via-primary/5 to-info/10 border border-success/20">
      {/* Decorative background elements */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-24 -right-24 w-48 h-48 rounded-full bg-success/10 blur-3xl" />
        <div className="absolute -bottom-24 -left-24 w-48 h-48 rounded-full bg-primary/10 blur-3xl" />
      </div>

      <div className="relative text-center py-10 px-6">
        {/* Animated checkmark */}
        <div className="relative w-20 h-20 mx-auto mb-5">
          <div className="absolute inset-0 rounded-full bg-success/20 animate-ping" />
          <div className="relative w-20 h-20 rounded-full bg-success/15 flex items-center justify-center">
            <CheckCircleIcon className="h-10 w-10 text-success" />
          </div>
        </div>

        <h3 className="text-xl font-bold text-foreground">You&apos;re all caught up!</h3>
        <p className="text-sm text-muted-foreground mt-2 max-w-md mx-auto">
          No outstanding tasks right now. Take a moment to explore or manage your account.
        </p>

        {/* Quick action cards */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mt-8 max-w-lg mx-auto">
          <Link
            href="/account/services"
            className="group flex flex-col items-center gap-2 p-4 rounded-xl bg-surface/80 backdrop-blur-sm border border-border/60 hover:border-primary/40 hover:shadow-lg transition-all"
          >
            <div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
              <Squares2X2Icon className="h-5 w-5 text-primary" />
            </div>
            <span className="text-sm font-medium text-foreground">Browse Services</span>
            <ArrowRightIcon className="h-4 w-4 text-muted-foreground group-hover:text-primary group-hover:translate-x-0.5 transition-all" />
          </Link>

          <Link
            href="/account/billing"
            className="group flex flex-col items-center gap-2 p-4 rounded-xl bg-surface/80 backdrop-blur-sm border border-border/60 hover:border-info/40 hover:shadow-lg transition-all"
          >
            <div className="w-10 h-10 rounded-lg bg-info/10 flex items-center justify-center group-hover:bg-info/20 transition-colors">
              <DocumentTextIcon className="h-5 w-5 text-info" />
            </div>
            <span className="text-sm font-medium text-foreground">View Invoices</span>
            <ArrowRightIcon className="h-4 w-4 text-muted-foreground group-hover:text-info group-hover:translate-x-0.5 transition-all" />
          </Link>

          <Link
            href="/account/support"
            className="group flex flex-col items-center gap-2 p-4 rounded-xl bg-surface/80 backdrop-blur-sm border border-border/60 hover:border-warning/40 hover:shadow-lg transition-all"
          >
            <div className="w-10 h-10 rounded-lg bg-warning/10 flex items-center justify-center group-hover:bg-warning/20 transition-colors">
              <ChatBubbleLeftRightIcon className="h-5 w-5 text-warning" />
            </div>
            <span className="text-sm font-medium text-foreground">Get Support</span>
            <ArrowRightIcon className="h-4 w-4 text-muted-foreground group-hover:text-warning group-hover:translate-x-0.5 transition-all" />
          </Link>
        </div>
      </div>
    </div>
  );
}

/**
 * Loading state for task list
 */
function TaskListLoading({ count = 2 }: { count?: number }) {
  return (
    <div className="space-y-4">
      {Array.from({ length: count }).map((_, i) => (
        <TaskCardSkeleton key={i} />
      ))}
    </div>
  );
}

/**
 * TaskList component that renders prioritized tasks
 */
export function TaskList({ tasks, isLoading = false, maxTasks = 4 }: TaskListProps) {
  const [loadingTaskId, setLoadingTaskId] = useState<string | null>(null);
  const createInvoiceSsoLink = useCreateInvoiceSsoLink();
  const createPaymentMethodsSsoLink = useCreatePaymentMethodsSsoLink();

  if (isLoading) {
    return <TaskListLoading count={2} />;
  }

  if (tasks.length === 0) {
    return <AllCaughtUp />;
  }

  const visibleTasks = tasks.slice(0, maxTasks);

  const handleTaskAction = async (task: DashboardTask) => {
    // If task doesn't require SSO action, just let the link handle navigation
    if (!task.requiresSsoAction) {
      return;
    }

    setLoadingTaskId(task.id);

    try {
      if (task.type === "invoice" && task.metadata?.invoiceId) {
        const ssoLink = await createInvoiceSsoLink.mutateAsync({
          invoiceId: task.metadata.invoiceId,
          target: "pay",
        });
        window.open(ssoLink.url, "_blank", "noopener,noreferrer");
      } else if (task.type === "payment_method") {
        const ssoLink = await createPaymentMethodsSsoLink.mutateAsync();
        window.open(ssoLink.url, "_blank", "noopener,noreferrer");
      }
    } catch (error) {
      logger.error("Failed to handle task action", {
        taskId: task.id,
        taskType: task.type,
        error: error instanceof Error ? error.message : String(error),
      });
    } finally {
      setLoadingTaskId(null);
    }
  };

  return (
    <div className="space-y-4">
      {visibleTasks.map(task => (
        <TaskCard
          key={task.id}
          id={task.id}
          icon={task.icon}
          title={task.title}
          description={task.description}
          actionLabel={task.actionLabel}
          detailHref={task.detailHref}
          onAction={task.requiresSsoAction ? () => void handleTaskAction(task) : undefined}
          tone={task.tone}
          isLoading={loadingTaskId === task.id}
          loadingText="Opening..."
        />
      ))}
    </div>
  );
}
