/**
 * Knowledge Base Onboarding Modal
 * Introduces users to the knowledge base feature and guides them through setup
 */

"use client";

import { Fragment, useState } from "react";
import { Dialog, Transition } from "@headlessui/react";
import type { Lang } from "@/lib/config";
import {
  BookOpen,
  FileText,
  MessageSquareText,
  Brain,
  Upload,
  CheckCircle,
  ArrowRight,
  X,
} from "lucide-react";

interface KnowledgeBaseOnboardingModalProps {
  isOpen: boolean;
  onClose: () => void;
  onComplete: () => void;
  lang: Lang;
}

const steps = [
  {
    id: "intro",
    icon: BookOpen,
    titleEn: "Welcome to Knowledge Base",
    titleAr: "مرحبا بك في قاعدة المعرفة",
    descriptionEn:
      "Your Knowledge Base is an AI-powered system that learns about your business and helps answer customer questions automatically.",
    descriptionAr:
      "قاعدة المعرفة الخاصة بك هي نظام مدعوم بالذكاء الاصطناعي يتعلم عن عملك ويساعد في الإجابة على أسئلة العملاء تلقائيا.",
  },
  {
    id: "documents",
    icon: FileText,
    titleEn: "Upload Your Documents",
    titleAr: "ارفع مستنداتك",
    descriptionEn:
      "Upload documents about your services, policies, pricing, and procedures. We support PDF, Word, and text files up to 10MB.",
    descriptionAr:
      "ارفع مستندات عن خدماتك وسياساتك وأسعارك وإجراءاتك. ندعم ملفات PDF و Word والنصوص حتى 10 ميغابايت.",
    featuresEn: [
      "Service descriptions and catalogs",
      "Pricing information and packages",
      "Company policies and terms",
      "Training materials",
      "FAQs and common procedures",
    ],
    featuresAr: [
      "أوصاف الخدمات والكتالوجات",
      "معلومات التسعير والباقات",
      "سياسات الشركة والشروط",
      "مواد التدريب",
      "الأسئلة الشائعة والإجراءات",
    ],
  },
  {
    id: "faqs",
    icon: MessageSquareText,
    titleEn: "Add Custom FAQs",
    titleAr: "أضف أسئلة شائعة مخصصة",
    descriptionEn:
      "Create question-answer pairs for common customer inquiries. These help the AI give accurate, consistent responses.",
    descriptionAr:
      "أنشئ أزواج من الأسئلة والأجوبة للاستفسارات الشائعة. تساعد هذه الذكاء الاصطناعي في تقديم إجابات دقيقة ومتسقة.",
    featuresEn: [
      "What are your working hours?",
      "How do I book an appointment?",
      "What services do you offer?",
      "What are your prices?",
    ],
    featuresAr: [
      "ما هي ساعات العمل؟",
      "كيف أحجز موعدا؟",
      "ما الخدمات التي تقدمونها؟",
      "ما هي أسعاركم؟",
    ],
  },
  {
    id: "ai",
    icon: Brain,
    titleEn: "AI-Powered Answers",
    titleAr: "إجابات مدعومة بالذكاء الاصطناعي",
    descriptionEn:
      "Our AI reads your documents and FAQs to understand your business. It then answers customer questions accurately using your own information.",
    descriptionAr:
      "يقرأ الذكاء الاصطناعي لدينا مستنداتك وأسئلتك الشائعة لفهم عملك. ثم يجيب على أسئلة العملاء بدقة باستخدام معلوماتك الخاصة.",
    featuresEn: [
      "Answers based on YOUR content",
      "Supports Arabic and English",
      "Learns from new documents",
      "Always cites sources",
    ],
    featuresAr: [
      "إجابات مبنية على محتواك",
      "يدعم العربية والإنجليزية",
      "يتعلم من المستندات الجديدة",
      "يذكر المصادر دائما",
    ],
  },
];

