'use client'

import { ShieldCheck, Key, Lock, User, Hash, WarningCircle } from '@phosphor-icons/react'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Input } from '@/components/ui/input'
import type { BrainfishRESTAuth } from '@/lib/api-docs/types'
import { cn } from '@/lib/utils'
import { usePlaygroundNavigation } from '@/lib/api-docs/playground/navigation-context'

const AUTH_TYPES = [
  { value: 'none', label: 'No Auth', icon: ShieldCheck },
  { value: 'basic', label: 'Basic Auth', icon: User },
  { value: 'bearer', label: 'Bearer Token', icon: Key },
  { value: 'api-key', label: 'API Key', icon: Lock },
] as const

interface AuthEditorProps {
  auth: BrainfishRESTAuth
  onChange: (auth: BrainfishRESTAuth) => void
  /** Show error styling to indicate this section needs attention */
  showError?: boolean
}

export function AuthEditor({ auth, onChange, showError = false }: AuthEditorProps) {
  const { state: navState } = usePlaygroundNavigation()
  
  // Check if auth field should be highlighted (from either prop or context)
  const isHighlighted = showError || (navState.highlightField?.type === 'auth' && navState.showError)
  const handleTypeChange = (type: string) => {
    switch (type) {
      case 'none':
        onChange({ authType: 'none', authActive: true })
        break
      case 'basic':
        onChange({ authType: 'basic', authActive: true, username: '', password: '' })
        break
      case 'bearer':
        onChange({ authType: 'bearer', authActive: true, token: '' })
        break
      case 'api-key':
        onChange({ authType: 'api-key', authActive: true, addTo: 'HEADERS', key: 'X-API-Key', value: '' })
        break
    }
  }

  const currentType = AUTH_TYPES.find((t) => t.value === auth.authType) || AUTH_TYPES[0]
  const CurrentIcon = currentType.icon

  return (
    <div className="flex flex-col h-full">
      {/* Header with Auth Type Selector */}
      <div className={cn(
        "flex items-center border-b bg-muted/30 px-4 py-2",
        isHighlighted ? "border-red-500 bg-red-500/5" : "border-border"
      )}>
        {isHighlighted && (
          <WarningCircle className="h-4 w-4 text-red-500 animate-pulse mr-2" weight="fill" />
        )}
        <span className={cn(
          "text-xs font-medium mr-3",
          isHighlighted ? "text-red-500" : "text-muted-foreground"
        )}>
          {isHighlighted ? "Auth required" : "Type"}
        </span>
        <Select value={auth.authType} onValueChange={handleTypeChange}>
          <SelectTrigger className="h-8 w-auto min-w-[140px] text-sm border-0 bg-transparent hover:bg-muted/50">
            <SelectValue>
              <span className="flex items-center gap-2">
                <CurrentIcon className="h-3.5 w-3.5" weight="bold" />
                <span>{currentType.label}</span>
              </span>
            </SelectValue>
          </SelectTrigger>
          <SelectContent>
            {AUTH_TYPES.map((type) => (
              <SelectItem key={type.value} value={type.value}>
                <div className="flex items-center gap-2">
                  <type.icon className="h-3.5 w-3.5" weight="bold" />
                  <span>{type.label}</span>
                </div>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Auth Content */}
      <div className="flex-1 overflow-auto">
        {auth.authType === 'none' && (
          <div className={cn(
            "flex flex-col items-center justify-center py-12 px-6 text-center",
            isHighlighted && "bg-red-500/5 border-2 border-red-500/30 rounded-lg m-4 animate-pulse"
          )}>
            {isHighlighted ? (
              <>
                <WarningCircle className="h-10 w-10 text-red-500 mb-3" weight="fill" />
                <p className="text-sm font-medium text-red-600 dark:text-red-400 mb-1">
                  Authentication Required
                </p>
                <p className="text-xs text-muted-foreground">
                  Select an auth type above to configure credentials
                </p>
              </>
            ) : (
              <>
                <ShieldCheck className="h-10 w-10 text-muted-foreground/50 mb-3" weight="duotone" />
                <p className="text-sm text-muted-foreground">
                  No authentication required
                </p>
              </>
            )}
          </div>
        )}

        {auth.authType === 'basic' && (
          <table className="w-full text-sm">
            <thead className="bg-muted/20 text-xs text-muted-foreground">
              <tr>
                <th className="text-left font-medium px-4 py-2 w-32">Field</th>
                <th className="text-left font-medium px-4 py-2">Value</th>
              </tr>
            </thead>
            <tbody>
              <tr className="border-b border-border/50">
                <td className="px-4 py-1">
                  <div className="flex items-center gap-2 text-sm font-medium">
                    <User className="h-3.5 w-3.5 text-muted-foreground" />
                    username
                  </div>
                </td>
                <td className="px-2 py-1">
                  <Input
                    type="text"
                    value={auth.username}
                    onChange={(e) => onChange({ ...auth, username: e.target.value })}
                    placeholder="Enter username..."
                    className="h-9 border-border/50 bg-transparent focus-visible:ring-1 focus-visible:ring-ring"
                  />
                </td>
              </tr>
              <tr className="border-b border-border/50">
                <td className="px-4 py-1">
                  <div className="flex items-center gap-2 text-sm font-medium">
                    <Lock className="h-3.5 w-3.5 text-muted-foreground" />
                    password
                  </div>
                </td>
                <td className="px-2 py-1">
                  <Input
                    type="password"
                    value={auth.password}
                    onChange={(e) => onChange({ ...auth, password: e.target.value })}
                    placeholder="Enter password..."
                    className="h-9 border-border/50 bg-transparent focus-visible:ring-1 focus-visible:ring-ring"
                  />
                </td>
              </tr>
            </tbody>
          </table>
        )}

        {auth.authType === 'bearer' && (
          <table className="w-full text-sm">
            <thead className="bg-muted/20 text-xs text-muted-foreground">
              <tr>
                <th className="text-left font-medium px-4 py-2 w-32">Field</th>
                <th className="text-left font-medium px-4 py-2">Value</th>
              </tr>
            </thead>
            <tbody>
              <tr className="border-b border-border/50">
                <td className="px-4 py-1 align-top pt-3">
                  <div className="flex items-center gap-2 text-sm font-medium">
                    <Key className="h-3.5 w-3.5 text-muted-foreground" />
                    token
                  </div>
                </td>
                <td className="px-2 py-1">
                  <textarea
                    value={auth.token}
                    onChange={(e) => onChange({ ...auth, token: e.target.value })}
                    placeholder="Paste your bearer token..."
                    className="w-full min-h-[80px] px-3 py-2 rounded-md border border-border/50 bg-transparent font-mono text-sm resize-none focus:outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"
                  />
                </td>
              </tr>
            </tbody>
          </table>
        )}

        {auth.authType === 'api-key' && (
          <>
            {/* Location toggle */}
            <div className="flex items-center gap-3 px-4 py-3 border-b border-border/50 bg-muted/10">
              <span className="text-xs text-muted-foreground font-medium">Add to</span>
              <div className="flex p-0.5 bg-muted rounded-sm">
                <button
                  type="button"
                  onClick={() => onChange({ ...auth, addTo: 'HEADERS' })}
                  className={cn(
                    "px-3 py-1 rounded text-xs font-medium transition-all",
                    auth.addTo === 'HEADERS'
                      ? "bg-background text-foreground shadow-sm"
                      : "text-muted-foreground hover:text-foreground"
                  )}
                >
                  Header
                </button>
                <button
                  type="button"
                  onClick={() => onChange({ ...auth, addTo: 'QUERY_PARAMS' })}
                  className={cn(
                    "px-3 py-1 rounded text-xs font-medium transition-all",
                    auth.addTo === 'QUERY_PARAMS'
                      ? "bg-background text-foreground shadow-sm"
                      : "text-muted-foreground hover:text-foreground"
                  )}
                >
                  Query
                </button>
              </div>
            </div>
            
            {/* Key-value inputs */}
            <table className="w-full text-sm">
              <thead className="bg-muted/20 text-xs text-muted-foreground">
                <tr>
                  <th className="text-left font-medium px-4 py-2 w-32">Field</th>
                  <th className="text-left font-medium px-4 py-2">Value</th>
                </tr>
              </thead>
              <tbody>
                <tr className="border-b border-border/50">
                  <td className="px-4 py-1">
                    <div className="flex items-center gap-2 text-sm font-medium">
                      <Hash className="h-3.5 w-3.5 text-muted-foreground" />
                      key
                    </div>
                  </td>
                  <td className="px-2 py-1">
                    <Input
                      type="text"
                      value={auth.key}
                      onChange={(e) => onChange({ ...auth, key: e.target.value })}
                      placeholder="X-API-Key"
                      className="h-9 border-border/50 bg-transparent focus-visible:ring-1 focus-visible:ring-ring font-mono"
                    />
                  </td>
                </tr>
                <tr className="border-b border-border/50">
                  <td className="px-4 py-1">
                    <div className="flex items-center gap-2 text-sm font-medium">
                      <Key className="h-3.5 w-3.5 text-muted-foreground" />
                      value
                    </div>
                  </td>
                  <td className="px-2 py-1">
                    <Input
                      type="password"
                      value={auth.value}
                      onChange={(e) => onChange({ ...auth, value: e.target.value })}
                      placeholder="Enter API key..."
                      className="h-9 border-border/50 bg-transparent focus-visible:ring-1 focus-visible:ring-ring font-mono"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </>
        )}
      </div>
    </div>
  )
}
