'use client';

import { useCallback, useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import { ArrowRight, ChevronLeft, ChevronRight, X } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { onboardingClient, type OnboardingSlide } from '@/lib/onboarding-client';

const ONBOARDING_DISMISSED_PREFIX = 'sehat-patient-onboarding-dismissed-v1';

function dismissedStorageKey(user: { id?: string; email?: string } | null): string | null {
  const identifier = user?.email?.trim().toLowerCase() || user?.id;
  return identifier ? `${ONBOARDING_DISMISSED_PREFIX}:${identifier}` : null;
}

function hasDismissedInBrowser(user: { id?: string; email?: string } | null): boolean {
  const key = dismissedStorageKey(user);
  if (!key || typeof window === 'undefined') return false;
  try {
    return window.localStorage.getItem(key) === '1';
  } catch {
    return false;
  }
}

function rememberDismissedInBrowser(user: { id?: string; email?: string } | null): void {
  const key = dismissedStorageKey(user);
  if (!key || typeof window === 'undefined') return;
  try {
    window.localStorage.setItem(key, '1');
  } catch {
    // Backend completion remains the durable fallback if browser storage is unavailable.
  }
}

export function OnboardingWalkthrough() {
  const { user, refresh } = useAuth();
  const pathname = usePathname();
  const [slides, setSlides] = useState<OnboardingSlide[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [visible, setVisible] = useState(false);
  const [exiting, setExiting] = useState(false);
  const [dismissedThisSession, setDismissedThisSession] = useState(false);
  const suppressAutoOnboarding =
    !pathname ||
    pathname.startsWith('/appointments') ||
    pathname.startsWith('/call');

  useEffect(() => {
    if (!user) return;
    if (suppressAutoOnboarding) return;
    if (dismissedThisSession) return;
    if ((user as { onboardingCompletedAt?: string | null }).onboardingCompletedAt) return;
    if (hasDismissedInBrowser(user)) return;

    let cancelled = false;
    onboardingClient
      .getSlides()
      .then((data) => {
        if (!cancelled && data.length > 0 && !hasDismissedInBrowser(user)) {
          setSlides(data);
          setCurrentIndex(0);
          setVisible(true);
        }
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, [user, dismissedThisSession, suppressAutoOnboarding]);

  useEffect(() => {
    const handler = () => {
      onboardingClient
        .getSlides()
        .then((data) => {
          if (data.length > 0) {
            setSlides(data);
            setCurrentIndex(0);
            setVisible(true);
          }
        })
        .catch(() => {});
    };
    window.addEventListener('replay-onboarding', handler);
    return () => window.removeEventListener('replay-onboarding', handler);
  }, []);

  const dismiss = useCallback(() => {
    setExiting(true);
    setDismissedThisSession(true);
    rememberDismissedInBrowser(user);
    setTimeout(() => {
      setVisible(false);
      setExiting(false);
    }, 300);
    onboardingClient
      .markCompleted()
      .then(() => refresh().catch(() => {}))
      .catch(() => {});
  }, [refresh, user]);

  const next = useCallback(() => {
    if (currentIndex < slides.length - 1) {
      setCurrentIndex((i) => i + 1);
    } else {
      dismiss();
    }
  }, [currentIndex, slides.length, dismiss]);

  const prev = useCallback(() => {
    if (currentIndex > 0) setCurrentIndex((i) => i - 1);
  }, [currentIndex]);

  if (!visible || slides.length === 0) return null;

  const slide = slides[currentIndex]!;
  const isLast = currentIndex === slides.length - 1;

  return (
    <div
      className={`fixed inset-0 z-[9999] flex items-center justify-center transition-opacity duration-300 ${
        exiting ? 'opacity-0' : 'opacity-100'
      }`}
      style={{ background: 'rgba(0, 0, 0, 0.7)', backdropFilter: 'blur(8px)' }}
    >
      <div
        className="relative w-full max-w-lg mx-4 rounded-2xl overflow-hidden shadow-2xl animate-in fade-in slide-in-from-bottom-4 duration-500"
        style={{ background: slide.backgroundColor }}
      >
        {/* Close button */}
        <button
          onClick={dismiss}
          className="absolute top-4 right-4 p-2 rounded-full hover:bg-white/20 transition-colors z-10"
          aria-label="Skip walkthrough"
        >
          <X size={20} style={{ color: slide.textColor }} />
        </button>

        {/* Slide content */}
        <div className="px-10 pt-12 pb-8 text-center" style={{ color: slide.textColor }}>
          {slide.imageUrl && (
            <div className="mb-8 flex justify-center">
              <img
                src={slide.imageUrl}
                alt={slide.title}
                className="w-48 h-48 object-contain"
              />
            </div>
          )}

          {!slide.imageUrl && (
            <div className="mb-8 flex justify-center">
              <div className="w-32 h-32 rounded-full flex items-center justify-center"
                style={{ background: 'rgba(255,255,255,0.15)' }}>
                <span className="text-5xl font-display font-bold">
                  {currentIndex + 1}
                </span>
              </div>
            </div>
          )}

          <h2 className="text-2xl font-display font-bold mb-4">{slide.title}</h2>
          <p className="text-base leading-relaxed opacity-90 max-w-sm mx-auto">
            {slide.description}
          </p>
        </div>

        {/* Navigation */}
        <div className="px-10 pb-8 flex items-center justify-between">
          <button
            onClick={prev}
            disabled={currentIndex === 0}
            className="p-2 rounded-full hover:bg-white/20 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
          >
            <ChevronLeft size={24} style={{ color: slide.textColor }} />
          </button>

          {/* Dots */}
          <div className="flex gap-2">
            {slides.map((_, i) => (
              <button
                key={i}
                onClick={() => setCurrentIndex(i)}
                className="w-2.5 h-2.5 rounded-full transition-all duration-300"
                style={{
                  background: i === currentIndex
                    ? slide.textColor
                    : `${slide.textColor}40`,
                  transform: i === currentIndex ? 'scale(1.3)' : 'scale(1)',
                }}
              />
            ))}
          </div>

          <button
            onClick={next}
            className="flex items-center gap-2 px-5 py-2.5 rounded-full font-semibold text-sm transition-all hover:scale-105"
            style={{
              background: slide.textColor,
              color: slide.backgroundColor,
            }}
          >
            {isLast ? slide.ctaText || 'Get Started' : slide.ctaText || 'Next'}
            <ArrowRight size={16} />
          </button>
        </div>

        {/* Skip link */}
        <div className="pb-6 text-center">
          <button
            onClick={dismiss}
            className="text-xs underline opacity-60 hover:opacity-100 transition-opacity"
            style={{ color: slide.textColor }}
          >
            Skip walkthrough
          </button>
        </div>
      </div>
    </div>
  );
}
