'use client';

/**
 * API Reference: Image Generation
 *
 * Based on docs/api/image-generation.md
 */

import { TipBox } from '@/components/docs/shared/TipBox';
import { Table } from '@/components/docs/shared/Table';
import { CodeBlock } from '@/components/docs/shared/CodeBlock';
import { DocPage } from '@/components/docs/layout/DocPage';
import { InteractiveAPIWidget } from '@/components/docs/blocks/InteractiveAPIWidget';
import {
  Hero,
  SectionHeader,
  InlineCode,
  EndpointCard,
} from '@/components/docs/blocks';

const tocItems = [
  { id: 'overview', text: 'Overview', level: 2 },
  { id: 'endpoint', text: 'Create Generation', level: 2 },
  { id: 'parameters', text: 'Parameters', level: 2 },
  { id: 'aspect-ratios', text: 'Aspect Ratios', level: 2 },
  { id: 'prompt-enhancement', text: 'Prompt Enhancement', level: 2 },
  { id: 'generation-status', text: 'Generation Status', level: 2 },
  { id: 'response', text: 'Response Format', level: 2 },
  { id: 'error-codes', text: 'Error Codes', level: 2 },
  { id: 'interactive', text: 'Try It Live', level: 2 },
  { id: 'next-steps', text: 'Next Steps', level: 2 },
];

const parameters = [
  { name: 'prompt', type: 'string', required: true, description: 'Text description of the image to generate' },
  { name: 'aspectRatio', type: 'string', required: false, default: '"1:1"', description: 'Image aspect ratio (1:1, 16:9, 9:16, 3:2, 21:9)' },
  { name: 'autoEnhance', type: 'boolean', required: false, default: 'true', description: 'Enable AI prompt enhancement for better results' },
  { name: 'meta', type: 'object', required: false, default: '{}', description: 'Custom metadata to store with generation' },
];

const aspectRatios = [
  ['1:1', 'Square images, social media posts, profile pictures'],
  ['16:9', 'Landscape, hero banners, video thumbnails'],
  ['9:16', 'Portrait, mobile screens, stories'],
  ['3:2', 'Photography standard, print'],
  ['21:9', 'Ultra-wide banners, cinematic'],
];

const statuses = [
  ['pending', 'Generation created, waiting to start'],
  ['processing', 'AI is generating the image'],
  ['success', 'Image generated successfully'],
  ['failed', 'Generation failed (see errorMessage)'],
];

const errorCodes = [
  ['400', 'VALIDATION_ERROR', 'Invalid parameters in the request body'],
  ['401', 'UNAUTHORIZED', 'Missing or invalid API key in X-API-Key header'],
  ['404', 'GENERATION_NOT_FOUND', 'Generation does not exist'],
  ['429', 'RATE_LIMIT_EXCEEDED', 'Too many requests (100/hour limit)'],
  ['500', 'GENERATION_FAILED', 'AI generation failed'],
];

