'use client'

import { useState } from 'react'
import { CaretDown, CaretRight, Play } from '@phosphor-icons/react'
import { MethodBadge } from '../shared/method-badge'
import { MarkdownRenderer } from '../shared/markdown-renderer'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { CodeViewer } from '../playground/code-editor'
import { ResponseSchema } from '../shared/schema-viewer'
import { CodeSnippetCompact } from '../playground/code-snippet'
import { useModeContext } from '@/lib/api-docs/code-editor'
import type { BrainfishRESTRequest } from '@/lib/api-docs/types'

interface RequestDetailsProps {
  request: BrainfishRESTRequest
}

// Collapsible section component
function CollapsibleSection({ 
  title, 
  children, 
  defaultOpen = true 
}: { 
  title: string
  children: React.ReactNode
  defaultOpen?: boolean 
}) {
  const [isOpen, setIsOpen] = useState(defaultOpen)

  return (
    <div className="docs-api-section border-b border-border">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="docs-api-section-header w-full flex items-center justify-between p-4 hover:bg-muted/50 transition-colors"
      >
        <span className="font-semibold text-sm">{title}</span>
        {isOpen ? (
          <CaretDown className="h-4 w-4 text-muted-foreground" weight="bold" />
        ) : (
          <CaretRight className="h-4 w-4 text-muted-foreground" weight="bold" />
        )}
      </button>
      {isOpen && <div className="docs-api-section-content px-4 pb-4">{children}</div>}
    </div>
  )
}

