/**
 * Knowledge Base Panel
 * Main dashboard view for Knowledge Base management
 * Supports multimodal media: documents, images, videos, audio, and FAQs
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import {
  BookOpen,
  FileText,
  MessageSquareText,
  Upload,
  Plus,
  Search,
  Trash2,
  Edit3,
  AlertCircle,
  CheckCircle,
  Clock,
  XCircle,
  RefreshCw,
  HelpCircle,
  Image as ImageIcon,
  Video,
  Music,
  Play,
  Sparkles,
} from "lucide-react";
import KnowledgeBaseQueryPanel from "./KnowledgeBaseQueryPanel";
import KnowledgeBaseOnboardingModal from "./KnowledgeBaseOnboardingModal";
import MediaUploadModal from "./MediaUploadModal";
import FAQEditorModal from "./FAQEditorModal";
import SuggestedFAQs from "@/components/dashboard/SuggestedFAQs";
import WhatsAppGreetingForm from "@/components/dashboard/WhatsAppGreetingForm";
import SectorPickerForm from "@/app/[lang]/dashboard/components/whatsapp/SectorPickerForm";
import type {
  KnowledgeBaseDocument,
  KnowledgeBaseFAQ,
  KnowledgeBaseSettings,
  KBMediaType,
} from "@/lib/types/knowledge-base.types";
import {
  DOCUMENT_CATEGORIES,
  FILE_TYPE_LABELS,
  MEDIA_TYPE_LABELS,
  MEDIA_FILE_TYPE_LABELS,
  getMediaType,
} from "@/lib/types/knowledge-base.types";

interface KnowledgeBasePanelProps {
  lang: Lang;
  organizationId?: string | null;
}

interface Stats {
  totalDocuments: number;
  processedDocuments: number;
  pendingDocuments: number;
  failedDocuments: number;
  totalFAQs: number;
  activeFAQs: number;
  totalChunks: number;
}

type TabType = "all" | "documents" | "images" | "videos" | "audio" | "faqs";

// Helper to get media type from a document
const getDocMediaType = (doc: KnowledgeBaseDocument): KBMediaType => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const mt = (doc as any).mediaType;
  if (mt && ["document", "image", "video", "audio"].includes(mt))
    return mt as KBMediaType;
  return getMediaType(doc.mimeType);
};

// Helper to get media icon component
const getMediaIcon = (mediaType: string) => {
  switch (mediaType) {
    case "image":
      return ImageIcon;
    case "video":
      return Video;
    case "audio":
      return Music;
    default:
      return FileText;
  }
};

// Media type icon colors
const getMediaIconColor = (mediaType: string) => {
  switch (mediaType) {
    case "image":
      return "bg-pink-50 text-pink-600";
    case "video":
      return "bg-purple-50 text-purple-600";
    case "audio":
      return "bg-orange-50 text-orange-600";
    default:
      return "bg-blue-50 text-blue-600";
  }
};

// Format duration in seconds to mm:ss
const formatDuration = (seconds: number | undefined): string => {
  if (!seconds) return "0:00";
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, "0")}`;
};

export default function KnowledgeBasePanel({
  lang,
  organizationId,
}: KnowledgeBasePanelProps) {
  const isAr = lang === "ar";

  // State
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [settings, setSettings] = useState<KnowledgeBaseSettings | null>(null);
  const [stats, setStats] = useState<Stats | null>(null);
  const [documents, setDocuments] = useState<KnowledgeBaseDocument[]>([]);
  const [faqs, setFAQs] = useState<KnowledgeBaseFAQ[]>([]);
  const [activeTab, setActiveTab] = useState<TabType>("all");
  const [csrfToken, setCsrfToken] = useState("");

  // Modals
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [showFAQModal, setShowFAQModal] = useState(false);
  const [editingFAQ, setEditingFAQ] = useState<KnowledgeBaseFAQ | null>(null);

  // Query panel
  const [showQueryPanel, setShowQueryPanel] = useState(false);

  // Search
  const [searchQuery, setSearchQuery] = useState("");

  // Fetch CSRF token
  useEffect(() => {
    fetch("/api/csrf")
      .then((res) => res.json())
      .then((data) => setCsrfToken(data.csrfToken))
      .catch((err) => console.error("Failed to fetch CSRF token", err));
  }, []);

  // Load data
  const loadData = useCallback(async (showRefresh = false) => {
    if (showRefresh) setRefreshing(true);
    else setLoading(true);

    try {
      const [overviewRes, documentsRes, faqsRes] = await Promise.all([
        fetch("/api/dashboard/knowledge-base"),
        fetch("/api/dashboard/knowledge-base/documents"),
        fetch("/api/dashboard/knowledge-base/faqs"),
      ]);

      if (overviewRes.ok) {
        const data = await overviewRes.json();
        setSettings(data.settings);
        setStats(data.stats);

        // Show onboarding once — check both server flag and localStorage
        const dismissedLocally = typeof window !== "undefined" && localStorage.getItem("kb-onboarding-dismissed") === "true";
        if (data.settings && !data.settings.onboardingCompleted && !dismissedLocally) {
          setShowOnboarding(true);
        }
      }

      if (documentsRes.ok) {
        const data = await documentsRes.json();
        setDocuments(data.documents || []);
      }

      if (faqsRes.ok) {
        const data = await faqsRes.json();
        setFAQs(data.faqs || []);
      }
    } catch (error) {
      console.error("Failed to load knowledge base data", error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // Complete onboarding
  const handleCompleteOnboarding = async () => {
    try {
      await fetch("/api/dashboard/knowledge-base/settings", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({ onboardingCompleted: true }),
      });
      setSettings((prev) =>
        prev ? { ...prev, onboardingCompleted: true } : null,
      );
    } catch (error) {
      console.error("Failed to complete onboarding", error);
    }
    if (typeof window !== "undefined") localStorage.setItem("kb-onboarding-dismissed", "true");
    setShowOnboarding(false);
  };

  // Delete document
  const handleDeleteDocument = async (documentId: string) => {
    if (
      !confirm(
        isAr
          ? "هل أنت متأكد من حذف هذا المستند؟"
          : "Are you sure you want to delete this document?",
      )
    ) {
      return;
    }

    try {
      const res = await fetch(
        `/api/dashboard/knowledge-base/documents/${documentId}`,
        {
          method: "DELETE",
          headers: { "x-csrf-token": csrfToken },
        },
      );

      if (res.ok) {
        setDocuments((prev) => prev.filter((d) => d.id !== documentId));
        loadData(true); // Refresh stats
      }
    } catch (error) {
      console.error("Failed to delete document", error);
    }
  };

  // Delete FAQ
  const handleDeleteFAQ = async (faqId: string) => {
    if (
      !confirm(
        isAr
          ? "هل أنت متأكد من حذف هذا السؤال؟"
          : "Are you sure you want to delete this FAQ?",
      )
    ) {
      return;
    }

    try {
      const res = await fetch(`/api/dashboard/knowledge-base/faqs/${faqId}`, {
        method: "DELETE",
        headers: { "x-csrf-token": csrfToken },
      });

      if (res.ok) {
        setFAQs((prev) => prev.filter((f) => f.id !== faqId));
        loadData(true); // Refresh stats
      }
    } catch (error) {
      console.error("Failed to delete FAQ", error);
    }
  };

  // Compute media type counts
  const mediaCounts = documents.reduce(
    (acc, doc) => {
      const mt = getDocMediaType(doc);
      acc[mt] = (acc[mt] || 0) + 1;
      return acc;
    },
    { document: 0, image: 0, video: 0, audio: 0 } as Record<
      KBMediaType,
      number
    >,
  );

  // Filter documents by tab (media type)
  const filteredByTab = documents.filter((doc) => {
    const mt = getDocMediaType(doc);
    if (activeTab === "all") return true;
    if (activeTab === "documents") return mt === "document";
    if (activeTab === "images") return mt === "image";
    if (activeTab === "videos") return mt === "video";
    if (activeTab === "audio") return mt === "audio";
    return true;
  });

  // Then apply search filter
  const filteredDocuments = filteredByTab.filter(
    (doc) =>
      (doc.title || doc.originalName)
        .toLowerCase()
        .includes(searchQuery.toLowerCase()) ||
      doc.category.toLowerCase().includes(searchQuery.toLowerCase()),
  );

  const filteredFAQs = faqs.filter(
    (faq) =>
      faq.questionEn.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (faq.questionAr && faq.questionAr.includes(searchQuery)) ||
      faq.answerEn.toLowerCase().includes(searchQuery.toLowerCase()),
  );

  // Status badge component
  const StatusBadge = ({ status }: { status: string }) => {
    const config = {
      COMPLETED: {
        icon: CheckCircle,
        color: "text-emerald-600 bg-emerald-50",
        label: isAr ? "جاهز" : "Ready",
      },
      PENDING: {
        icon: Clock,
        color: "text-amber-600 bg-amber-50",
        label: isAr ? "قيد المعالجة" : "Processing",
      },
      PROCESSING: {
        icon: RefreshCw,
        color: "text-blue-600 bg-blue-50",
        label: isAr ? "معالجة" : "Processing",
      },
      FAILED: {
        icon: XCircle,
        color: "text-red-600 bg-red-50",
        label: isAr ? "فشل" : "Failed",
      },
    }[status] || {
      icon: AlertCircle,
      color: "text-slate-600 bg-slate-50",
      label: status,
    };

    const Icon = config.icon;

    return (
      <span
        className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${config.color}`}
      >
        <Icon className="h-3 w-3" />
        {config.label}
      </span>
    );
  };

  // Get category label
  const getCategoryLabel = (value: string) => {
    const category = DOCUMENT_CATEGORIES.find((c) => c.value === value);
    return category ? (isAr ? category.labelAr : category.labelEn) : value;
  };

  // Upload button text based on active tab
  const getUploadButtonText = () => {
    switch (activeTab) {
      case "images":
        return isAr ? "رفع صورة" : "Upload Image";
      case "videos":
        return isAr ? "رفع فيديو" : "Upload Video";
      case "audio":
        return isAr ? "رفع صوت" : "Upload Audio";
      case "faqs":
        return isAr ? "إضافة سؤال" : "Add FAQ";
      default:
        return isAr ? "رفع" : "Upload";
    }
  };

  // Tab configuration
  const tabs: {
    key: TabType;
    icon: typeof BookOpen;
    labelEn: string;
    labelAr: string;
    count: number;
  }[] = [
    {
      key: "all",
      icon: BookOpen,
      labelEn: "All",
      labelAr: "الكل",
      count: documents.length,
    },
    {
      key: "documents",
      icon: FileText,
      labelEn: "Documents",
      labelAr: "المستندات",
      count: mediaCounts.document,
    },
    {
      key: "images",
      icon: ImageIcon,
      labelEn: "Images",
      labelAr: "الصور",
      count: mediaCounts.image,
    },
    {
      key: "videos",
      icon: Video,
      labelEn: "Videos",
      labelAr: "الفيديو",
      count: mediaCounts.video,
    },
    {
      key: "audio",
      icon: Music,
      labelEn: "Audio",
      labelAr: "الصوت",
      count: mediaCounts.audio,
    },
    {
      key: "faqs",
      icon: MessageSquareText,
      labelEn: "FAQs",
      labelAr: "الأسئلة الشائعة",
      count: faqs.length,
    },
  ];

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <RefreshCw className="h-8 w-8 text-brand-green animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fadeIn">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
            <BookOpen className="h-6 w-6 text-brand-green" />
            {isAr ? "قاعدة المعرفة" : "Knowledge Base"}
          </h2>
          <p className="text-slate-600 mt-1">
            {isAr
              ? "قم بتدريب الذكاء الاصطناعي على معلومات عملك للإجابة على استفسارات العملاء"
              : "Train AI on your business information to answer customer inquiries"}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => loadData(true)}
            disabled={refreshing}
            className="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors disabled:opacity-50"
          >
            <RefreshCw
              className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`}
            />
            {isAr ? "تحديث" : "Refresh"}
          </button>
          <button
            onClick={() => setShowOnboarding(true)}
            className="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <HelpCircle className="h-4 w-4" />
            {isAr ? "مساعدة" : "Help"}
          </button>
        </div>
      </div>

      {/* Stats Cards */}
      {stats && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
          {/* Total Media */}
          <div className="rounded-xl bg-gradient-to-br from-blue-50 to-indigo-50 p-4 border border-blue-100">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-500">
                <BookOpen className="h-5 w-5 text-white" />
              </div>
              <div>
                <p className="text-xs font-medium text-slate-500 uppercase">
                  {isAr ? "إجمالي الوسائط" : "Total Media"}
                </p>
                <p className="text-2xl font-bold text-slate-900">
                  {stats.totalDocuments}
                </p>
              </div>
            </div>
            {stats.pendingDocuments > 0 && (
              <p className="mt-2 text-xs text-amber-600">
                {stats.pendingDocuments} {isAr ? "قيد المعالجة" : "processing"}
              </p>
            )}
          </div>

          {/* Documents */}
          <div className="rounded-xl bg-gradient-to-br from-slate-50 to-gray-50 p-4 border border-slate-200">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-slate-600">
                <FileText className="h-5 w-5 text-white" />
              </div>
              <div>
                <p className="text-xs font-medium text-slate-500 uppercase">
                  {isAr ? "المستندات" : "Documents"}
                </p>
                <p className="text-2xl font-bold text-slate-900">
                  {mediaCounts.document}
                </p>
              </div>
            </div>
          </div>

          {/* Images */}
          <div className="rounded-xl bg-gradient-to-br from-pink-50 to-rose-50 p-4 border border-pink-100">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-pink-500">
                <ImageIcon className="h-5 w-5 text-white" />
              </div>
              <div>
                <p className="text-xs font-medium text-slate-500 uppercase">
                  {isAr ? "الصور" : "Images"}
                </p>
                <p className="text-2xl font-bold text-slate-900">
                  {mediaCounts.image}
                </p>
              </div>
            </div>
          </div>

          {/* Videos & Audio */}
          <div className="rounded-xl bg-gradient-to-br from-purple-50 to-violet-50 p-4 border border-purple-100">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-500">
                <Video className="h-5 w-5 text-white" />
              </div>
              <div>
                <p className="text-xs font-medium text-slate-500 uppercase">
                  {isAr ? "فيديو وصوت" : "Videos & Audio"}
                </p>
                <p className="text-2xl font-bold text-slate-900">
                  {mediaCounts.video + mediaCounts.audio}
                </p>
              </div>
            </div>
          </div>

          {/* FAQs */}
          <div className="rounded-xl bg-gradient-to-br from-violet-50 to-purple-50 p-4 border border-violet-100">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-violet-500">
                <MessageSquareText className="h-5 w-5 text-white" />
              </div>
              <div>
                <p className="text-xs font-medium text-slate-500 uppercase">
                  {isAr ? "الأسئلة الشائعة" : "FAQs"}
                </p>
                <p className="text-2xl font-bold text-slate-900">
                  {stats.activeFAQs}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Tabs and Search */}
      <div className="flex flex-col gap-4">
        {/* Tab bar */}
        <div className="flex rounded-lg bg-slate-100 p-1 overflow-x-auto">
          {tabs.map((tab) => {
            const TabIcon = tab.icon;
            return (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-all whitespace-nowrap ${
                  activeTab === tab.key
                    ? "bg-white text-slate-900 shadow-sm"
                    : "text-slate-600 hover:text-slate-900"
                }`}
              >
                <TabIcon className="h-4 w-4" />
                {isAr ? tab.labelAr : tab.labelEn}
                <span className="rounded-full bg-slate-200 px-2 py-0.5 text-xs">
                  {tab.count}
                </span>
              </button>
            );
          })}
        </div>

        {/* Search and Upload */}
        <div className="flex items-center gap-3 justify-end">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
            <input
              type="text"
              placeholder={isAr ? "بحث..." : "Search..."}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="h-10 w-64 rounded-lg border border-slate-200 bg-white pl-10 pr-4 text-sm placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none"
            />
          </div>
          <button
            onClick={() =>
              activeTab === "faqs"
                ? setShowFAQModal(true)
                : setShowUploadModal(true)
            }
            className="inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
          >
            {activeTab === "faqs" ? (
              <Plus className="h-4 w-4" />
            ) : (
              <Upload className="h-4 w-4" />
            )}
            {getUploadButtonText()}
          </button>
        </div>
      </div>

      {/* Images Tab - Grid View */}
      {activeTab === "images" && (
        <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
          {filteredDocuments.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-pink-50 mb-4">
                <ImageIcon className="h-8 w-8 text-pink-400" />
              </div>
              <h3 className="text-lg font-semibold text-slate-900">
                {isAr ? "لا توجد صور" : "No Images"}
              </h3>
              <p className="mt-1 text-sm text-slate-500 max-w-sm">
                {isAr
                  ? "ارفع صور منتجاتك أو خدماتك لمساعدة الذكاء الاصطناعي"
                  : "Upload images of your products or services to help AI"}
              </p>
              <button
                onClick={() => setShowUploadModal(true)}
                className="mt-4 inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
              >
                <Upload className="h-4 w-4" />
                {isAr ? "رفع أول صورة" : "Upload First Image"}
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 p-4">
              {filteredDocuments.map((doc) => (
                <div
                  key={doc.id}
                  className="group relative rounded-xl border border-slate-200 overflow-hidden hover:shadow-md transition-shadow"
                >
                  <div className="aspect-square bg-slate-100 flex items-center justify-center">
                    {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
                    {(doc as any).mediaUrl ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={
                          (doc as unknown as Record<string, unknown>)
                            .mediaUrl as string
                        }
                        alt={doc.title || doc.originalName}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <ImageIcon className="h-12 w-12 text-slate-300" />
                    )}
                  </div>
                  <div className="p-3">
                    <p className="text-sm font-medium text-slate-900 truncate">
                      {doc.title || doc.originalName}
                    </p>
                    <p className="text-xs text-slate-500">
                      {getCategoryLabel(doc.category)}
                    </p>
                  </div>
                  <button
                    onClick={() => handleDeleteDocument(doc.id)}
                    className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 rounded-full p-1.5 bg-white/80 text-red-500 hover:bg-red-50 transition-all"
                    title={isAr ? "حذف" : "Delete"}
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                  <div className="absolute top-2 left-2">
                    <StatusBadge status={doc.status} />
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Videos Tab - Cards with play overlay */}
      {activeTab === "videos" && (
        <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
          {filteredDocuments.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-purple-50 mb-4">
                <Video className="h-8 w-8 text-purple-400" />
              </div>
              <h3 className="text-lg font-semibold text-slate-900">
                {isAr ? "لا توجد فيديوهات" : "No Videos"}
              </h3>
              <p className="mt-1 text-sm text-slate-500 max-w-sm">
                {isAr
                  ? "ارفع فيديوهات تدريبية أو توضيحية لقاعدة المعرفة"
                  : "Upload training or explainer videos to your knowledge base"}
              </p>
              <button
                onClick={() => setShowUploadModal(true)}
                className="mt-4 inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
              >
                <Upload className="h-4 w-4" />
                {isAr ? "رفع أول فيديو" : "Upload First Video"}
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 p-4">
              {filteredDocuments.map((doc) => {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const docAny = doc as any;
                return (
                  <div
                    key={doc.id}
                    className="group relative rounded-xl border border-slate-200 overflow-hidden hover:shadow-md transition-shadow"
                  >
                    <div className="aspect-video bg-slate-900 flex items-center justify-center relative">
                      {docAny.thumbnailUrl ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img
                          src={docAny.thumbnailUrl}
                          alt={doc.title || doc.originalName}
                          className="w-full h-full object-cover opacity-80"
                        />
                      ) : (
                        <Video className="h-12 w-12 text-slate-500" />
                      )}
                      {/* Play icon overlay */}
                      <div className="absolute inset-0 flex items-center justify-center">
                        <div className="flex h-14 w-14 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm group-hover:bg-white/40 transition-colors">
                          <Play className="h-7 w-7 text-white ml-1" />
                        </div>
                      </div>
                      {/* Duration badge */}
                      {docAny.duration && (
                        <div className="absolute bottom-2 right-2 rounded bg-black/70 px-2 py-0.5 text-xs text-white font-medium">
                          {formatDuration(docAny.duration)}
                        </div>
                      )}
                    </div>
                    <div className="p-3">
                      <p className="text-sm font-medium text-slate-900 truncate">
                        {doc.title || doc.originalName}
                      </p>
                      <div className="flex items-center gap-2 mt-1 text-xs text-slate-500">
                        <span>{getCategoryLabel(doc.category)}</span>
                        <span>-</span>
                        <span>
                          {MEDIA_FILE_TYPE_LABELS[doc.mimeType] || doc.mimeType}
                        </span>
                      </div>
                    </div>
                    <button
                      onClick={() => handleDeleteDocument(doc.id)}
                      className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 rounded-full p-1.5 bg-white/80 text-red-500 hover:bg-red-50 transition-all"
                      title={isAr ? "حذف" : "Delete"}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                    <div className="absolute top-2 left-2">
                      <StatusBadge status={doc.status} />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* Audio Tab - List with Music icon and duration */}
      {activeTab === "audio" && (
        <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
          {filteredDocuments.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-orange-50 mb-4">
                <Music className="h-8 w-8 text-orange-400" />
              </div>
              <h3 className="text-lg font-semibold text-slate-900">
                {isAr ? "لا توجد ملفات صوتية" : "No Audio Files"}
              </h3>
              <p className="mt-1 text-sm text-slate-500 max-w-sm">
                {isAr
                  ? "ارفع تسجيلات صوتية لتدريب الذكاء الاصطناعي"
                  : "Upload audio recordings to train AI on your content"}
              </p>
              <button
                onClick={() => setShowUploadModal(true)}
                className="mt-4 inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
              >
                <Upload className="h-4 w-4" />
                {isAr ? "رفع أول ملف صوتي" : "Upload First Audio"}
              </button>
            </div>
          ) : (
            <div className="divide-y divide-slate-100">
              {filteredDocuments.map((doc) => {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const docAny = doc as any;
                return (
                  <div
                    key={doc.id}
                    className="flex items-center justify-between p-4 hover:bg-slate-50 transition-colors"
                  >
                    <div className="flex items-center gap-4 min-w-0">
                      <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-orange-50 text-orange-600 flex-shrink-0">
                        <Music className="h-6 w-6" />
                      </div>
                      <div className="min-w-0">
                        <p className="font-medium text-slate-900 truncate">
                          {doc.title || doc.originalName}
                        </p>
                        <div className="flex items-center gap-2 mt-1 text-xs text-slate-500">
                          <span>{getCategoryLabel(doc.category)}</span>
                          <span>-</span>
                          <span>
                            {MEDIA_FILE_TYPE_LABELS[doc.mimeType] ||
                              doc.mimeType}
                          </span>
                          {docAny.duration && (
                            <>
                              <span>-</span>
                              <span>{formatDuration(docAny.duration)}</span>
                            </>
                          )}
                          <span>-</span>
                          <span>{(doc.fileSize / 1024).toFixed(1)} KB</span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <StatusBadge status={doc.status} />
                      <button
                        onClick={() => handleDeleteDocument(doc.id)}
                        className="rounded-lg p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                        title={isAr ? "حذف" : "Delete"}
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* All / Documents Tab - List view with media type badge */}
      {(activeTab === "all" || activeTab === "documents") && (
        <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
          {filteredDocuments.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-slate-100 mb-4">
                <FileText className="h-8 w-8 text-slate-400" />
              </div>
              <h3 className="text-lg font-semibold text-slate-900">
                {activeTab === "all"
                  ? isAr
                    ? "لا توجد ملفات"
                    : "No Files"
                  : isAr
                    ? "لا توجد مستندات"
                    : "No Documents"}
              </h3>
              <p className="mt-1 text-sm text-slate-500 max-w-sm">
                {isAr
                  ? "ارفع مستنداتك لتدريب الذكاء الاصطناعي على معلومات عملك"
                  : "Upload your documents to train AI on your business information"}
              </p>
              <button
                onClick={() => setShowUploadModal(true)}
                className="mt-4 inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
              >
                <Upload className="h-4 w-4" />
                {isAr ? "رفع أول مستند" : "Upload First Document"}
              </button>
            </div>
          ) : (
            <div className="divide-y divide-slate-100">
              {filteredDocuments.map((doc) => {
                const mt = getDocMediaType(doc);
                const MediaTypeIcon = getMediaIcon(mt);
                const iconColor = getMediaIconColor(mt);
                const mtLabel = MEDIA_TYPE_LABELS[mt];

                return (
                  <div
                    key={doc.id}
                    className="flex items-center justify-between p-4 hover:bg-slate-50 transition-colors"
                  >
                    <div className="flex items-center gap-4 min-w-0">
                      <div
                        className={`flex h-12 w-12 items-center justify-center rounded-lg flex-shrink-0 ${iconColor}`}
                      >
                        <MediaTypeIcon className="h-6 w-6" />
                      </div>
                      <div className="min-w-0">
                        <p className="font-medium text-slate-900 truncate">
                          {doc.title || doc.originalName}
                        </p>
                        <div className="flex items-center gap-2 mt-1 text-xs text-slate-500">
                          {activeTab === "all" && (
                            <>
                              <span className="inline-flex items-center rounded-full bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-600 uppercase">
                                {isAr ? mtLabel.ar : mtLabel.en}
                              </span>
                              <span>-</span>
                            </>
                          )}
                          <span>{getCategoryLabel(doc.category)}</span>
                          <span>-</span>
                          <span>
                            {MEDIA_FILE_TYPE_LABELS[doc.mimeType] ||
                              FILE_TYPE_LABELS[doc.mimeType] ||
                              doc.mimeType}
                          </span>
                          <span>-</span>
                          <span>{(doc.fileSize / 1024).toFixed(1)} KB</span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <StatusBadge status={doc.status} />
                      <button
                        onClick={() => handleDeleteDocument(doc.id)}
                        className="rounded-lg p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                        title={isAr ? "حذف" : "Delete"}
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* FAQs Tab */}
      {activeTab === "faqs" && (
        <div className="space-y-6">
        <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
          {filteredFAQs.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-slate-100 mb-4">
                <MessageSquareText className="h-8 w-8 text-slate-400" />
              </div>
              <h3 className="text-lg font-semibold text-slate-900">
                {isAr ? "لا توجد أسئلة شائعة" : "No FAQs"}
              </h3>
              <p className="mt-1 text-sm text-slate-500 max-w-sm">
                {isAr
                  ? "أضف أسئلة وأجوبة شائعة لتساعد الذكاء الاصطناعي في الرد على استفسارات العملاء"
                  : "Add common questions and answers to help AI respond to customer inquiries"}
              </p>
              <button
                onClick={() => setShowFAQModal(true)}
                className="mt-4 inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
              >
                <Plus className="h-4 w-4" />
                {isAr ? "إضافة أول سؤال" : "Add First FAQ"}
              </button>
            </div>
          ) : (
            <div className="divide-y divide-slate-100">
              {filteredFAQs.map((faq) => (
                <div
                  key={faq.id}
                  className="p-4 hover:bg-slate-50 transition-colors"
                >
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-slate-900">
                        {isAr && faq.questionAr
                          ? faq.questionAr
                          : faq.questionEn}
                      </p>
                      <p className="mt-1 text-sm text-slate-600 line-clamp-2">
                        {isAr && faq.answerAr ? faq.answerAr : faq.answerEn}
                      </p>
                      <div className="flex items-center gap-2 mt-2">
                        <span className="inline-flex items-center rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600">
                          {getCategoryLabel(faq.category)}
                        </span>
                        {!faq.isActive && (
                          <span className="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-600">
                            {isAr ? "غير نشط" : "Inactive"}
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <button
                        onClick={() => {
                          setEditingFAQ(faq);
                          setShowFAQModal(true);
                        }}
                        className="rounded-lg p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                        title={isAr ? "تعديل" : "Edit"}
                      >
                        <Edit3 className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleDeleteFAQ(faq.id)}
                        className="rounded-lg p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                        title={isAr ? "حذف" : "Delete"}
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

          {/* Sector picker — set the org's industry so the AI engine
              uses sector-specific vocabulary + workflows */}
          {organizationId && <SectorPickerForm lang={lang} />}

          {/* WhatsApp greeting customization (custom welcome message + opt-out) */}
          {organizationId && (
            <WhatsAppGreetingForm
              organizationId={organizationId}
              lang={lang}
            />
          )}

          {/* AI-Suggested FAQs (from unanswered customer questions) */}
          {organizationId && (
            <SuggestedFAQs organizationId={organizationId} lang={lang} />
          )}
        </div>
      )}

      {/* Knowledge Base Chat - Test RAG */}
      <div className="mt-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-slate-900 flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-brand-green" />
            {isAr ? "اختبار قاعدة المعرفة" : "Test Knowledge Base"}
          </h3>
          <button
            onClick={() => setShowQueryPanel(!showQueryPanel)}
            className="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <MessageSquareText className="h-4 w-4" />
            {showQueryPanel
              ? isAr
                ? "إخفاء"
                : "Hide Chat"
              : isAr
                ? "فتح المحادثة"
                : "Open Chat"}
          </button>
        </div>
        {showQueryPanel && <KnowledgeBaseQueryPanel lang={lang} />}
      </div>

      {/* Modals */}
      <KnowledgeBaseOnboardingModal
        isOpen={showOnboarding}
        onClose={() => {
          if (typeof window !== "undefined") localStorage.setItem("kb-onboarding-dismissed", "true");
          setShowOnboarding(false);
        }}
        onComplete={handleCompleteOnboarding}
        lang={lang}
      />

      <MediaUploadModal
        isOpen={showUploadModal}
        onClose={() => setShowUploadModal(false)}
        onSuccess={() => {
          setShowUploadModal(false);
          loadData(true);
        }}
        lang={lang}
      />

      <FAQEditorModal
        isOpen={showFAQModal}
        onClose={() => {
          setShowFAQModal(false);
          setEditingFAQ(null);
        }}
        onSuccess={() => {
          setShowFAQModal(false);
          setEditingFAQ(null);
          loadData(true);
        }}
        lang={lang}
        csrfToken={csrfToken}
        faq={editingFAQ}
      />
    </div>
  );
}