export default function KnowledgeBaseOnboardingModal({
  isOpen,
  onClose,
  onComplete,
  lang,
}: KnowledgeBaseOnboardingModalProps) {
  const isAr = lang === "ar";
  const [currentStep, setCurrentStep] = useState(0);

  const step = steps[currentStep];
  const StepIcon = step.icon;
  const isLastStep = currentStep === steps.length - 1;

  const handleNext = () => {
    if (isLastStep) {
      onComplete();
      onClose();
    } else {
      setCurrentStep((prev) => prev + 1);
    }
  };

  const handleBack = () => {
    setCurrentStep((prev) => Math.max(0, prev - 1));
  };

  const handleSkip = () => {
    onComplete();
    onClose();
  };

  return (
    <Transition appear show={isOpen} as={Fragment}>
      <Dialog
        as="div"
        className="relative z-50"
        onClose={onClose}
        dir={isAr ? "rtl" : "ltr"}
      >
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-2xl transform overflow-hidden rounded-2xl bg-white shadow-2xl transition-all">
                {/* Header */}
                <div className="relative bg-gradient-to-br from-brand-green to-emerald-600 px-6 py-8 text-white">
                  <button
                    onClick={onClose}
                    className="absolute top-4 right-4 rounded-full p-1.5 text-white/80 hover:text-white hover:bg-white/10 transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>

                  <div className="flex items-center gap-4">
                    <div className="flex h-16 w-16 items-center justify-center rounded-xl bg-white/20 backdrop-blur-sm">
                      <StepIcon className="h-8 w-8 text-white" />
                    </div>
                    <div>
                      <Dialog.Title className="text-2xl font-bold">
                        {isAr ? step.titleAr : step.titleEn}
                      </Dialog.Title>
                      <p className="mt-1 text-sm text-white/80">
                        {isAr
                          ? `الخطوة ${currentStep + 1} من ${steps.length}`
                          : `Step ${currentStep + 1} of ${steps.length}`}
                      </p>
                    </div>
                  </div>

                  {/* Progress indicators */}
                  <div className="absolute bottom-0 left-0 right-0 flex gap-1 px-6 pb-4">
                    {steps.map((_, index) => (
                      <div
                        key={index}
                        className={`h-1 flex-1 rounded-full transition-all ${
                          index <= currentStep ? "bg-white" : "bg-white/30"
                        }`}
                      />
                    ))}
                  </div>
                </div>

                {/* Content */}
                <div className="px-6 py-6">
                  <p className="text-slate-600 leading-relaxed">
                    {isAr ? step.descriptionAr : step.descriptionEn}
                  </p>

                  {/* Feature list if available */}
                  {(step.featuresEn || step.featuresAr) && (
                    <div className="mt-6 rounded-xl bg-slate-50 p-4">
                      <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">
                        {step.id === "documents" &&
                          (isAr
                            ? "أنواع المستندات المقترحة"
                            : "Suggested Document Types")}
                        {step.id === "faqs" &&
                          (isAr ? "أمثلة على الأسئلة" : "Example Questions")}
                        {step.id === "ai" &&
                          (isAr ? "المزايا الرئيسية" : "Key Benefits")}
                      </p>
                      <ul className="space-y-2">
                        {(isAr ? step.featuresAr : step.featuresEn)?.map(
                          (feature, index) => (
                            <li key={index} className="flex items-start gap-2">
                              <CheckCircle className="h-4 w-4 text-brand-green mt-0.5 flex-shrink-0" />
                              <span className="text-sm text-slate-700">
                                {feature}
                              </span>
                            </li>
                          ),
                        )}
                      </ul>
                    </div>
                  )}
                </div>

                {/* Footer */}
                <div className="flex items-center justify-between border-t border-slate-100 px-6 py-4">
                  <button
                    onClick={handleSkip}
                    className="text-sm text-slate-500 hover:text-slate-700 transition-colors"
                  >
                    {isAr ? "تخطي المقدمة" : "Skip Introduction"}
                  </button>

                  <div className="flex items-center gap-3">
                    {currentStep > 0 && (
                      <button
                        onClick={handleBack}
                        className="rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
                      >
                        {isAr ? "السابق" : "Back"}
                      </button>
                    )}
                    <button
                      onClick={handleNext}
                      className="inline-flex items-center gap-2 rounded-lg bg-brand-green px-5 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
                    >
                      {isLastStep ? (
                        <>
                          {isAr ? "ابدأ الآن" : "Get Started"}
                          <Upload className="h-4 w-4" />
                        </>
                      ) : (
                        <>
                          {isAr ? "التالي" : "Next"}
                          <ArrowRight className="h-4 w-4" />
                        </>
                      )}
                    </button>
                  </div>
                </div>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  );
}
