'use client';

/**
 * API Key Widget Component
 *
 * Global API key management widget displayed in navigation bar.
 * Features:
 * - Inline collapsed state (fits in nav rightSlot)
 * - Popup expanded state (absolute positioned dropdown)
 * - API key validation and management
 * - Click outside and Escape key to close
 * - Focus method accessible via useApiKey hook
 *
 * Usage:
 * Must be used within ApiKeyProvider context
 */

import { useEffect, useRef, useState } from 'react';
import { useApiKey } from './apikey-context';

export function ApiKeyWidget() {
  const {
    apiKey,
    apiKeyValidated,
    apiKeyInfo,
    apiKeyError,
    validatingKey,
    ui,
    inputRef,
    containerRef,
    setApiKey,
    validateApiKey,
    revokeApiKey,
    toggleKeyVisibility,
    setExpanded,
  } = useApiKey();

  // const containerRef = useRef<HTMLDivElement>(null);
  // const inputRef = useRef<HTMLInputElement>(null);
  const [isMobileContext, setIsMobileContext] = useState(false);

  // Detect mobile context (inside mobile dropdown menu)
  useEffect(() => {
    const checkContext = () => {
      if (containerRef.current) {
        // Check if ancestor has md:hidden class (mobile menu)
        const mobileMenu = containerRef.current.closest('.md\\:hidden');
        setIsMobileContext(mobileMenu !== null);
      }
    };

    checkContext();
    window.addEventListener('resize', checkContext);
    return () => window.removeEventListener('resize', checkContext);
  }, []);

  // Click outside to close
  useEffect(() => {
    if (!ui.expanded) return;

    function handleClickOutside(event: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setExpanded(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [ui.expanded, setExpanded]);

  // Escape key to close
  useEffect(() => {
    if (!ui.expanded) return;

    function handleEscape(event: KeyboardEvent) {
      if (event.key === 'Escape') {
        setExpanded(false);
      }
    }

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [ui.expanded, setExpanded]);

  // Handle Enter key for validation
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && !validatingKey) {
      validateApiKey();
    }
  };

  return (
    <>
      {/* Backdrop for mobile expanded state */}
      {ui.expanded && isMobileContext && (
        <div
          className="fixed inset-0 bg-black/50 z-40"
          onClick={() => setExpanded(false)}
          aria-label="Close API key details"
        />
      )}

      <div ref={containerRef} className={isMobileContext ? "relative" : "relative h-full flex items-center"}>
        {/* COLLAPSED STATE - Always rendered to maintain layout space */}
        <button
          onClick={() => setExpanded(true)}
          className={`group px-3 bg-transparent backdrop-blur-sm border-none rounded-lg hover:border-purple-500/50 transition-all flex items-center ${
            isMobileContext
              ? 'w-auto max-w-full py-2.5 h-11' // Mobile: auto-width, larger touch target
              : 'py-2 h-10' // Desktop: original size
          } ${
            ui.expanded && isMobileContext ? 'opacity-50 pointer-events-none' : '' // Fade when expanded on mobile
          }`}
          aria-label="Expand API key details"
          disabled={ui.expanded}
        >
          <div className="flex items-center gap-2">
            <div
              className={`w-2 h-2 rounded-full ${apiKeyValidated ? 'bg-green-400' : 'bg-gray-500'}`}
            ></div>
            <span className="text-sm text-gray-300 font-medium whitespace-nowrap">
              {apiKeyValidated && apiKeyInfo
                ? `${apiKeyInfo.organizationSlug} / ${apiKeyInfo.projectSlug}`
                : 'API Key'}
            </span>
            <svg
              className="w-4 h-4 text-gray-400 group-hover:text-purple-400 transition-colors"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M19 9l-7 7-7-7"
              />
            </svg>
          </div>
        </button>

        {/* EXPANDED STATE - Rendered as overlay when expanded */}
        {ui.expanded && (
          <div className={`bg-slate-900/95 backdrop-blur-sm border border-slate-700 rounded-xl shadow-2xl animate-in fade-in duration-200 ${
            isMobileContext
              ? 'fixed inset-x-4 top-16 p-5 z-50 max-h-[calc(100vh-6rem)] overflow-y-auto' // Mobile: fixed positioning for full-width
              : 'absolute top-0 right-0 w-96 p-5 z-50' // Desktop: absolute positioned
          }`}>
          {/* Header */}
          <div className="flex items-start justify-between mb-4">
            <div>
              <h3 className={`font-semibold text-white mb-1 ${isMobileContext ? 'text-base' : 'text-sm'}`}>
                {apiKeyValidated ? 'API Key Active' : 'Enter API Key'}
              </h3>
              {apiKeyValidated && apiKeyInfo && (
                <p className="text-xs text-gray-400">
                  {apiKeyInfo.organizationSlug} / {apiKeyInfo.projectSlug}
                </p>
              )}
            </div>
            <button
              onClick={() => setExpanded(false)}
              className={`rounded-lg bg-slate-800 hover:bg-slate-700 text-gray-400 hover:text-white flex items-center justify-center transition-colors ${
                isMobileContext ? 'w-10 h-10' : 'w-8 h-8'
              }`}
              aria-label="Minimize API key details"
            >
              <svg className={isMobileContext ? 'w-5 h-5' : 'w-4 h-4'} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M5 15l7-7 7 7"
                />
              </svg>
            </button>
          </div>

          {/* API Key Input/Display */}
          <div className="mb-4">
            <label className="text-xs text-gray-500 mb-2 block">API Key</label>
            <div className={`flex gap-2 ${isMobileContext ? 'flex-col' : 'flex-row'}`}>
              <input
                ref={inputRef}
                type={ui.keyVisible ? 'text' : 'password'}
                value={apiKey}
                onChange={(e) => setApiKey(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder="Enter your API key"
                disabled={apiKeyValidated}
                className={`flex-1 px-4 bg-slate-800 border border-slate-700 rounded-lg text-gray-300 font-mono placeholder:text-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all ${
                  isMobileContext ? 'py-3 text-base' : 'py-2 text-sm'
                }`}
              />
              <button
                onClick={toggleKeyVisibility}
                className={`bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-lg text-gray-400 hover:text-white transition-colors ${
                  isMobileContext ? 'px-4 py-3 w-full justify-center flex items-center gap-2' : 'px-3 py-2'
                }`}
                aria-label={ui.keyVisible ? 'Hide API key' : 'Show API key'}
              >
                {ui.keyVisible ? (
                  <>
                    <svg className={isMobileContext ? 'w-5 h-5' : 'w-4 h-4'} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
                      />
                    </svg>
                    {isMobileContext && <span className="text-sm font-medium">Hide</span>}
                  </>
                ) : (
                  <>
                    <svg className={isMobileContext ? 'w-5 h-5' : 'w-4 h-4'} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                      />
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
                      />
                    </svg>
                    {isMobileContext && <span className="text-sm font-medium">Show</span>}
                  </>
                )}
              </button>
            </div>
          </div>

          {/* Error Message */}
          {apiKeyError && (
            <div className={`mb-3 bg-red-900/20 border border-red-700/50 rounded-lg ${isMobileContext ? 'p-3' : 'p-2'}`}>
              <p className="text-xs text-red-400">{apiKeyError}</p>
            </div>
          )}

          {/* Actions */}
          <div className="flex gap-2">
            {!apiKeyValidated ? (
              <button
                onClick={validateApiKey}
                disabled={validatingKey || !apiKey.trim()}
                className={`flex-1 bg-purple-600 hover:bg-purple-700 disabled:bg-slate-700 disabled:text-gray-500 disabled:cursor-not-allowed border border-purple-500 disabled:border-slate-600 rounded-lg text-white font-medium transition-colors ${
                  isMobileContext ? 'px-5 py-3.5 text-base' : 'px-4 py-2 text-sm'
                }`}
              >
                {validatingKey ? (
                  <span className="flex items-center justify-center gap-2">
                    <svg
                      className={isMobileContext ? 'animate-spin h-5 w-5' : 'animate-spin h-4 w-4'}
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      ></circle>
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      ></path>
                    </svg>
                    Validating...
                  </span>
                ) : (
                  'Validate Key'
                )}
              </button>
            ) : (
              <button
                onClick={() => revokeApiKey()}
                className={`flex-1 bg-red-900/20 hover:bg-red-900/30 border border-red-700/50 hover:border-red-600 rounded-lg text-red-400 font-medium transition-colors ${
                  isMobileContext ? 'px-5 py-3.5 text-base' : 'px-4 py-2 text-sm'
                }`}
              >
                Revoke & Use Different Key
              </button>
            )}
          </div>

          {/* Helper Text */}
          {!apiKeyValidated && (
            <p className={`mt-3 text-gray-500 text-center ${isMobileContext ? 'text-sm' : 'text-xs'}`}>
              Press Enter or click Validate to verify your API key
            </p>
          )}
        </div>
      )}
      </div>
    </>
  );
}
