'use client'

import { useState, useEffect, useMemo } from 'react'
import { ShieldCheck, Key, Lock, User, X, Star } from '@phosphor-icons/react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogFooter,
  DialogTitle,
  DialogClose,
} from '@/components/ui/dialog'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { useAuth } from '@/lib/api-docs/auth'
import type { BrainfishRESTAuth } from '@/lib/api-docs/types'
import { cn } from '@/lib/utils'

const BASE_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 GlobalAuthModalProps {
  open: boolean
  onClose: () => void
}

export function GlobalAuthModal({ open, onClose }: GlobalAuthModalProps) {
  const { globalAuth, setGlobalAuth, clearAuth, specSchemes, specDefaultAuth } = useAuth()
  
  // Local state for editing
  const [authType, setAuthType] = useState<string>('none')
  const [basicUsername, setBasicUsername] = useState('')
  const [basicPassword, setBasicPassword] = useState('')
  const [bearerToken, setBearerToken] = useState('')
  const [apiKeyName, setApiKeyName] = useState('X-API-Key')
  const [apiKeyValue, setApiKeyValue] = useState('')
  const [apiKeyLocation, setApiKeyLocation] = useState<'HEADERS' | 'QUERY_PARAMS'>('HEADERS')
  const [showPassword, setShowPassword] = useState(false)

  // Build auth types with spec-recommended first
  const AUTH_TYPES = useMemo(() => {
    // If we have a spec default auth, put it first with a recommended label
    if (specDefaultAuth && specDefaultAuth.authType !== 'none') {
      const specType = specDefaultAuth.authType
      const baseType = BASE_AUTH_TYPES.find(t => t.value === specType)
      
      if (baseType) {
        // Get scheme info but use short label
        const scheme = specSchemes.find(s => s.type === specType)
        const label = `${baseType.label} (Recommended)`
        const description = scheme?.description
        
        return [
          { ...baseType, label, isRecommended: true, description },
          ...BASE_AUTH_TYPES.filter(t => t.value !== specType).map(t => ({ ...t, isRecommended: false, description: undefined })),
        ]
      }
    }
    return BASE_AUTH_TYPES.map(t => ({ ...t, isRecommended: false, description: undefined }))
  }, [specDefaultAuth, specSchemes])

  // Sync local state with global auth when modal opens
  useEffect(() => {
    if (open && globalAuth) {
      setAuthType(globalAuth.authType)
      
      if (globalAuth.authType === 'basic') {
        setBasicUsername(globalAuth.username)
        setBasicPassword(globalAuth.password)
      } else if (globalAuth.authType === 'bearer') {
        setBearerToken(globalAuth.token)
      } else if (globalAuth.authType === 'api-key') {
        setApiKeyName(globalAuth.key)
        setApiKeyValue(globalAuth.value)
        setApiKeyLocation(globalAuth.addTo)
      }
    } else if (open) {
      // If no global auth set, use spec default as the initial type
      if (specDefaultAuth && specDefaultAuth.authType !== 'none') {
        setAuthType(specDefaultAuth.authType)
        
        // Pre-populate fields from spec (like API key name)
        if (specDefaultAuth.authType === 'api-key') {
          setApiKeyName(specDefaultAuth.key || 'X-API-Key')
          setApiKeyLocation(specDefaultAuth.addTo || 'HEADERS')
          setApiKeyValue('') // User needs to enter value
        }
      } else {
        setAuthType('none')
      }
      setBasicUsername('')
      setBasicPassword('')
      setBearerToken('')
      if (!specDefaultAuth || specDefaultAuth.authType !== 'api-key') {
        setApiKeyName('X-API-Key')
        setApiKeyValue('')
        setApiKeyLocation('HEADERS')
      }
    }
  }, [open, globalAuth, specDefaultAuth])

  const handleSave = () => {
    let auth: BrainfishRESTAuth

    switch (authType) {
      case 'basic':
        auth = {
          authType: 'basic',
          authActive: true,
          username: basicUsername.trim(),
          password: basicPassword,
        }
        break
      case 'bearer':
        auth = {
          authType: 'bearer',
          authActive: true,
          token: bearerToken.trim(),
        }
        break
      case 'api-key':
        auth = {
          authType: 'api-key',
          authActive: true,
          addTo: apiKeyLocation,
          key: apiKeyName.trim(),
          value: apiKeyValue.trim(),
        }
        break
      default:
        auth = { authType: 'none', authActive: true }
    }

    setGlobalAuth(auth)
    onClose()
  }

  const handleClear = () => {
    clearAuth()
    setAuthType('none')
    setBasicUsername('')
    setBasicPassword('')
    setBearerToken('')
    setApiKeyName('X-API-Key')
    setApiKeyValue('')
    onClose()
  }

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

  return (
    <Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Global Authentication</DialogTitle>
          <DialogClose className="text-muted-foreground hover:text-foreground transition-colors p-1 hover:bg-muted rounded">
            <X className="h-4 w-4" />
          </DialogClose>
        </DialogHeader>

        {/* Content */}
        <div className="p-5 space-y-4">
          {/* Auth Type Selector */}
          <div className="space-y-1.5">
            <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Type</label>
            <Select value={authType} onValueChange={setAuthType}>
              <SelectTrigger className="w-full h-9">
                <SelectValue>
                  <span className="flex items-center gap-2">
                    <CurrentIcon className="h-3.5 w-3.5" weight="bold" />
                    <span className="text-sm truncate">{currentType.label}</span>
                    {currentType.isRecommended && (
                      <Star className="h-3 w-3 text-amber-500 flex-shrink-0" weight="fill" />
                    )}
                  </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>
                      {type.isRecommended && (
                        <Star className="h-3 w-3 text-amber-500 ml-1" weight="fill" />
                      )}
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {currentType.description && (
              <p className="text-xs text-muted-foreground mt-1.5 line-clamp-2">
                {currentType.description.split('\n')[0]}
              </p>
            )}
          </div>

          {/* Auth Type Specific Fields */}
          {authType === 'none' && (
            <div className="flex items-center justify-center py-8 text-center">
              <p className="text-sm text-muted-foreground">
                No authentication will be applied
              </p>
            </div>
          )}

          {authType === 'basic' && (
            <div className="space-y-3">
              <div className="space-y-1.5">
                <label className="text-xs font-medium text-muted-foreground">Username</label>
                <Input
                  type="text"
                  value={basicUsername}
                  onChange={(e) => setBasicUsername(e.target.value)}
                  placeholder="Enter username"
                  className="h-9"
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-xs font-medium text-muted-foreground">Password</label>
                <div className="relative">
                  <Input
                    type={showPassword ? 'text' : 'password'}
                    value={basicPassword}
                    onChange={(e) => setBasicPassword(e.target.value)}
                    placeholder="Enter password"
                    className="h-9 pr-14"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground text-xs px-1.5 py-0.5 rounded hover:bg-muted"
                  >
                    {showPassword ? 'Hide' : 'Show'}
                  </button>
                </div>
              </div>
            </div>
          )}

          {authType === 'bearer' && (
            <div className="space-y-1.5">
              <label className="text-xs font-medium text-muted-foreground">Token</label>
              <textarea
                value={bearerToken}
                onChange={(e) => setBearerToken(e.target.value)}
                placeholder="Paste your bearer token..."
                className="w-full min-h-[80px] px-3 py-2 rounded-md border border-input bg-background font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-ring placeholder:text-muted-foreground/50"
              />
            </div>
          )}

          {authType === 'api-key' && (
            <div className="space-y-3">
              {/* Location toggle */}
              <div className="space-y-1.5">
                <label className="text-xs font-medium text-muted-foreground">Add to</label>
                <div className="flex p-0.5 bg-muted rounded-md">
                  <button
                    type="button"
                    onClick={() => setApiKeyLocation('HEADERS')}
                    className={cn(
                      'flex-1 px-3 py-1 rounded text-xs font-medium transition-all',
                      apiKeyLocation === 'HEADERS'
                        ? 'bg-background text-foreground shadow-sm'
                        : 'text-muted-foreground hover:text-foreground'
                    )}
                  >
                    Header
                  </button>
                  <button
                    type="button"
                    onClick={() => setApiKeyLocation('QUERY_PARAMS')}
                    className={cn(
                      'flex-1 px-3 py-1 rounded text-xs font-medium transition-all',
                      apiKeyLocation === 'QUERY_PARAMS'
                        ? 'bg-background text-foreground shadow-sm'
                        : 'text-muted-foreground hover:text-foreground'
                    )}
                  >
                    Query
                  </button>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-xs font-medium text-muted-foreground">Key Name</label>
                <Input
                  type="text"
                  value={apiKeyName}
                  onChange={(e) => setApiKeyName(e.target.value)}
                  placeholder="X-API-Key"
                  className="font-mono h-9"
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-xs font-medium text-muted-foreground">Key Value</label>
                <div className="relative">
                  <Input
                    type={showPassword ? 'text' : 'password'}
                    value={apiKeyValue}
                    onChange={(e) => setApiKeyValue(e.target.value)}
                    placeholder="Enter API key"
                    className="font-mono h-9 pr-14"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground text-xs px-1.5 py-0.5 rounded hover:bg-muted"
                  >
                    {showPassword ? 'Hide' : 'Show'}
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <button
            onClick={handleClear}
            className="text-xs text-muted-foreground hover:text-destructive transition-colors"
          >
            Clear
          </button>
          <div className="flex gap-2">
            <Button variant="ghost" size="sm" onClick={onClose} className="h-8 px-3 text-xs">
              Cancel
            </Button>
            <Button size="sm" onClick={handleSave} className="h-8 px-4 text-xs">
              Apply
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
