"use client";

import * as React from "react";
import { X } from "lucide-react";

import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

import type { ResolvedTask } from "./types";

type TutorialCoachBarProps = {
  task: ResolvedTask;
  stepIndex: number;
  primaryLabel: string;
  onBack: () => void;
  onNext: () => void;
  onSkip: () => void;
  onOpenTarget: () => void;
  className?: string;
};

export function TutorialCoachBar({
  task,
  stepIndex,
  primaryLabel,
  onBack,
  onNext,
  onSkip,
  onOpenTarget,
  className,
}: TutorialCoachBarProps) {
  const step = task.steps[stepIndex] ?? task.steps[task.steps.length - 1];
  const isLast = stepIndex >= task.steps.length - 1;
  const isFirst = stepIndex <= 0;

  if (!step) {
    return null;
  }

  return (
    <div
      className={cn(
        "pointer-events-auto fixed right-4 bottom-4 z-40 w-[min(100%-2rem,22rem)] rounded-xl border border-border bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10",
        className,
      )}
      data-tutorial="coach-bar"
      role="status"
    >
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0">
          <p className="text-[10px] font-semibold tracking-widest text-muted-foreground uppercase">
            {task.title} · {stepIndex + 1}/{task.steps.length}
          </p>
          <p className="mt-1 text-sm font-medium">{step.title}</p>
          <p className="mt-1 text-xs text-muted-foreground">{step.description}</p>
        </div>
        <Button
          type="button"
          variant="ghost"
          size="icon-sm"
          className="shrink-0"
          aria-label="Dismiss task"
          onClick={onSkip}
        >
          <X className="size-3.5" />
        </Button>
      </div>
      <div className="mt-3 flex flex-wrap items-center gap-2">
        <Button type="button" size="sm" variant="outline" onClick={onOpenTarget}>
          {primaryLabel}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="ghost"
          disabled={isFirst}
          onClick={onBack}
        >
          Back
        </Button>
        <Button type="button" size="sm" onClick={onNext}>
          {isLast ? "Finish" : "Next"}
        </Button>
      </div>
    </div>
  );
}
