/**
 * Knowledge Base Setup Step - Upload documents and add FAQs
 */

"use client";

import { useState } from "react";
import { BookOpen, Upload, Plus, X, CheckCircle2 } from "lucide-react";
import type { Lang } from "@/lib/config";
import type { QuickFAQ } from "@/lib/types/onboarding.types";

interface KnowledgeBaseSetupStepProps {
  lang: Lang;
  onContinue: () => void;
  onSkip: () => void;
}

export default function KnowledgeBaseSetupStep({
  lang,
  onContinue,
  onSkip,
}: KnowledgeBaseSetupStepProps) {
  const isAr = lang === "ar";
  const [faqs, setFaqs] = useState<QuickFAQ[]>([]);
  const [newFaq, setNewFaq] = useState<QuickFAQ>({
    question: "",
    answer: "",
    category: "general",
  });
  const [uploading, setUploading] = useState(false);
  const [uploadedFiles, setUploadedFiles] = useState<string[]>([]);

  const t = {
    title: isAr ? "إعداد قاعدة المعرفة" : "Knowledge Base Setup",
    subtitle: isAr
      ? "علّم الوكيل الذكي عن عيادتك"
      : "Teach your AI agent about your clinic",
    uploadTitle: isAr ? "تحميل المستندات" : "Upload Documents",
    uploadDesc: isAr
      ? "قم بتحميل كتيبات الخدمات، السياسات، إلخ."
      : "Upload service brochures, policies, etc.",
    uploadBtn: isAr ? "اختر الملفات" : "Choose Files",
    faqTitle: isAr ? "الأسئلة الشائعة السريعة" : "Quick FAQs",
    faqDesc: isAr
      ? "أضف بعض الأسئلة الشائعة للبدء"
      : "Add some common questions to get started",
    questionPlaceholder: isAr ? "ما هي ساعات العمل؟" : "What are your hours?",
    answerPlaceholder: isAr
      ? "نحن مفتوحون من 9 صباحاً إلى 9 مساءً"
      : "We're open 9am to 9pm",
    categoryLabel: isAr ? "الفئة" : "Category",
    addFaqBtn: isAr ? "إضافة سؤال" : "Add FAQ",
    skipBtn: isAr ? "تخطي الآن" : "Skip for now",
    continueBtn: isAr ? "حفظ والمتابعة" : "Save & Continue",
    categories: {
      general: isAr ? "عام" : "General",
      services: isAr ? "الخدمات" : "Services",
      pricing: isAr ? "الأسعار" : "Pricing",
      booking: isAr ? "الحجز" : "Booking",
    },
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;

    setUploading(true);
    try {
      const formData = new FormData();
      Array.from(files).forEach((file) => {
        formData.append("files", file);
      });

      const response = await fetch("/api/knowledge-base/upload", {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        setUploadedFiles((prev) => [...prev, ...data.files]);
      }
    } catch (error) {
      console.error("Upload error:", error);
    } finally {
      setUploading(false);
    }
  };

  const handleAddFaq = () => {
    if (newFaq.question && newFaq.answer) {
      setFaqs((prev) => [...prev, newFaq]);
      setNewFaq({ question: "", answer: "", category: "general" });
    }
  };

  const handleRemoveFaq = (index: number) => {
    setFaqs((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSave = async () => {
    try {
      await fetch("/api/knowledge-base/faqs", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ faqs }),
      });
      onContinue();
    } catch (error) {
      console.error("Error saving FAQs:", error);
    }
  };

  return (
    <div className="space-y-8 animate-fadeIn">
      {/* Header */}
      <div className="text-center">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-br from-purple-500 to-violet-600 shadow-lg shadow-purple-500/25 mb-6">
          <BookOpen className="w-8 h-8 text-white" />
        </div>
        <h2 className="text-3xl font-bold text-slate-900 mb-3">{t.title}</h2>
        <p className="text-lg text-slate-600">{t.subtitle}</p>
      </div>

      {/* Document Upload */}
      <div className="p-6 rounded-2xl bg-white border border-slate-200">
        <h3 className="text-lg font-bold text-slate-900 mb-2">
          {t.uploadTitle}
        </h3>
        <p className="text-sm text-slate-600 mb-4">{t.uploadDesc}</p>

        <label className="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-slate-300 rounded-xl cursor-pointer hover:border-brand-green hover:bg-brand-green/5 transition-all">
          <Upload className="w-8 h-8 text-slate-400 mb-2" />
          <span className="text-sm text-slate-600">{t.uploadBtn}</span>
          <input
            type="file"
            multiple
            className="hidden"
            onChange={handleFileUpload}
            accept=".pdf,.doc,.docx,.txt"
          />
        </label>

        {uploadedFiles.length > 0 && (
          <div className="mt-4 space-y-2">
            {uploadedFiles.map((file, index) => (
              <div
                key={index}
                className="flex items-center gap-2 text-sm text-slate-600"
              >
                <CheckCircle2 className="w-4 h-4 text-green-500" />
                <span>{file}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* FAQ Section */}
      <div className="p-6 rounded-2xl bg-white border border-slate-200">
        <h3 className="text-lg font-bold text-slate-900 mb-2">{t.faqTitle}</h3>
        <p className="text-sm text-slate-600 mb-4">{t.faqDesc}</p>

        {/* Add FAQ Form */}
        <div className="space-y-3 mb-4">
          <input
            type="text"
            value={newFaq.question}
            onChange={(e) => setNewFaq({ ...newFaq, question: e.target.value })}
            placeholder={t.questionPlaceholder}
            className="w-full px-4 py-3 rounded-xl border border-slate-200 text-slate-900 placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
          />
          <textarea
            value={newFaq.answer}
            onChange={(e) => setNewFaq({ ...newFaq, answer: e.target.value })}
            placeholder={t.answerPlaceholder}
            rows={3}
            className="w-full px-4 py-3 rounded-xl border border-slate-200 text-slate-900 placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none resize-none"
          />
          <div className="flex gap-3">
            <select
              value={newFaq.category}
              onChange={(e) =>
                setNewFaq({ ...newFaq, category: e.target.value })
              }
              className="flex-1 px-4 py-3 rounded-xl border border-slate-200 text-slate-900 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
            >
              {Object.entries(t.categories).map(([key, label]) => (
                <option key={key} value={key}>
                  {label}
                </option>
              ))}
            </select>
            <button
              onClick={handleAddFaq}
              disabled={!newFaq.question || !newFaq.answer}
              className="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-brand-green text-white font-semibold hover:bg-brand-greenHover disabled:opacity-50 disabled:cursor-not-allowed transition-all"
            >
              <Plus className="w-4 h-4" />
              {t.addFaqBtn}
            </button>
          </div>
        </div>

        {/* FAQ List */}
        {faqs.length > 0 && (
          <div className="space-y-3 mt-4 pt-4 border-t border-slate-200">
            {faqs.map((faq, index) => (
              <div
                key={index}
                className="p-4 rounded-xl bg-slate-50 border border-slate-200"
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1">
                    <p className="font-semibold text-slate-900 mb-1">
                      {faq.question}
                    </p>
                    <p className="text-sm text-slate-600">{faq.answer}</p>
                    <span className="inline-block mt-2 px-2 py-1 rounded text-xs font-medium bg-brand-green/10 text-brand-green">
                      {t.categories[faq.category as keyof typeof t.categories]}
                    </span>
                  </div>
                  <button
                    onClick={() => handleRemoveFaq(index)}
                    className="flex-shrink-0 p-1 text-slate-400 hover:text-red-500 transition-colors"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Actions */}
      <div className="flex items-center justify-between pt-4">
        <button
          onClick={onSkip}
          className="text-sm font-medium text-slate-600 hover:text-brand-green transition-colors"
        >
          {t.skipBtn}
        </button>
        <button
          onClick={handleSave}
          className="inline-flex items-center gap-2 px-8 py-4 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-white font-semibold shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 hover:-translate-y-0.5 transition-all"
        >
          {t.continueBtn}
          <span className="text-xl">{isAr ? "←" : "→"}</span>
        </button>
      </div>

      <style jsx>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        .animate-fadeIn {
          animation: fadeIn 0.4s ease-out forwards;
        }
      `}</style>
    </div>
  );
}