export function RequestDetails({ request }: RequestDetailsProps) {
  const { switchToApiClient } = useModeContext()
  
  return (
    <div className="docs-api-endpoint h-full overflow-y-auto bg-background">
      {/* Endpoint Header */}
      <div className="docs-api-endpoint-header p-4 border-b border-border">
        <div className="flex items-center justify-between gap-2 mb-2">
          <div className="flex items-center gap-2 min-w-0">
            <MethodBadge method={request.method} />
            <h2 className="docs-api-endpoint-name font-semibold text-lg truncate">{request.name}</h2>
          </div>
          <Button 
            size="sm" 
            onClick={() => switchToApiClient()}
            className="docs-button docs-button-try-it shrink-0"
          >
            <Play className="h-3.5 w-3.5 mr-1.5" weight="fill" />
            Try it out
          </Button>
        </div>
        <code className="docs-api-path text-xs text-muted-foreground font-mono break-all">
          {request.endpoint}
        </code>
      </div>

      {/* Code Snippet */}
      <CodeSnippetCompact request={request} />

      {/* Description - only show if there's actual content */}
      {request.description?.trim() && (
        <CollapsibleSection title="Description" defaultOpen={true}>
          <div className="text-sm text-muted-foreground">
            <MarkdownRenderer content={request.description} />
          </div>
        </CollapsibleSection>
      )}

      {/* Parameters */}
      {request.params.length > 0 && (
        <CollapsibleSection title="Parameters" defaultOpen={false}>
          <div className="border rounded-sm overflow-x-auto">
            <table className="w-full text-sm min-w-[400px]">
              <thead className="bg-muted/50">
                <tr>
                  <th className="px-3 py-2 text-left text-xs font-semibold whitespace-nowrap">Name</th>
                  <th className="px-3 py-2 text-left text-xs font-semibold whitespace-nowrap">Description</th>
                  <th className="px-3 py-2 text-left text-xs font-semibold whitespace-nowrap">Required</th>
                </tr>
              </thead>
              <tbody>
                {request.params.map((param) => (
                  <tr key={param.key} className="border-t">
                    <td className="px-3 py-2 font-mono text-xs whitespace-nowrap">{param.key}</td>
                    <td className="px-3 py-2 text-xs text-muted-foreground">
                      {param.description || '-'}
                    </td>
                    <td className="px-3 py-2 text-xs whitespace-nowrap">
                      {param.active ? (
                        <Badge variant="default" className="text-xs">Required</Badge>
                      ) : (
                        <span className="text-muted-foreground">Optional</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CollapsibleSection>
      )}

      {/* Headers */}
      {request.headers.length > 0 && (
        <CollapsibleSection title="Headers" defaultOpen={false}>
          <div className="border rounded-sm overflow-x-auto">
            <table className="w-full text-sm min-w-[400px]">
              <thead className="bg-muted/50">
                <tr>
                  <th className="px-3 py-2 text-left text-xs font-semibold whitespace-nowrap">Name</th>
                  <th className="px-3 py-2 text-left text-xs font-semibold whitespace-nowrap">Description</th>
                  <th className="px-3 py-2 text-left text-xs font-semibold whitespace-nowrap">Required</th>
                </tr>
              </thead>
              <tbody>
                {request.headers.map((header) => (
                  <tr key={header.key} className="border-t">
                    <td className="px-3 py-2 font-mono text-xs whitespace-nowrap">{header.key}</td>
                    <td className="px-3 py-2 text-xs text-muted-foreground">
                      {header.description || '-'}
                    </td>
                    <td className="px-3 py-2 text-xs whitespace-nowrap">
                      {header.active ? (
                        <Badge variant="default" className="text-xs">Required</Badge>
                      ) : (
                        <span className="text-muted-foreground">Optional</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CollapsibleSection>
      )}

      {/* Authentication */}
      {request.auth.authType !== 'none' && (
        <CollapsibleSection title="Authentication" defaultOpen={false}>
          <div className="border rounded-sm overflow-hidden">
            {request.auth.authType === 'basic' && (
              <>
                <div className="px-3 py-2 border-b bg-muted/30">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-sm">Basic Auth</span>
                    <span className="text-xs text-orange-500 font-medium">required</span>
                  </div>
                </div>
                <div className="p-3 space-y-2">
                  <div className="flex items-center justify-between py-2 border-b border-border/50">
                    <span className="text-sm font-medium">username</span>
                    <span className="text-xs text-muted-foreground">string</span>
                  </div>
                  <div className="flex items-center justify-between py-2">
                    <span className="text-sm font-medium">password</span>
                    <span className="text-xs text-muted-foreground">string</span>
                  </div>
                </div>
              </>
            )}

            {request.auth.authType === 'bearer' && (
              <>
                <div className="px-3 py-2 border-b bg-muted/30">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-sm">Bearer Token</span>
                    <span className="text-xs text-orange-500 font-medium">required</span>
                  </div>
                </div>
                <div className="p-3">
                  <div className="flex items-center justify-between py-2">
                    <span className="text-sm font-medium">Authorization</span>
                    <span className="text-xs text-muted-foreground font-mono">Bearer &lt;token&gt;</span>
                  </div>
                  <p className="text-xs text-muted-foreground mt-1">
                    Pass the token in the Authorization header
                  </p>
                </div>
              </>
            )}

            {request.auth.authType === 'api-key' && (
              <>
                <div className="px-3 py-2 border-b bg-muted/30">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-sm">API Key</span>
                    <span className="text-xs text-orange-500 font-medium">required</span>
                  </div>
                </div>
                <div className="p-3 space-y-3">
                  <div className="border-b border-border/50 pb-3">
                    <div className="flex items-start gap-2 flex-wrap">
                      <span className="font-semibold text-sm">{request.auth.key}</span>
                      <span className="text-xs text-muted-foreground">string</span>
                      <span className="text-xs text-orange-500 font-medium">required</span>
                    </div>
                    <p className="text-xs text-muted-foreground mt-1">
                      Your API key for authentication
                    </p>
                  </div>
                  <div className="flex items-center gap-2 text-xs">
                    <span className="text-muted-foreground">Location:</span>
                    <code className="bg-muted px-2 py-0.5 rounded font-mono">
                      {request.auth.addTo === 'HEADERS' ? 'Header' : 'Query'}
                    </code>
                  </div>
                </div>
              </>
            )}

            {request.auth.authType === 'oauth-2' && (
              <>
                <div className="px-3 py-2 border-b bg-muted/30">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-sm">OAuth 2.0</span>
                    <span className="text-xs text-orange-500 font-medium">required</span>
                  </div>
                </div>
                <div className="p-3 space-y-3">
                  <div className="border-b border-border/50 pb-3">
                    <div className="flex items-start gap-2 flex-wrap">
                      <span className="font-semibold text-sm">Grant Type</span>
                      <span className="text-xs text-muted-foreground">
                        {request.auth.grantTypeInfo.grantType.replace('_', ' ')}
                      </span>
                    </div>
                  </div>
                  {request.auth.grantTypeInfo.authEndpoint && (
                    <div className="border-b border-border/50 pb-3">
                      <div className="flex items-start gap-2 flex-wrap">
                        <span className="font-semibold text-sm">authEndpoint</span>
                        <span className="text-xs text-muted-foreground">string</span>
                      </div>
                      <code className="text-xs text-muted-foreground mt-1 block break-all">
                        {request.auth.grantTypeInfo.authEndpoint}
                      </code>
                    </div>
                  )}
                  {request.auth.grantTypeInfo.tokenEndpoint && (
                    <div className="pb-1">
                      <div className="flex items-start gap-2 flex-wrap">
                        <span className="font-semibold text-sm">tokenEndpoint</span>
                        <span className="text-xs text-muted-foreground">string</span>
                      </div>
                      <code className="text-xs text-muted-foreground mt-1 block break-all">
                        {request.auth.grantTypeInfo.tokenEndpoint}
                      </code>
                    </div>
                  )}
                </div>
              </>
            )}
          </div>
        </CollapsibleSection>
      )}

      {/* Body */}
      {request.body.body !== null && (
        <CollapsibleSection title="Request Body" defaultOpen={false}>
          <div className="border rounded-sm overflow-hidden">
            <div className="bg-muted/50 px-3 py-2 border-b">
              <span className="text-xs font-medium">Content-Type: </span>
              <code className="text-xs">{request.body.contentType}</code>
            </div>
            {Array.isArray(request.body.body) ? (
              <div className="p-3 space-y-1">
                {request.body.body.map((item, index) => (
                  <div key={index} className="flex items-center gap-2 text-xs">
                    <code className="bg-background px-2 py-1 rounded">{item.key}</code>
                    <span className="text-muted-foreground">
                      {item.isFile ? '(file)' : '(text)'}
                    </span>
                  </div>
                ))}
              </div>
            ) : (
              <div className="dark-editor">
                <CodeViewer
                  value={typeof request.body.body === 'string' ? request.body.body : JSON.stringify(request.body.body)}
                  language={request.body.contentType?.includes('json') ? 'json' : request.body.contentType?.includes('xml') ? 'xml' : 'plaintext'}
                  theme="dark"
                  height="auto"
                  minHeight={80}
                  maxHeight={250}
                  showBorder={false}
                  rounded={false}
                />
              </div>
            )}
          </div>
        </CollapsibleSection>
      )}

      {/* Responses */}
      {Object.keys(request.responses).length > 0 && (
        <CollapsibleSection title="Responses" defaultOpen={true}>
          <div>
            {Object.entries(request.responses).map(([name, response]) => (
              <ResponseSchema
                key={name}
                code={response.code}
                status={response.status}
                description={name !== response.status ? name : undefined}
                schema={response.body}
              />
            ))}
          </div>
        </CollapsibleSection>
      )}
    </div>
  )
}