export default function ImageGenerationPage() {
  return (
    <DocPage
      breadcrumbItems={[
        { label: 'Documentation', href: '/docs' },
        { label: 'API Reference', href: '/docs/api' },
        { label: 'Image Generation' },
      ]}
      tocItems={tocItems}
      nextSteps={{
        links: [
          {
            href: '/docs/api/advanced',
            title: 'Advanced Generation',
            description: 'Learn about references, aliases, and generation flows.',
            accent: 'primary',
          },
          {
            href: '/docs/api/upload',
            title: 'Image Upload',
            description: 'Upload reference images for image-to-image generation.',
            accent: 'secondary',
          },
        ],
      }}
    >
      {/* Hero Section */}
      <Hero
        title="Image Generation"
        subtitle="Generate high-quality AI images from text prompts with automatic enhancement."
      />

      {/* Overview */}
      <section id="overview" className="mb-12">
        <SectionHeader level={2} id="overview">
          Overview
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          The Image Generation API allows you to create AI-generated images from natural language descriptions.
          Powered by advanced AI models, it produces high-quality images optimized for your specified requirements.
        </p>
        <TipBox variant="compact" type="info">
          <strong>Tip:</strong> Enable <InlineCode>autoEnhance</InlineCode> (on by default)
          to let AI improve your prompts for better image quality.
        </TipBox>
      </section>

      {/* Endpoint */}
      <section id="endpoint" className="mb-12">
        <SectionHeader level={2} id="endpoint">
          Create Generation
        </SectionHeader>
        <EndpointCard
          method="POST"
          endpoint="/api/v1/generations"
          baseUrl="https://api.banatie.app"
        />
        <p className="text-gray-400 text-sm mt-4">
          Requires <InlineCode>X-API-Key</InlineCode> header with your Project Key.
        </p>
      </section>

      {/* Parameters */}
      <section id="parameters" className="mb-12">
        <SectionHeader level={2} id="parameters" className="mb-6">
          Parameters
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-6">
          All parameters should be sent in the request body as JSON.
        </p>

        <Table
          headers={['Parameter', 'Type', 'Required', 'Default', 'Description']}
          rows={parameters.map((param) => [
            <InlineCode key="name">{param.name}</InlineCode>,
            <span key="type" className="text-cyan-400">{param.type}</span>,
            <span key="required" className={param.required ? 'text-green-400' : 'text-gray-500'}>
              {param.required ? 'Yes' : 'No'}
            </span>,
            param.default ? <InlineCode key="default">{param.default}</InlineCode> : <span className="text-gray-500">-</span>,
            param.description,
          ])}
        />

        <div className="mt-6">
          <CodeBlock
            code={`{
  "prompt": "a red sports car on a mountain road",
  "aspectRatio": "16:9",
  "autoEnhance": true
}`}
            language="json"
            filename="Example Request"
          />
        </div>
      </section>

      {/* Aspect Ratios */}
      <section id="aspect-ratios" className="mb-12">
        <SectionHeader level={2} id="aspect-ratios" className="mb-6">
          Aspect Ratios
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-6">
          Supported aspect ratios for image generation:
        </p>

        <Table
          headers={['Aspect Ratio', 'Use Case']}
          rows={aspectRatios.map(([ratio, useCase]) => [
            <InlineCode key="ratio">{ratio}</InlineCode>,
            useCase,
          ])}
        />
      </section>

      {/* Prompt Enhancement */}
      <section id="prompt-enhancement" className="mb-12">
        <SectionHeader level={2} id="prompt-enhancement" className="mb-6">
          Prompt Enhancement
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          By default, prompts are automatically enhanced by AI to produce better results.
        </p>

        <SectionHeader level={3} id="how-it-works" className="mb-4">
          How It Works
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          When <InlineCode>autoEnhance: true</InlineCode> (default):
        </p>
        <ul className="list-disc list-inside text-gray-300 space-y-2 mb-6">
          <li>Your original prompt is preserved in <InlineCode>originalPrompt</InlineCode></li>
          <li>AI enhances it with style details, lighting, and composition</li>
          <li>The enhanced version is stored in <InlineCode>prompt</InlineCode> and used for generation</li>
        </ul>

        <p className="text-gray-300 leading-relaxed mb-4">
          When <InlineCode>autoEnhance: false</InlineCode>:
        </p>
        <ul className="list-disc list-inside text-gray-300 space-y-2 mb-6">
          <li>Both <InlineCode>prompt</InlineCode> and <InlineCode>originalPrompt</InlineCode> contain your original text</li>
          <li>No AI enhancement is applied</li>
        </ul>

        <TipBox variant="prominent" type="info">
          <strong>Enhancement Templates (Roadmap):</strong> Template selection for enhancement styles
          (photorealistic, illustration, minimalist, etc.) is planned for a future release.
          Currently all enhanced prompts use the default general style.
        </TipBox>

        <div className="mt-6">
          <CodeBlock
            code={`// Request
{
  "prompt": "a cat",
  "autoEnhance": true
}

// Response
{
  "prompt": "A photorealistic close-up portrait of a domestic cat with soft fur, captured with an 85mm lens...",
  "originalPrompt": "a cat",
  "autoEnhance": true
}`}
            language="json"
            filename="Enhancement Example"
          />
        </div>
      </section>

      {/* Generation Status */}
      <section id="generation-status" className="mb-12">
        <SectionHeader level={2} id="generation-status" className="mb-6">
          Generation Status
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-6">
          Generations go through these status stages:
        </p>

        <Table
          headers={['Status', 'Description']}
          rows={statuses.map(([status, description]) => [
            <InlineCode key="status">{status}</InlineCode>,
            description,
          ])}
        />

        <p className="text-gray-300 leading-relaxed mt-6 mb-4">
          Poll the generation endpoint to check status:
        </p>
        <EndpointCard
          method="GET"
          endpoint="/api/v1/generations/:id"
          baseUrl="https://api.banatie.app"
        />
        <p className="text-gray-400 text-sm mt-4">
          When <InlineCode>status: "success"</InlineCode>, the <InlineCode>outputImageId</InlineCode> field
          contains the generated image ID.
        </p>
      </section>

      {/* Response */}
      <section id="response" className="mb-12">
        <SectionHeader level={2} id="response" className="mb-4">
          Response Format
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          On success, the API returns a JSON object containing the generation details and output image.
        </p>

        <CodeBlock
          code={`{
  "success": true,
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "projectId": "57c7f7f4-47de-4d70-9ebd-3807a0b63746",
    "prompt": "A photorealistic establishing shot of a sleek red sports car...",
    "originalPrompt": "a red sports car on a mountain road",
    "autoEnhance": true,
    "aspectRatio": "16:9",
    "status": "success",
    "outputImageId": "7c4ccf47-41ce-4718-afbc-8c553b2c631a",
    "outputImage": {
      "id": "7c4ccf47-41ce-4718-afbc-8c553b2c631a",
      "storageUrl": "https://cdn.banatie.app/default/my-project/img/7c4ccf47-41ce-4718-afbc-8c553b2c631a",
      "mimeType": "image/png",
      "width": 1792,
      "height": 1024,
      "fileSize": 1909246
    },
    "processingTimeMs": 8500,
    "createdAt": "2025-11-28T10:00:00.000Z"
  }
}`}
          language="json"
          filename="Success Response"
        />

        <TipBox variant="compact" type="info" >
          <strong>Note:</strong> The image URL uses the UUID as filename with no extension.
          Content-Type is stored in object metadata.
        </TipBox>
      </section>

      {/* Error Codes */}
      <section id="error-codes" className="mb-12">
        <SectionHeader level={2} id="error-codes" className="mb-6">
          Error Codes
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-6">
          The API uses standard HTTP status codes and returns descriptive error messages.
        </p>

        <Table
          headers={['Status', 'Code', 'Description']}
          rows={errorCodes.map(([status, code, description]) => [
            <InlineCode key="status" color="error">{status}</InlineCode>,
            <InlineCode key="code">{code}</InlineCode>,
            description,
          ])}
        />

        <div className="mt-6">
          <TipBox variant="compact" type="warning">
            <strong>Rate Limits:</strong> Project API keys are limited to 100 requests per hour.
            Check <InlineCode>X-RateLimit-Remaining</InlineCode> header for current usage.
          </TipBox>
        </div>
      </section>

      {/* Interactive Widget */}
      <section id="interactive" className="mb-12">
        <SectionHeader level={2} id="interactive" className="mb-4">
          Try It Live
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-6">
          Test the API directly from this page. Enter your API key and customize the parameters below.
        </p>

        <InteractiveAPIWidget
          endpoint="/api/v1/generations"
          method="POST"
          description="Generate an image from a text prompt"
          parameters={parameters}
        />
      </section>
    </DocPage>
  );
}
