'use client'

import type { BrainfishRESTReqBody, FormDataKeyValue } from '@/lib/api-docs/types'

interface BodySectionProps {
  body: BrainfishRESTReqBody
}

export function BodySection({ body }: BodySectionProps) {
  if (!body.body || body.contentType === null) {
    return null
  }

  const isFormData = Array.isArray(body.body)
  const isFormUrlEncoded = body.contentType === 'application/x-www-form-urlencoded'
  
  let bodyContent: string
  let formItems: FormDataKeyValue[] = []
  
  if (isFormData) {
    formItems = body.body as FormDataKeyValue[]
    bodyContent = JSON.stringify(
      formItems.map((item) => ({ key: item.key, value: item.value, isFile: item.isFile })),
      null,
      2
    )
  } else if (typeof body.body === 'string') {
    bodyContent = body.body
  } else {
    bodyContent = JSON.stringify(body.body, null, 2)
  }

  return (
    <section>
      <h2 className="text-2xl font-semibold mb-4">Request Body</h2>
      <div className="border rounded-sm overflow-hidden">
        <div className="bg-muted/50 px-4 py-2 border-b">
          <span className="text-sm font-medium">Content-Type: </span>
          <code className="text-sm">{body.contentType}</code>
        </div>
        <div className="p-4">
          {isFormData && formItems.length > 0 ? (
            <div className="space-y-2">
              {formItems.map((item, index) => (
                <div key={index} className="flex items-center gap-2">
                  <code className="bg-background px-2 py-1 rounded text-sm">{item.key}</code>
                  <span className="text-sm text-muted-foreground">
                    {item.isFile ? '(file)' : '(text)'}
                  </span>
                </div>
              ))}
            </div>
          ) : isFormUrlEncoded ? (
            <pre className="bg-muted p-4 rounded overflow-x-auto">
              <code className="text-sm">{bodyContent}</code>
            </pre>
          ) : (
            <pre className="bg-muted p-4 rounded overflow-x-auto">
              <code className="text-sm">{bodyContent}</code>
            </pre>
          )}
        </div>
      </div>
    </section>
  )
}
