"use client";

import { useEffect, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import Link from "next/link";

/* ------------------------------------------------------------------ */
/*  Tour step definitions per user type                                */
/* ------------------------------------------------------------------ */

interface TourStep {
  title: string;
  description: string;
  icon: React.ReactNode;
  cta?: { label: string; href: string };
}

const ICON_WELCOME = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 3v1m0 16v1m8.66-13.66l-.71.71M4.05 19.95l-.71.71M21 12h-1M4 12H3m16.66 7.66l-.71-.71M4.05 4.05l-.71-.71M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
  </svg>
);
const ICON_SEARCH = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 21l-4.35-4.35M11 19a8 8 0 100-16 8 8 0 000 16z" />
  </svg>
);
const ICON_CREDITS = (
  <svg className="w-8 h-8 text-gold" viewBox="0 0 24 24" fill="currentColor">
    <circle cx="12" cy="12" r="10" fill="currentColor" opacity="0.15" />
    <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.5" fill="none" />
    <text x="12" y="16" textAnchor="middle" fontSize="11" fontWeight="bold" fill="currentColor">C</text>
  </svg>
);
const ICON_PROFILE = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
  </svg>
);
const ICON_CALENDAR = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
  </svg>
);
const ICON_EARN = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
  </svg>
);
const ICON_TEAM = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 20h5v-2a4 4 0 00-3-3.87M9 20H4v-2a4 4 0 013-3.87m6-1.26a4 4 0 110-8 4 4 0 010 8z" />
  </svg>
);
const ICON_CHART = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6m6 0h6m0 0v-2a2 2 0 012-2h2a2 2 0 012 2v2m-6 0V9a2 2 0 012-2h2a2 2 0 012 2v10" />
  </svg>
);
const ICON_VENUE = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
  </svg>
);
const ICON_STAR = (
  <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l2.07 6.37h6.7c.969 0 1.371 1.24.588 1.81l-5.42 3.94 2.07 6.37c.3.921-.755 1.688-1.54 1.118l-5.42-3.94-5.42 3.94c-.784.57-1.838-.197-1.539-1.118l2.07-6.37-5.42-3.94c-.783-.57-.38-1.81.589-1.81h6.7l2.07-6.37z" />
  </svg>
);

const CLIENT_STEPS: TourStep[] = [
  {
    title: "Welcome to AdultWorld.ai!",
    description:
      "Your journey starts here. Browse thousands of verified escorts & providers, save favorites, send messages, and manage everything from your personal dashboard.",
    icon: ICON_WELCOME,
  },
  {
    title: "Browse & Search",
    description:
      "Use our powerful search and filter system to find exactly who you're looking for — filter by location, services, rates, availability, and more. Tap the heart icon to save favorites for quick access later.",
    icon: ICON_SEARCH,
    cta: { label: "Browse Escorts", href: "/escorts" },
  },
  {
    title: "Credits & Messaging",
    description:
      "AdultWorld runs on a credits system. Purchase credits to unlock messaging, view private galleries, and access premium features. Start a conversation directly from any profile.",
    icon: ICON_CREDITS,
    cta: { label: "Buy Credits", href: "/credits/buy" },
  },
];

const PROVIDER_STEPS: TourStep[] = [
  {
    title: "Welcome, Provider!",
    description:
      "Congratulations on joining AdultWorld.ai! Let's get you set up so clients can discover your profile and start reaching out.",
    icon: ICON_WELCOME,
  },
  {
    title: "Complete Your Profile",
    description:
      "Upload eye-catching photos, set your rates, write a compelling bio, and list your services. A complete profile gets up to 5x more views than an incomplete one.",
    icon: ICON_PROFILE,
    cta: { label: "Edit Profile", href: "/manage/profile/personal-information" },
  },
  {
    title: "Set Your Availability",
    description:
      "Toggle \"Available Now\" to appear at the top of search results instantly. Use the availability calendar to let clients know your regular working hours and schedule.",
    icon: ICON_CALENDAR,
    cta: { label: "Set Availability", href: "/manage/availabilities" },
  },
  {
    title: "Start Earning",
    description:
      "Earn credits when clients message you or subscribe to your profile. Boost your visibility with featured listings, go live with LiveCam, and set your own messaging prices.",
    icon: ICON_EARN,
  },
];

const AGENCY_STEPS: TourStep[] = [
  {
    title: "Welcome, Agency!",
    description:
      "Your agency dashboard gives you everything you need to manage multiple escort profiles, track performance, and grow your business on AdultWorld.ai.",
    icon: ICON_WELCOME,
  },
  {
    title: "Add Your Escorts",
    description:
      "Create and manage individual profiles for each of your escorts. Upload their photos, set rates, and keep information up to date — all from one central place.",
    icon: ICON_TEAM,
    cta: { label: "Manage Escorts", href: "/dashboard/agency" },
  },
  {
    title: "Track Performance",
    description:
      "Monitor profile views, messages received, earnings, and subscriber counts for each escort. Use analytics to identify your top performers and optimize your listings.",
    icon: ICON_CHART,
  },
];

const CLUB_STEPS: TourStep[] = [
  {
    title: "Welcome, Club!",
    description:
      "Your venue dashboard lets you showcase your club, attract visitors, and manage your presence on AdultWorld.ai.",
    icon: ICON_WELCOME,
  },
  {
    title: "Set Up Your Venue",
    description:
      "Complete your club profile with photos, a description, your location, opening hours, and contact details. A rich profile helps visitors know what to expect.",
    icon: ICON_VENUE,
    cta: { label: "Edit Profile", href: "/manage/profile/personal-information" },
  },
  {
    title: "Attract Visitors",
    description:
      "Promote upcoming events, use featured listing boosts to reach more people, and keep your profile active to climb the search rankings.",
    icon: ICON_STAR,
  },
];

