"use client";

import { useEffect, useState } from "react";
import { ChatBubbleLeftRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { logger } from "@/core/logger";

/**
 * Agentforce Widget Configuration
 *
 * These values should be set in environment variables:
 * - NEXT_PUBLIC_SF_EMBEDDED_SERVICE_URL: The Salesforce Messaging for Web script URL
 * - NEXT_PUBLIC_SF_EMBEDDED_SERVICE_DEPLOYMENT_ID: The deployment ID
 * - NEXT_PUBLIC_SF_ORG_ID: Your Salesforce org ID
 *
 * To get these values:
 * 1. Go to Salesforce Setup > Messaging > Embedded Service Deployments
 * 2. Create or select a deployment
 * 3. Copy the deployment code snippet
 * 4. Extract the URL and deployment ID
 */

interface AgentforceWidgetProps {
  /**
   * Whether to show the floating chat button
   * If false, the widget will only be triggered programmatically
   */
  showFloatingButton?: boolean;
}

declare global {
  interface Window {
    embeddedservice_bootstrap?: {
      settings: {
        language: string;
      };
      init: (
        orgId: string,
        deploymentName: string,
        baseSiteURL: string,
        options: {
          scrt2URL: string;
        }
      ) => void;
    };
  }
}

export function AgentforceWidget({ showFloatingButton = true }: AgentforceWidgetProps) {
  const [isLoaded, setIsLoaded] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Configuration from environment variables
  const scriptUrl = process.env["NEXT_PUBLIC_SF_EMBEDDED_SERVICE_URL"];
  const orgId = process.env["NEXT_PUBLIC_SF_ORG_ID"];
  const deploymentId = process.env["NEXT_PUBLIC_SF_EMBEDDED_SERVICE_DEPLOYMENT_ID"];
  const baseSiteUrl = process.env["NEXT_PUBLIC_SF_EMBEDDED_SERVICE_SITE_URL"];
  const scrt2Url = process.env["NEXT_PUBLIC_SF_EMBEDDED_SERVICE_SCRT2_URL"];

  useEffect(() => {
    // Skip if not configured
    if (!scriptUrl || !orgId || !deploymentId || !baseSiteUrl || !scrt2Url) {
      setError(
        "Agentforce widget is not configured. Please set the required environment variables."
      );
      return;
    }

    // Skip if already loaded
    if (window.embeddedservice_bootstrap) {
      setIsLoaded(true);
      return;
    }

    // Load the Salesforce Messaging for Web script
    const script = document.createElement("script");
    script.src = scriptUrl;
    script.async = true;
    script.onload = () => {
      try {
        if (window.embeddedservice_bootstrap) {
          window.embeddedservice_bootstrap.settings.language = "en";
          window.embeddedservice_bootstrap.init(orgId, deploymentId, baseSiteUrl, {
            scrt2URL: scrt2Url,
          });
          setIsLoaded(true);
        }
      } catch (err) {
        setError("Failed to initialize Agentforce widget");
        logger.error("Agentforce init error", err);
      }
    };
    script.onerror = () => {
      setError("Failed to load Agentforce widget script");
    };

    document.body.appendChild(script);

    return () => {
      // Cleanup is handled by Salesforce's script
    };
  }, [scriptUrl, orgId, deploymentId, baseSiteUrl, scrt2Url]);

  // If not configured, show nothing or a placeholder
  if (error) {
    // In development, show the error; in production, fail silently
    if (process.env["NODE_ENV"] === "development") {
      return (
        <div className="fixed bottom-4 right-4 max-w-xs bg-yellow-50 border border-yellow-200 rounded-lg p-3 shadow-lg z-50">
          <p className="text-xs text-yellow-700">{error}</p>
        </div>
      );
    }
    return null;
  }

  // Show custom floating button only if the Salesforce widget hasn't loaded
  // Once loaded, Salesforce's native button will appear
  if (!isLoaded && showFloatingButton) {
    return (
      <div className="fixed bottom-4 right-4 z-50">
        <button
          onClick={() => setIsOpen(!isOpen)}
          className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-primary text-primary-foreground shadow-[var(--cp-shadow-3)] hover:bg-primary-hover focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background transition-colors"
          aria-label={isOpen ? "Close chat" : "Open chat"}
        >
          {isOpen ? (
            <XMarkIcon className="h-6 w-6" />
          ) : (
            <ChatBubbleLeftRightIcon className="h-6 w-6" />
          )}
        </button>

        {isOpen && (
          <div className="absolute bottom-16 right-0 w-80 bg-card text-card-foreground rounded-lg shadow-[var(--cp-shadow-3)] border border-border">
            <div className="p-4 border-b border-border bg-primary rounded-t-lg">
              <h3 className="text-lg font-medium text-primary-foreground">AI Assistant</h3>
              <p className="text-sm text-primary-foreground/80">Loading...</p>
            </div>
            <div className="p-4 flex items-center justify-center h-32">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
          </div>
        )}
      </div>
    );
  }

  // Once loaded, Salesforce handles the UI
  return null;
}
