"use client";

import { useRouter } from "next/navigation";
import { PlayCircle } from '@/lib/icons';
import { Button } from "@/components/ui/button";
import type { AcademyModule } from "@/lib/academy/tours";
import { markModuleComplete } from "@/lib/academy/progress";

interface AcademyTourButtonProps {
  module: AcademyModule;
  onComplete?: () => void;
  variant?: "default" | "outline" | "ghost";
  size?: "default" | "sm";
}

export function AcademyTourButton({
  module,
  onComplete,
  variant = "outline",
  size = "sm",
}: AcademyTourButtonProps) {
  const router = useRouter();

  async function startTour() {
    // @ts-expect-error - CSS loaded dynamically
    await import("driver.js/dist/driver.css");
    const { driver } = await import("driver.js");

    router.push(module.url);
    await new Promise((r) => setTimeout(r, 900));

    let driverObj: ReturnType<typeof driver>;

    driverObj = driver({
      showProgress: true,
      progressText: "{{current}} / {{total}}",
      nextBtnText: "İleri →",
      prevBtnText: "← Geri",
      doneBtnText: "Tamamla ✓",
      smoothScroll: true,
      onDestroyStarted: () => {
        driverObj.destroy();
      },
      onDestroyed: () => {
        // Close any open form
        if (module.closeEvent) {
          window.dispatchEvent(new CustomEvent(module.closeEvent));
        }
        markModuleComplete(module.id);
        onComplete?.();
      },
      onNextClick: (_el, _step, { state }) => {
        const nextIndex = (state.activeIndex ?? 0) + 1;
        if (nextIndex >= module.steps.length) {
          driverObj.destroy();
          return;
        }

        const nextStep = module.steps[nextIndex];

        // Dispatch a window event before this step (e.g. open a form)
        if (nextStep.triggerEvent) {
          window.dispatchEvent(new CustomEvent(nextStep.triggerEvent));
          setTimeout(() => driverObj.moveNext(), nextStep.triggerDelay ?? 700);
          return;
        }

        // Click a DOM element before this step (e.g. navigate form wizard)
        if (nextStep.clickBefore) {
          const target = document.querySelector<HTMLElement>(nextStep.clickBefore);
          target?.click();
          setTimeout(() => driverObj.moveNext(), nextStep.clickDelay ?? 350);
          return;
        }

        driverObj.moveNext();
      },
      steps: module.steps.map((s) => ({
        element: s.element,
        popover: {
          title: s.title,
          description: s.description,
          side: s.side ?? "bottom",
          align: "start",
        },
      })),
    });

    driverObj.drive();
  }

  return (
    <Button variant={variant} size={size} onClick={startTour} className="gap-1.5">
      <PlayCircle className="size-4" />
      Turu Başlat
    </Button>
  );
}
