import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Progress } from "@/components/ui/progress";
import { TaskCheckItem } from "@/components/ui/pipeline-primitives";
import { Spinner } from "@/components/ui/spinner";

/**
 * StageTimeline — WealthX DS (L4 Section)
 *
 * Progress bar + accordion list of pipeline stages with task checklists.
 * Used in the Tasks tab of OpportunityDetailsDrawer.
 *
 * Layout:
 *   • Top: progress bar showing completed stages / total stages
 *   • Below: accordion with one item per stage
 *
 * Data source: `listColumns()` + `listLoans()` → tasks per stage
 */

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface StageTimelineTask {
  id: string;
  title: string;
  completed: boolean;
  aiAgentName?: string | null;
  /** When provided alongside `aiAgentName`, shows the auto-complete toggle switch. */
  autoCompleteEnabled?: boolean;
}

export interface StageTimelineStage {
  id: string;
  name: string;
  tasks: StageTimelineTask[];
  /** Stage the opportunity is currently in. */
  isCurrentStage?: boolean;
  /** Stage has been fully passed through. */
  isCompleted?: boolean;
}

export interface StageTimelineProps {
  stages: StageTimelineStage[];
  /** Called when a task checkbox is toggled. */
  onTaskToggle?: (stageId: string, taskId: string) => void;
  /** Called when the auto-complete switch on a task is toggled. */
  onTaskAutoCompleteToggle?: (stageId: string, taskId: string) => void;
  /** Shows a loading skeleton instead of stages. */
  isLoading?: boolean;
  className?: string;
}

// ---------------------------------------------------------------------------
// StageTimeline
// ---------------------------------------------------------------------------

export function StageTimeline({
  stages,
  onTaskToggle,
  onTaskAutoCompleteToggle,
  isLoading = false,
  className,
}: StageTimelineProps) {
  if (isLoading) {
    return (
      <div
        className={cn(
          "flex flex-col items-center justify-center gap-3 py-10",
          className,
        )}
        data-slot="stage-timeline"
      >
        <Spinner size="lg" className="text-muted-foreground" />
        <p className="text-sm text-muted-foreground">Loading stages…</p>
      </div>
    );
  }

  if (stages.length === 0) {
    return (
      <div
        className={cn(
          "flex items-center justify-center py-10 text-sm text-muted-foreground",
          className,
        )}
        data-slot="stage-timeline"
      >
        No stages available.
      </div>
    );
  }

  const completedCount = stages.filter((s) => s.isCompleted).length;
  const progressPct = Math.round((completedCount / stages.length) * 100);

  // Default open: current stage (or first if none flagged)
  const defaultOpen = stages.find((s) => s.isCurrentStage)?.id ?? stages[0].id;

  return (
    <div
      className={cn("flex flex-col gap-4", className)}
      data-slot="stage-timeline"
    >
      {/* Progress bar */}
      <div className="flex flex-col gap-2">
        <div className="flex items-center justify-between text-sm text-muted-foreground">
          <span>Stage progress</span>
          <span>
            {completedCount} / {stages.length} completed
          </span>
        </div>
        <Progress value={progressPct} className="h-2.5" />
      </div>

      {/* Stage accordion */}
      <Accordion
        defaultValue={[defaultOpen]}
        className="w-full"
      >
        {stages.map((stage) => {
          const completedTasks = stage.tasks.filter((t) => t.completed).length;
          const hasTasks = stage.tasks.length > 0;

          return (
            <AccordionItem
              key={stage.id}
              value={stage.id}
              className="border-b border-border last:border-0"
            >
              <AccordionTrigger
                className={cn(
                  "py-3.5 text-sm hover:no-underline [&>svg]:size-4",
                  stage.isCompleted
                    ? "text-muted-foreground"
                    : stage.isCurrentStage
                      ? "font-semibold text-foreground"
                      : "font-normal text-muted-foreground",
                )}
                disabled={!hasTasks}
              >
                <span className="flex items-center gap-2.5">
                  {/* Stage status icon */}
                  {stage.isCompleted ? (
                    <span
                      className="flex size-5 shrink-0 items-center justify-center rounded-full bg-primary"
                      aria-hidden="true"
                    >
                      <Check
                        className="size-3 text-primary-foreground"
                        strokeWidth={2.5}
                      />
                    </span>
                  ) : stage.isCurrentStage ? (
                    <span
                      className="size-5 shrink-0 rounded-full border-2 border-primary bg-background"
                      aria-hidden="true"
                    />
                  ) : (
                    <span
                      className="size-5 shrink-0 rounded-full border-2 border-muted-foreground/30 bg-background"
                      aria-hidden="true"
                    />
                  )}

                  <span className={cn(stage.isCompleted && "line-through")}>
                    {stage.name}
                  </span>

                  {hasTasks && (
                    <span className="text-xs text-muted-foreground">
                      {completedTasks}/{stage.tasks.length}
                    </span>
                  )}
                </span>
              </AccordionTrigger>

              {hasTasks && (
                <AccordionContent className="p-0 pb-3 pl-8">
                  {stage.tasks.map((task) => (
                    <TaskCheckItem
                      key={task.id}
                      title={task.title}
                      completed={task.completed}
                      aiAgentName={task.aiAgentName}
                      autoCompleteEnabled={task.autoCompleteEnabled}
                      size="sm"
                      onToggle={
                        onTaskToggle
                          ? () => onTaskToggle(stage.id, task.id)
                          : undefined
                      }
                      onAutoCompleteToggle={
                        onTaskAutoCompleteToggle
                          ? () => onTaskAutoCompleteToggle(stage.id, task.id)
                          : undefined
                      }
                    />
                  ))}
                </AccordionContent>
              )}
            </AccordionItem>
          );
        })}
      </Accordion>
    </div>
  );
}