/* ------------------------------------------------------------------ */
/*  Component                                                          */
/* ------------------------------------------------------------------ */

interface OnboardingTourProps {
  /** Override user type detection (for agency/club which share escort type) */
  userTypeOverride?: "client" | "escort" | "agency" | "strip_club";
}

export function OnboardingTour({ userTypeOverride }: OnboardingTourProps) {
  const { data: session } = useSession();
  const [currentStep, setCurrentStep] = useState(0);
  const [visible, setVisible] = useState(false);
  const [animating, setAnimating] = useState(false);
  const [direction, setDirection] = useState<"next" | "prev">("next");

  const userId = session?.user?.id;
  const sessionUserType = (session?.user as Record<string, unknown> | undefined)?.userType as
    | string
    | undefined;
  const effectiveType = userTypeOverride ?? sessionUserType;

  const steps = (() => {
    if (effectiveType === "agency") return AGENCY_STEPS;
    if (effectiveType === "strip_club") return CLUB_STEPS;
    if (effectiveType === "escort") return PROVIDER_STEPS;
    return CLIENT_STEPS;
  })();

  // Check if tour should show
  useEffect(() => {
    if (!userId) return;

    const lsKey = `onboarding_completed_${userId}`;
    if (localStorage.getItem(lsKey) === "true") return;

    // Small delay so dashboard renders first
    const timer = setTimeout(() => setVisible(true), 600);
    return () => clearTimeout(timer);
  }, [userId]);

  const markComplete = useCallback(async () => {
    if (!userId) return;
    localStorage.setItem(`onboarding_completed_${userId}`, "true");

    try {
      await fetch("/api/onboarding/complete", { method: "POST" });
    } catch {
      // localStorage is the backup — API failure is non-critical
    }
  }, [userId]);

  const handleNext = () => {
    if (animating) return;
    if (currentStep >= steps.length - 1) {
      handleFinish();
      return;
    }
    setDirection("next");
    setAnimating(true);
    setTimeout(() => {
      setCurrentStep((s) => s + 1);
      setAnimating(false);
    }, 200);
  };

  const handlePrev = () => {
    if (animating || currentStep === 0) return;
    setDirection("prev");
    setAnimating(true);
    setTimeout(() => {
      setCurrentStep((s) => s - 1);
      setAnimating(false);
    }, 200);
  };

  const handleSkip = () => {
    handleFinish();
  };

  const handleFinish = () => {
    setVisible(false);
    markComplete();
  };

  if (!visible) return null;

  const step = steps[currentStep];
  const isLast = currentStep === steps.length - 1;

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm" />

      {/* Card */}
      <div className="relative bg-[#111127] border border-gold/20 rounded-2xl shadow-2xl shadow-gold/10 max-w-lg w-full p-8 sm:p-10">
        {/* Gold gradient bar at top */}
        <div className="absolute top-0 inset-x-0 h-1 rounded-t-2xl bg-gradient-to-r from-gold/60 via-gold to-gold/60" />

        {/* Skip button */}
        <button
          onClick={handleSkip}
          className="absolute top-4 right-4 text-text-muted hover:text-white text-sm transition-colors"
        >
          Skip tour
        </button>

        {/* Step content with transition */}
        <div
          className={`transition-all duration-200 ${
            animating
              ? direction === "next"
                ? "opacity-0 translate-x-4"
                : "opacity-0 -translate-x-4"
              : "opacity-100 translate-x-0"
          }`}
        >
          {/* Icon */}
          <div className="flex justify-center mb-6">
            <div className="w-16 h-16 rounded-full bg-gold/10 border border-gold/30 flex items-center justify-center">
              {step.icon}
            </div>
          </div>

          {/* Title */}
          <h2 className="text-2xl font-bold text-white text-center mb-3">
            {step.title}
          </h2>

          {/* Description */}
          <p className="text-text-muted text-center leading-relaxed mb-6">
            {step.description}
          </p>

          {/* Optional CTA link */}
          {step.cta && (
            <div className="flex justify-center mb-6">
              <Link
                href={step.cta.href}
                onClick={handleFinish}
                className="text-gold hover:text-gold-light text-sm font-medium underline underline-offset-4 transition-colors"
              >
                {step.cta.label} &rarr;
              </Link>
            </div>
          )}
        </div>

        {/* Step indicator dots */}
        <div className="flex justify-center gap-2 mb-6">
          {steps.map((_, i) => (
            <button
              key={i}
              onClick={() => {
                if (animating) return;
                setDirection(i > currentStep ? "next" : "prev");
                setAnimating(true);
                setTimeout(() => {
                  setCurrentStep(i);
                  setAnimating(false);
                }, 200);
              }}
              className={`w-2.5 h-2.5 rounded-full transition-all duration-300 ${
                i === currentStep
                  ? "bg-gold w-6"
                  : i < currentStep
                  ? "bg-gold/40"
                  : "bg-white/20"
              }`}
              aria-label={`Go to step ${i + 1}`}
            />
          ))}
        </div>

        {/* Navigation buttons */}
        <div className="flex gap-3">
          {currentStep > 0 && (
            <button
              onClick={handlePrev}
              className="flex-1 border border-white/10 hover:border-gold/30 text-white font-medium py-3 rounded-xl transition-all"
            >
              Back
            </button>
          )}
          <button
            onClick={handleNext}
            className="flex-1 bg-gold hover:bg-gold-light text-black font-bold py-3 rounded-xl transition-all shadow-glow"
          >
            {isLast ? "Get Started" : "Next"}
          </button>
        </div>
      </div>
    </div>
  );
}
