/**
 * @fileoverview Advanced usage examples for the RAG Chatbot Library
 */

"use client";

import React, { useState, useEffect } from "react";
import {
  ChatbotProvider,
  RAGChat,
  useChatbot,
  useDocuments,
  useTheme,
  useI18n,
  useErrorHandler,
} from "../index";

/**
 * Advanced chatbot with custom configuration
 */
export function AdvancedChatbotExample() {
  const config = {
    llm: {
      provider: "openai" as const,
      model: "gpt-4",
      apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY || "",
      maxTokens: 2000,
      temperature: 0.8,
      systemPrompt:
        "You are a helpful AI assistant with access to a knowledge base. Provide accurate and detailed responses based on the available documents.",
    },
    vectorStore: {
      provider: "supabase" as const,
      url: process.env.NEXT_PUBLIC_SUPABASE_URL || "",
      apiKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "",
      dimensions: 1536,
    },
    storage: {
      provider: "supabase" as const,
      bucket: "chatbot-documents",
    },
  };

  const handleError = (error: any) => {
    console.error("Chatbot Error:", error);
    // Send to error tracking service
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
      <ChatbotProvider config={config} onError={handleError}>
        <div className="container mx-auto p-8">
          <h1 className="text-4xl font-bold text-center mb-12">
            Advanced RAG Chatbot
          </h1>

          <div className="grid grid-cols-1 xl:grid-cols-4 gap-8">
            {/* Settings Panel */}
            <div className="xl:col-span-1">
              <SettingsPanel />
            </div>

            {/* Main Chat Interface */}
            <div className="xl:col-span-2">
              <RAGChat
                showDocumentSearch={true}
                showUpload={true}
                maxHeight="600px"
                className="shadow-2xl"
              />
            </div>

            {/* Analytics Panel */}
            <div className="xl:col-span-1">
              <AnalyticsPanel />
            </div>
          </div>
        </div>
      </ChatbotProvider>
    </div>
  );
}

/**
 * Settings panel for theme and language customization
 */
