'use client'

import { useEffect, useState, useRef } from 'react'
import { type SearchButtonProps } from '@chainlink/cl-search-frontend'
import '@chainlink/cl-search-frontend/dist/index.css'
import { cn } from '../../utils/cn'

export const transparentTriggerStyles = cn(
  '!bg-foreground/[0.03]',
  'md:!border-solid md:!border-border md:!border-transparent',
  'md:hover:!border-border-hover md:hover:!bg-foreground/[0.03]',
  '[&_button#blocks-algolia-search-trigger[data-slot=algolia-search]]:md:focus-visible:!border-border-active',
  '[&_button#blocks-algolia-search-trigger[data-slot=algolia-search]]:md:focus-visible:!shadow-none',
  '[&_button#blocks-algolia-search-trigger[data-slot=algolia-search]]:md:focus-visible:!outline-none',
  '[&_[class*=searchButtonBorder]]:focus-visible:!shadow-none',
  '[&_[class*=searchButtonBorder]]:focus-visible:!border-border-active',
  '[&_svg]:max-md:!size-5',
  'items-center justify-center max-md:!p-1',
)

const algoliaVars = {
  algoliaEnabled: process.env.NEXT_PUBLIC_AI_SEARCH_ENABLED || 'true',
  algoliaAppId: process.env.NEXT_PUBLIC_AI_SEARCH_APP_ID || '',
  algoliaPublicApiKey: process.env.NEXT_PUBLIC_AI_SEARCH_API_KEY || '',
  algoliaBaseApiUrl: process.env.NEXT_PUBLIC_AI_SEARCH_BASE_API_URL || '',
}

export type AlgoliaSearchProps = Partial<SearchButtonProps> & {
  /**
   * Custom className for styling the search button
   */
  className?: string
}

/**
 * AlgoliaSearch component that provides search functionality.
 *
 * This component lazy loads the search functionality to avoid SSR issues
 * and provides a framework-agnostic way to integrate Algolia search.
 *
 * @example
 * ```tsx
 * <AlgoliaSearch
 *   className="w-full"
 *   enableSearch={true}
 *   algoliaAppId="your-app-id"
 *   algoliaPublicApiKey="your-api-key"
 * />
 * ```
 */
export const AlgoliaSearch = ({
  algoliaAppId = algoliaVars.algoliaAppId,
  algoliaPublicApiKey = algoliaVars.algoliaPublicApiKey,
  baseApiUrl = algoliaVars.algoliaBaseApiUrl,
  enableSearch = true,
  className,
  ...props
}: AlgoliaSearchProps) => {
  const [isLoaded, setIsLoaded] = useState(false)
  const [SearchComponent, setSearchComponent] =
    useState<React.ComponentType<SearchButtonProps> | null>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    // Only load on client side
    if (typeof window === 'undefined') return

    const loadSearchButton = async () => {
      try {
        const searchModule = await import('@chainlink/cl-search-frontend')
        setSearchComponent(() => searchModule.SearchButton)
        setIsLoaded(true)
      } catch (error) {
        console.error('Failed to load search component:', error)
      }
    }

    void loadSearchButton()
  }, [])

  // Don't render anything on server side
  if (typeof window === 'undefined' || !isLoaded || !SearchComponent) {
    return null
  }

  return (
    <div ref={containerRef}>
      <SearchComponent
        data-slot="algolia-search"
        {...props}
        className={cn(
          transparentTriggerStyles,
          '![&_svg]:min-h-4 ![&_svg]:min-w-4 m-0 !mr-0 !h-8 !max-h-8 !min-h-8 !w-8 !min-w-8 !max-w-8 !rounded !p-2 !text-ghost-foreground md:!m-0 md:!max-h-none md:!min-h-10 md:!w-auto md:!max-w-none',
          className,
        )}
        algoliaAppId={algoliaAppId}
        algoliaPublicApiKey={algoliaPublicApiKey}
        baseApiUrl={baseApiUrl}
        enableSearch={enableSearch}
      />
    </div>
  )
}
