/**
 * @fileoverview Basic usage example for the RAG Chatbot Library
 */

"use client";

import React, { useState } from "react";
import {
  ChatbotProvider,
  ChatbotWidget,
  useChatbot,
  useErrorHandler,
} from "../index";

/**
 * Basic chatbot setup example
 */
export function BasicChatbotExample() {
  const config = {
    llm: {
      provider: "openai" as const,
      model: "gpt-3.5-turbo",
      apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY || "",
      maxTokens: 1000,
      temperature: 0.7,
    },
    vectorStore: {
      provider: "memory" as const,
      dimensions: 1536,
    },
    storage: {
      provider: "local" as const,
    },
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <ChatbotProvider config={config}>
        <div className="container mx-auto p-8">
          <h1 className="text-3xl font-bold mb-8">Basic Chatbot Example</h1>
          <p className="text-gray-600 mb-8">
            This example shows the most basic setup of the RAG chatbot.
          </p>

          {/* The chatbot widget will appear as a floating button */}
          <ChatbotWidget
            position="bottom-right"
            showSuggestedQuestions={true}
            placeholder="Ask me anything..."
          />
        </div>
      </ChatbotProvider>
    </div>
  );
}

/**
 * Custom chat interface example
 */
export function CustomChatInterface() {
  const { isInitialized, sendMessage, currentConversation, isProcessing } =
    useChatbot();

  const { error, hasError, clearError } = useErrorHandler();
  const [inputValue, setInputValue] = useState("");

  const handleSendMessage = async () => {
    if (!inputValue.trim() || isProcessing) return;

    try {
      await sendMessage(inputValue);
      setInputValue("");
    } catch (err) {
      console.error("Failed to send message:", err);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  if (!isInitialized) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-4"></div>
          <p>Initializing chatbot...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto">
      <div className="bg-white rounded-lg shadow-lg overflow-hidden">
        {/* Chat Header */}
        <div className="bg-blue-600 text-white p-4">
          <h2 className="text-xl font-semibold">AI Assistant</h2>
          <p className="text-blue-100 text-sm">
            Ask questions about uploaded documents
          </p>
        </div>

        {/* Error Display */}
        {hasError && (
          <div className="bg-red-50 border-l-4 border-red-400 p-4">
            <div className="flex">
              <div className="flex-shrink-0">
                <svg
                  className="h-5 w-5 text-red-400"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fillRule="evenodd"
                    d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                    clipRule="evenodd"
                  />
                </svg>
              </div>
              <div className="ml-3">
                <p className="text-sm text-red-700">{error?.message}</p>
                <button
                  onClick={clearError}
                  className="mt-2 text-sm text-red-600 hover:text-red-500"
                >
                  Dismiss
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Messages */}
        <div className="h-96 overflow-y-auto p-4 space-y-4">
          {currentConversation?.messages.map((message) => (
            <div
              key={message.id}
              className={`flex ${
                message.role === "user" ? "justify-end" : "justify-start"
              }`}
            >
              <div
                className={`max-w-xs lg:max-w-md px-4 py-2 rounded-lg ${
                  message.role === "user"
                    ? "bg-blue-600 text-white"
                    : "bg-gray-100 text-gray-900"
                }`}
              >
                <p className="text-sm">{message.content}</p>
                <p className="text-xs mt-1 opacity-70">
                  {message.timestamp.toLocaleTimeString()}
                </p>
              </div>
            </div>
          ))}

          {isProcessing && (
            <div className="flex justify-start">
              <div className="bg-gray-100 text-gray-900 max-w-xs lg:max-w-md px-4 py-2 rounded-lg">
                <div className="flex items-center space-x-2">
                  <div className="animate-pulse flex space-x-1">
                    <div className="w-2 h-2 bg-gray-400 rounded-full"></div>
                    <div className="w-2 h-2 bg-gray-400 rounded-full"></div>
                    <div className="w-2 h-2 bg-gray-400 rounded-full"></div>
                  </div>
                  <span className="text-sm">AI is thinking...</span>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Input */}
        <div className="border-t p-4">
          <div className="flex space-x-2">
            <input
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="Type your message..."
              className="flex-1 border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              disabled={isProcessing}
            />
            <button
              onClick={handleSendMessage}
              disabled={isProcessing || !inputValue.trim()}
              className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Send
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * Full featured example with document management
 */
export function FullFeaturedExample() {
  return (
    <ChatbotProvider>
      <div className="min-h-screen bg-gray-50">
        <div className="container mx-auto p-8">
          <h1 className="text-3xl font-bold mb-8">Full Featured Chatbot</h1>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Document Management Panel */}
            <div className="lg:col-span-1">
              <DocumentManagementPanel />
            </div>

            {/* Chat Interface */}
            <div className="lg:col-span-2">
              <CustomChatInterface />
            </div>
          </div>
        </div>
      </div>
    </ChatbotProvider>
  );
}

/**
 * Document management panel component
 */
function DocumentManagementPanel() {
  const { uploadDocument, documents } = useChatbot();
  const [isUploading, setIsUploading] = useState(false);

  const handleFileUpload = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setIsUploading(true);
    try {
      await uploadDocument(file, {
        title: file.name,
        uploadedAt: new Date(),
      });
    } catch (error) {
      console.error("Upload failed:", error);
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div className="bg-white rounded-lg shadow-lg p-6">
      <h2 className="text-xl font-semibold mb-4">Knowledge Base</h2>

      {/* Upload Section */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Upload Document
        </label>
        <input
          type="file"
          onChange={handleFileUpload}
          accept=".pdf,.doc,.docx,.txt"
          className="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
          disabled={isUploading}
        />
        {isUploading && (
          <p className="text-sm text-blue-600 mt-2">Uploading...</p>
        )}
      </div>

      {/* Documents List */}
      <div>
        <h3 className="text-lg font-medium mb-3">
          Documents ({documents.length})
        </h3>
        <div className="space-y-2 max-h-64 overflow-y-auto">
          {documents.map((doc) => (
            <div
              key={doc.id}
              className="p-3 border border-gray-200 rounded-lg hover:bg-gray-50"
            >
              <p className="text-sm font-medium text-gray-900">
                {doc.metadata.title || doc.metadata.filename}
              </p>
              <p className="text-xs text-gray-500">
                {doc.metadata.fileType} • {doc.metadata.fileSize} bytes
              </p>
              <p className="text-xs text-gray-400">
                {doc.metadata.uploadedAt?.toLocaleDateString()}
              </p>
            </div>
          ))}

          {documents.length === 0 && (
            <p className="text-sm text-gray-500 text-center py-8">
              No documents uploaded yet
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
