"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
import {
  Briefcase,
  Building2,
  User,
  ArrowRight,
  ArrowLeft,
  Sparkles,
  X,
  ChevronRight,
  UploadCloud,
} from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { apiFetch } from "@/lib/csrf/client";

interface OnboardingWizardProps {
  isOpen: boolean;
  fullScreen?: boolean;
  onComplete: (data: {
    useCase: string;
    monthlyVolume: string;
    exportFormat: string;
    referralSource: string;
  }) => void;
  onSkip?: () => void;
}

export function OnboardingWizard({ isOpen, fullScreen = false, onComplete, onSkip }: OnboardingWizardProps) {
  const router = useRouter();
  const { language } = useI18n();
  const isDe = language === "de";

  const [step, setStep] = useState<number>(1);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [useCase, setUseCase] = useState<string>("");

  if (!isOpen) return null;

  const totalSteps = 3;
  const progressPercent = Math.round(((step - 1) / totalSteps) * 100);

  const finish = async (navigateToFirstScan: boolean) => {
    setIsSubmitting(true);
    try {
      await apiFetch("/api/onboarding", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          useCase: useCase || "unassigned",
          monthlyVolume: "unassigned",
          exportFormat: "unassigned",
          referralSource: "unassigned",
        }),
      });
    } catch (err) {
      console.error("Failed to save onboarding responses", err);
    } finally {
      setIsSubmitting(false);
      onComplete({
        useCase,
        monthlyVolume: "unassigned",
        exportFormat: "unassigned",
        referralSource: "unassigned",
      });
      router.push(navigateToFirstScan ? "/dashboard?firstScan=1" : "/dashboard");
    }
  };

  const handleSkip = async () => {
    onSkip?.();
    await finish(true);
  };

  const personaOptions = [
    {
      id: "freelancer",
      title: isDe ? "Freelancer & Solo-Selbstständiger" : "Freelancer & Solo Entrepreneur",
      desc: isDe ? "Belege scannen und schnell als Excel exportieren" : "Scan receipts and export them to Excel fast",
      icon: Briefcase,
      badge: isDe ? "Beliebt" : "Popular",
    },
    {
      id: "small_business",
      title: isDe ? "Kleinunternehmen & Start-up" : "Small Business & Team",
      desc: isDe ? "Mehrere Belege, Ausgaben & Reisekosten verwalten" : "Manage team expenses, purchases & travel receipts",
      icon: Building2,
    },
    {
      id: "personal",
      title: isDe ? "Privatperson" : "Personal / Household",
      desc: isDe ? "Garantiebelege, Haushaltsbuch & private Ausgaben" : "Warranties, household budgeting & personal expenses",
      icon: User,
    },
  ];

  const OptionCard = ({
    item,
    selected,
    onSelect,
  }: {
    item: { id: string; title: string; desc: string; icon: typeof Briefcase; badge?: string };
    selected: boolean;
    onSelect: () => void;
  }) => {
    const Icon = item.icon;
    return (
      <button
        key={item.id}
        type="button"
        onClick={onSelect}
        className={`relative p-4 rounded-xl border text-left transition-all duration-150 flex flex-col justify-between group ${
          selected
            ? "bg-emerald-500/10 border-emerald-500 text-white shadow-lg shadow-emerald-500/5"
            : "bg-slate-900/60 hover:bg-slate-800/60 border-slate-800 hover:border-slate-700 text-slate-200"
        }`}
      >
        {item.badge && (
          <span className="absolute top-3 right-3 text-[10px] uppercase tracking-wider font-semibold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 px-2 py-0.5 rounded-full">
            {item.badge}
          </span>
        )}
        <div>
          <div className="w-9 h-9 rounded-lg bg-slate-800/80 border border-slate-700/60 flex items-center justify-center text-emerald-400 mb-3 group-hover:scale-105 transition-transform">
            <Icon size={18} />
          </div>
          <h3 className="font-semibold text-sm text-slate-100 mb-1">{item.title}</h3>
          <p className="text-xs text-slate-400 leading-relaxed">{item.desc}</p>
        </div>
        <div className="mt-4 flex items-center text-xs font-medium text-emerald-400 gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          <span>{isDe ? "Auswählen" : "Select"}</span>
          <ChevronRight size={14} />
        </div>
      </button>
    );
  };

  return (
    <div
      className={
        fullScreen
          ? "min-h-screen bg-slate-950 flex items-center justify-center p-4 sm:p-6 overflow-y-auto"
          : "fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-slate-950/80 backdrop-blur-md animate-in fade-in duration-200 overflow-y-auto"
      }
    >
      <div className="relative w-full max-w-2xl bg-slate-900 border border-slate-800 rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh] my-4">
        <div className="px-6 pt-6 pb-4 border-b border-slate-800/80 bg-slate-900/50">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="w-7 h-7 rounded-lg bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-emerald-400 font-semibold text-xs">
                {step}/{totalSteps}
              </div>
              <span className="text-xs font-medium text-slate-400 uppercase tracking-wider">
                {isDe ? `Schritt ${step} von ${totalSteps}` : `Step ${step} of ${totalSteps}`}
              </span>
            </div>

            <button
              onClick={handleSkip}
              disabled={isSubmitting}
              className="text-xs font-medium text-slate-400 hover:text-slate-200 px-3 py-1.5 rounded-lg hover:bg-slate-800/60 transition-colors flex items-center gap-1"
            >
              {isDe ? "Direkt scannen" : "Skip to scan"}
              <X size={14} />
            </button>
          </div>

          <div className="w-full h-1.5 bg-slate-800 rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-emerald-500 to-teal-400 transition-all duration-300 rounded-full"
              style={{ width: `${progressPercent}%` }}
            />
          </div>
        </div>

        <div className="p-6 overflow-y-auto flex-1 custom-scrollbar">
          {step === 1 && (
            <div className="space-y-5 animate-in fade-in slide-in-from-right-4 duration-200 text-center py-4">
              <div className="w-16 h-16 bg-emerald-500/10 border border-emerald-500/30 rounded-2xl flex items-center justify-center text-emerald-400 mx-auto">
                <Sparkles size={30} />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-slate-100 mb-2">
                  {isDe ? "Willkommen bei ScanReceipts!" : "Welcome to ScanReceipts!"}
                </h2>
                <p className="text-sm text-slate-400 max-w-md mx-auto leading-relaxed">
                  {isDe
                    ? "Du kannst sofort scannen. Optional: sag uns in einem Klick, wofür du ScanReceipts nutzt."
                    : "You can start scanning right away. Optionally tell us in one click how you'll use ScanReceipts."}
                </p>
              </div>

              <div className="flex flex-col sm:flex-row gap-3 justify-center pt-2">
                <button
                  type="button"
                  onClick={handleSkip}
                  disabled={isSubmitting}
                  className="h-11 px-6 bg-white text-slate-900 rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-2"
                >
                  <UploadCloud className="w-4 h-4" />
                  <span>{isDe ? "Sofort scannen" : "Scan now"}</span>
                </button>
                <button
                  type="button"
                  onClick={() => setStep(2)}
                  className="h-11 px-6 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-2"
                >
                  <span>{isDe ? "Kurz einrichten" : "Quick setup"}</span>
                  <ArrowRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="space-y-5 animate-in fade-in slide-in-from-right-4 duration-200">
              <div>
                <h2 className="text-xl font-bold text-slate-100 mb-1">
                  {isDe ? "Wofür nutzt du ScanReceipts?" : "How will you use ScanReceipts?"}
                </h2>
                <p className="text-sm text-slate-400">
                  {isDe
                    ? "Ein Klick reicht — danach geht's direkt zum Scanner."
                    : "One click is enough — then you land on the scanner."}
                </p>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2">
                {personaOptions.map((item) => (
                  <OptionCard
                    key={item.id}
                    item={item}
                    selected={useCase === item.id}
                    onSelect={() => {
                      setUseCase(item.id);
                      setStep(3);
                    }}
                  />
                ))}
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="text-center py-6 px-4 space-y-6 animate-in zoom-in-95 duration-200">
              <div className="w-16 h-16 bg-emerald-500/10 border border-emerald-500/30 rounded-2xl flex items-center justify-center text-emerald-400 mx-auto shadow-xl shadow-emerald-500/10">
                <Sparkles size={32} />
              </div>

              <div className="max-w-md mx-auto">
                <h2 className="text-2xl font-bold text-slate-100 mb-2">
                  {isDe ? "Bereit zum Scannen" : "Ready to scan"}
                </h2>
                <p className="text-sm text-slate-400 leading-relaxed">
                  {isDe
                    ? "Zieh einen Beleg in die Dropzone oder fotografiere ihn mit der Kamera."
                    : "Drop a receipt into the dropzone or snap it with your camera."}
                </p>
              </div>

              <button
                onClick={() => finish(true)}
                disabled={isSubmitting}
                className="w-full sm:w-auto px-8 py-3.5 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white font-medium rounded-xl shadow-lg shadow-emerald-600/20 transition-all flex items-center justify-center gap-2 mx-auto disabled:opacity-60"
              >
                {isSubmitting ? (
                  <span>{isDe ? "Wird gespeichert…" : "Saving…"}</span>
                ) : (
                  <>
                    <span>{isDe ? "Jetzt ersten Beleg scannen" : "Scan first receipt"}</span>
                    <ArrowRight size={18} />
                  </>
                )}
              </button>
            </div>
          )}
        </div>

        {step > 1 && (
          <div className="px-6 py-4 border-t border-slate-800/80 bg-slate-900/50 flex items-center justify-between">
            <button
              type="button"
              onClick={() => setStep((s) => s - 1)}
              disabled={isSubmitting}
              className="text-xs font-medium text-slate-400 hover:text-slate-200 px-3 py-2 rounded-lg hover:bg-slate-800 transition-colors flex items-center gap-1.5"
            >
              <ArrowLeft size={14} />
              <span>{isDe ? "Zurück" : "Back"}</span>
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
