'use client'

import { useState, useEffect } from 'react'
import type { BrainfishRESTReqBody, BrainfishRESTAuth } from '@/lib/api-docs/types'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'
// import { Button } from '@/components/ui/button'
import { ShieldCheck, Link as LinkIcon, WarningCircle } from '@phosphor-icons/react'
import { KeyValueEditor, KeyValueItem } from './key-value-editor'
import { BodyEditor } from './body-editor'
import { AuthEditor } from './auth-editor'
import { getAuthTypeLabel } from '@/lib/api-docs/auth'
import { usePlaygroundNavigation, type PlaygroundTab } from '@/lib/api-docs/playground/navigation-context'
import { cn } from '@/lib/utils'

interface RequestTabsProps {
  params: KeyValueItem[]
  headers: KeyValueItem[]
  body: string | null
  bodyContentType: BrainfishRESTReqBody['contentType']
  auth: BrainfishRESTAuth
  usingGlobalAuth?: boolean
  globalAuth?: BrainfishRESTAuth | null
  onParamsChange: (params: KeyValueItem[]) => void
  onHeadersChange: (headers: KeyValueItem[]) => void
  onBodyChange: (body: string | null) => void
  onBodyContentTypeChange: (contentType: BrainfishRESTReqBody['contentType']) => void
  onAuthChange: (auth: BrainfishRESTAuth) => void
  onUseGlobalAuth?: () => void
}