function SettingsPanel() {
  const { theme, setTheme, toggleMode } = useTheme();
  const { language, setLanguage, t } = useI18n();
  const { clearError } = useErrorHandler();

  return (
    <div className="bg-white rounded-xl shadow-lg p-6 space-y-6">
      <h2 className="text-xl font-semibold">{t("settings.title")}</h2>

      {/* Theme Settings */}
      <div>
        <h3 className="text-lg font-medium mb-3">{t("settings.theme")}</h3>
        <div className="space-y-3">
          <button
            onClick={toggleMode}
            className="w-full text-left p-3 border rounded-lg hover:bg-gray-50"
          >
            <div className="flex items-center justify-between">
              <span>{t("settings.darkMode")}</span>
              <div
                className={`w-12 h-6 rounded-full ${
                  theme.mode === "dark" ? "bg-blue-600" : "bg-gray-300"
                } relative`}
              >
                <div
                  className={`w-5 h-5 bg-white rounded-full absolute top-0.5 transition-transform ${
                    theme.mode === "dark" ? "translate-x-6" : "translate-x-0.5"
                  }`}
                />
              </div>
            </div>
          </button>

          <div>
            <label className="block text-sm font-medium mb-2">
              {t("settings.primaryColor")}
            </label>
            <div className="flex space-x-2">
              {["#007bff", "#28a745", "#dc3545", "#ffc107", "#6f42c1"].map(
                (color) => (
                  <button
                    key={color}
                    onClick={() => setTheme({ primaryColor: color })}
                    className="w-8 h-8 rounded-full border-2 border-gray-300"
                    style={{ backgroundColor: color }}
                  />
                )
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Language Settings */}
      <div>
        <h3 className="text-lg font-medium mb-3">{t("settings.language")}</h3>
        <select
          value={language}
          onChange={(e) => setLanguage(e.target.value as any)}
          className="w-full p-2 border rounded-lg"
        >
          <option value="en">English</option>
          <option value="ko">한국어</option>
          <option value="ja">日本語</option>
          <option value="zh">中文</option>
        </select>
      </div>

      {/* Actions */}
      <div className="space-y-2">
        <button
          onClick={clearError}
          className="w-full bg-gray-100 text-gray-700 py-2 px-4 rounded-lg hover:bg-gray-200"
        >
          {t("settings.clearErrors")}
        </button>
      </div>
    </div>
  );
}

/**
 * Analytics panel showing conversation and document stats
 */
function AnalyticsPanel() {
  const { conversations, documents } = useChatbot();
  const [stats, setStats] = useState({
    totalMessages: 0,
    totalDocuments: documents.length,
    avgResponseTime: 0,
  });

  useEffect(() => {
    const totalMessages = conversations.reduce(
      (acc, conv) => acc + conv.messages.length,
      0
    );
    setStats((prev) => ({
      ...prev,
      totalMessages,
      totalDocuments: documents.length,
    }));
  }, [conversations, documents]);

  return (
    <div className="bg-white rounded-xl shadow-lg p-6 space-y-6">
      <h2 className="text-xl font-semibold">Analytics</h2>

      {/* Stats Cards */}
      <div className="space-y-4">
        <div className="bg-blue-50 p-4 rounded-lg">
          <div className="text-2xl font-bold text-blue-600">
            {conversations.length}
          </div>
          <div className="text-sm text-blue-800">Total Conversations</div>
        </div>

        <div className="bg-green-50 p-4 rounded-lg">
          <div className="text-2xl font-bold text-green-600">
            {stats.totalMessages}
          </div>
          <div className="text-sm text-green-800">Total Messages</div>
        </div>

        <div className="bg-purple-50 p-4 rounded-lg">
          <div className="text-2xl font-bold text-purple-600">
            {stats.totalDocuments}
          </div>
          <div className="text-sm text-purple-800">Documents in KB</div>
        </div>
      </div>

      {/* Recent Activity */}
      <div>
        <h3 className="text-lg font-medium mb-3">Recent Activity</h3>
        <div className="space-y-2 max-h-32 overflow-y-auto">
          {conversations.slice(0, 5).map((conv) => (
            <div key={conv.id} className="text-sm p-2 bg-gray-50 rounded">
              <div className="font-medium truncate">{conv.title}</div>
              <div className="text-gray-500 text-xs">
                {conv.messages.length} messages •{" "}
                {conv.updatedAt.toLocaleDateString()}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/**
 * Custom hook for chatbot analytics
 */
export function useChatbotAnalytics() {
  const { conversations, documents } = useChatbot();
  const [analytics, setAnalytics] = useState({
    conversationCount: 0,
    messageCount: 0,
    documentCount: 0,
    avgMessagesPerConversation: 0,
    mostActiveDay: "",
    topicsDiscussed: [] as string[],
  });

  useEffect(() => {
    const messageCount = conversations.reduce(
      (acc, conv) => acc + conv.messages.length,
      0
    );
    const avgMessages =
      conversations.length > 0 ? messageCount / conversations.length : 0;

    // Analyze conversation topics (simplified)
    const topics = conversations
      .map((conv) => conv.title)
      .filter((title) => title && title !== "New Conversation")
      .slice(0, 5);

    setAnalytics({
      conversationCount: conversations.length,
      messageCount,
      documentCount: documents.length,
      avgMessagesPerConversation: Math.round(avgMessages * 10) / 10,
      mostActiveDay: "Today", // Simplified
      topicsDiscussed: topics,
    });
  }, [conversations, documents]);

  return analytics;
}

/**
 * Example with custom document processing
 */
export function CustomDocumentProcessingExample() {
  const { uploadDocument } = useDocuments();
  const [processing, setProcessing] = useState(false);

  const handleCustomUpload = async (file: File) => {
    setProcessing(true);
    try {
      // Custom preprocessing
      const processedFile = await preprocessDocument(file);

      // Upload with custom metadata
      await uploadDocument(processedFile, {
        title: file.name.replace(/\.[^/.]+$/, ""),
        tags: extractTags(file.name),
        description: `Processed document: ${file.name}`,
        uploadedAt: new Date(),
      });
    } catch (error) {
      console.error("Custom upload failed:", error);
    } finally {
      setProcessing(false);
    }
  };

  return (
    <div className="bg-white rounded-lg p-6">
      <h3 className="text-lg font-semibold mb-4">Custom Document Processing</h3>
      <input
        type="file"
        onChange={(e) =>
          e.target.files?.[0] && handleCustomUpload(e.target.files[0])
        }
        className="mb-4"
        disabled={processing}
      />
      {processing && (
        <div className="text-blue-600">Processing document...</div>
      )}
    </div>
  );
}

// Helper functions
async function preprocessDocument(file: File): Promise<File> {
  // Add custom preprocessing logic here
  return file;
}

function extractTags(filename: string): string[] {
  // Extract tags from filename
  const parts = filename.toLowerCase().split(/[-_\s]/);
  return parts.filter((part) => part.length > 2).slice(0, 3);
}