export function RequestTabs({
  params,
  headers,
  body,
  bodyContentType,
  auth,
  usingGlobalAuth = false,
  globalAuth,
  onParamsChange,
  onHeadersChange,
  onBodyChange,
  onBodyContentTypeChange,
  onAuthChange,
  onUseGlobalAuth,
}: RequestTabsProps) {
  const paramsCount = params.filter((p) => p.active && p.key).length
  const headersCount = headers.filter((h) => h.active && h.key).length
  const hasBody = body !== null && body.length > 0
  const hasAuth = auth.authType !== 'none'

  // Always default to Parameters tab for consistency
  const [activeTab, setActiveTab] = useState<PlaygroundTab>('params')
  
  // Get navigation context
  const { state: navState, setActiveTab: syncActiveTab, clearHighlight } = usePlaygroundNavigation()
  
  // Sync with navigation context
  useEffect(() => {
    if (navState.activeTab && navState.activeTab !== activeTab) {
      setActiveTab(navState.activeTab)
    }
  }, [navState.activeTab, activeTab])
  
  // Update context when tab changes locally
  const handleTabChange = (tab: string) => {
    setActiveTab(tab as PlaygroundTab)
    syncActiveTab(tab as PlaygroundTab)
    clearHighlight()
  }
  
  // Check if a tab should show error indicator
  const shouldShowTabError = (tab: PlaygroundTab) => {
    if (!navState.showError || !navState.highlightField) return false
    
    switch (tab) {
      case 'params':
        return navState.highlightField.type === 'param'
      case 'headers':
        return navState.highlightField.type === 'header'
      case 'body':
        return navState.highlightField.type === 'body'
      case 'auth':
        return navState.highlightField.type === 'auth'
      default:
        return false
    }
  }

  return (
    <Tabs value={activeTab} onValueChange={handleTabChange} className="flex flex-col h-full gap-0">
      <TabsList className="w-full justify-start rounded-none border-b bg-muted/30 h-auto p-0 overflow-x-auto overflow-y-hidden flex-shrink-0">
        <TabsTrigger
          value="params"
          className={cn(
            "rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-background px-2 sm:px-4 py-2 sm:py-3 text-xs sm:text-sm whitespace-nowrap",
            shouldShowTabError('params') && "border-red-500 data-[state=active]:border-red-500"
          )}
        >
          <span className="hidden sm:inline">Parameters</span>
          <span className="sm:hidden">Params</span>
          {shouldShowTabError('params') ? (
            <WarningCircle className="ml-1 sm:ml-2 h-4 w-4 text-red-500 animate-pulse" weight="fill" />
          ) : paramsCount > 0 ? (
            <Badge variant="secondary" className="ml-1 sm:ml-2 h-4 sm:h-5 px-1 sm:px-1.5 text-xs">
              {paramsCount}
            </Badge>
          ) : null}
        </TabsTrigger>
        <TabsTrigger
          value="body"
          className={cn(
            "rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-background px-2 sm:px-4 py-2 sm:py-3 text-xs sm:text-sm whitespace-nowrap",
            shouldShowTabError('body') && "border-red-500 data-[state=active]:border-red-500"
          )}
        >
          Body
          {shouldShowTabError('body') ? (
            <WarningCircle className="ml-1 sm:ml-2 h-4 w-4 text-red-500 animate-pulse" weight="fill" />
          ) : hasBody ? (
            <span className="ml-1 sm:ml-2 w-2 h-2 bg-primary rounded-full" />
          ) : null}
        </TabsTrigger>
        <TabsTrigger
          value="headers"
          className={cn(
            "rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-background px-2 sm:px-4 py-2 sm:py-3 text-xs sm:text-sm whitespace-nowrap",
            shouldShowTabError('headers') && "border-red-500 data-[state=active]:border-red-500"
          )}
        >
          Headers
          {shouldShowTabError('headers') ? (
            <WarningCircle className="ml-1 sm:ml-2 h-4 w-4 text-red-500 animate-pulse" weight="fill" />
          ) : headersCount > 0 ? (
            <Badge variant="secondary" className="ml-1 sm:ml-2 h-4 sm:h-5 px-1 sm:px-1.5 text-xs">
              {headersCount}
            </Badge>
          ) : null}
        </TabsTrigger>
        <TabsTrigger
          value="auth"
          className={cn(
            "rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-background px-2 sm:px-4 py-2 sm:py-3 text-xs sm:text-sm whitespace-nowrap",
            shouldShowTabError('auth') && "border-red-500 data-[state=active]:border-red-500"
          )}
        >
          <span className="hidden sm:inline">Authorization</span>
          <span className="sm:hidden">Auth</span>
          {shouldShowTabError('auth') ? (
            <WarningCircle className="ml-1 sm:ml-2 h-4 w-4 text-red-500 animate-pulse" weight="fill" />
          ) : usingGlobalAuth ? (
            <LinkIcon className="ml-1 sm:ml-2 h-3.5 w-3.5 text-green-600 dark:text-green-400" weight="bold" />
          ) : hasAuth ? (
            <span className="ml-1 sm:ml-2 w-2 h-2 bg-primary rounded-full" />
          ) : null}
        </TabsTrigger>
      </TabsList>

      <TabsContent value="params" className="flex-1 m-0 overflow-auto">
        <KeyValueEditor
          items={params}
          onChange={onParamsChange}
          title="Query Parameters"
          keyLabel="Name"
          valueLabel="Value"
          showError={navState.highlightField?.type === 'param' && navState.showError}
        />
      </TabsContent>

      <TabsContent value="body" className="flex-1 m-0 overflow-auto">
        <BodyEditor
          body={body}
          contentType={bodyContentType}
          onBodyChange={onBodyChange}
          onContentTypeChange={onBodyContentTypeChange}
          showError={navState.highlightField?.type === 'body' && navState.showError}
        />
      </TabsContent>

      <TabsContent value="headers" className="flex-1 m-0 overflow-auto">
        <KeyValueEditor
          items={headers}
          onChange={onHeadersChange}
          title="Request Headers"
          keyLabel="Name"
          valueLabel="Value"
          showError={navState.highlightField?.type === 'header' && navState.showError}
        />
      </TabsContent>

      <TabsContent value="auth" className="flex-1 m-0 overflow-hidden flex flex-col">
        {/* Subtle Auth Status Bar */}
        {globalAuth && globalAuth.authType !== 'none' && (
          <div className="flex items-center justify-between px-4 py-1.5 bg-muted/40 border-b border-border text-xs">
            {usingGlobalAuth ? (
              <>
                <span className="flex items-center gap-1.5 text-muted-foreground">
                  <LinkIcon className="h-3 w-3 text-green-600 dark:text-green-400" weight="bold" />
                  <span>Global: <span className="text-foreground font-medium">{getAuthTypeLabel(globalAuth)}</span></span>
                </span>
                <button
                  onClick={() => onAuthChange({ ...globalAuth })}
                  className="text-muted-foreground hover:text-foreground transition-colors"
                >
                  Customize
                </button>
              </>
            ) : (
              <>
                <span className="flex items-center gap-1.5 text-muted-foreground">
                  <ShieldCheck className="h-3 w-3" weight="bold" />
                  <span>Custom auth</span>
                </span>
                {onUseGlobalAuth && (
                  <button
                    onClick={onUseGlobalAuth}
                    className="text-muted-foreground hover:text-foreground transition-colors"
                  >
                    Use global
                  </button>
                )}
              </>
            )}
          </div>
        )}
        
        <div className="flex-1 overflow-auto">
          <AuthEditor 
            auth={auth} 
            onChange={onAuthChange} 
            showError={navState.highlightField?.type === 'auth' && navState.showError}
          />
        </div>
      </TabsContent>
    </Tabs>
  )
}
