'use client';

/**
 * API Reference: Advanced Generation
 *
 * Based on docs/api/image-generation-advanced.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 {
  Hero,
  SectionHeader,
  InlineCode,
  EndpointCard,
} from '@/components/docs/blocks';

const tocItems = [
  { id: 'overview', text: 'Overview', level: 2 },
  { id: 'reference-images', text: 'Reference Images', level: 2 },
  { id: 'alias-assignment', text: 'Alias Assignment', level: 2 },
  { id: 'alias-resolution', text: '3-Tier Alias Resolution', level: 2 },
  { id: 'flows', text: 'Generation Flows', level: 2 },
  { id: 'regeneration', text: 'Regeneration', level: 2 },
  { id: 'flow-management', text: 'Flow Management', level: 2 },
  { id: 'next-steps', text: 'Next Steps', level: 2 },
];

const referenceLimits = [
  ['Max references', '3 images'],
  ['Max file size', '5MB per image'],
  ['Supported formats', 'PNG, JPEG, WebP'],
];

const aliasFormat = [
  ['Prefix', 'Must start with @'],
  ['Characters', 'Alphanumeric, underscore, hyphen'],
  ['Pattern', '@[a-zA-Z0-9_-]+'],
  ['Max length', '50 characters'],
  ['Examples', '@logo, @hero-bg, @image_1'],
];

const technicalAliases = [
  ['@last', 'Most recently generated image in flow'],
  ['@first', 'First generated image in flow'],
  ['@upload', 'Most recently uploaded image in flow'],
];

const flowIdBehavior = [
  ['undefined (not provided)', 'Auto-generate pendingFlowId, lazy creation'],
  ['null (explicitly null)', 'No flow association'],
  ['"uuid-string"', 'Use provided ID, create flow if doesn\'t exist'],
];

const regenerationTriggers = [
  ['prompt', 'Yes'],
  ['aspectRatio', 'Yes'],
  ['flowId', 'No (metadata only)'],
  ['meta', 'No (metadata only)'],
];

export default function AdvancedGenerationPage() {
  return (
    <DocPage
      breadcrumbItems={[
        { label: 'Documentation', href: '/docs' },
        { label: 'API Reference', href: '/docs/api' },
        { label: 'Advanced Generation' },
      ]}
      tocItems={tocItems}
      nextSteps={{
        links: [
          {
            href: '/docs/api/live',
            title: 'Live URLs',
            description: 'Generate images on-demand via URL parameters.',
            accent: 'primary',
          },
          {
            href: '/docs/api/upload',
            title: 'Image Upload',
            description: 'Upload reference images for generation workflows.',
            accent: 'secondary',
          },
        ],
      }}
    >
      {/* Hero Section */}
      <Hero
        title="Advanced Generation"
        subtitle="Reference images, aliases, flows, and regeneration for complex workflows."
      />

      {/* Overview */}
      <section id="overview" className="mb-12">
        <SectionHeader level={2} id="overview">
          Overview
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          The Advanced Generation API extends basic generation with powerful features for
          production workflows: reference images for style guidance, aliases for human-readable
          identifiers, and flows for organizing related generations.
        </p>
        <TipBox variant="compact" type="info">
          <strong>Tip:</strong> For basic generation without these features, see the{' '}
          <a href="/docs/api/generate" className="text-purple-400 hover:underline">Image Generation</a> page.
        </TipBox>
      </section>

      {/* Reference Images */}
      <section id="reference-images" className="mb-12">
        <SectionHeader level={2} id="reference-images">
          Reference Images
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Use existing images as style or content references for generation.
        </p>

        <SectionHeader level={3} id="using-references" className="mb-4">
          Using References
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Add <InlineCode>referenceImages</InlineCode> array to your generation request:
        </p>

        <CodeBlock
          code={`{
  "prompt": "A product photo with the logo in the corner",
  "referenceImages": ["@brand-logo", "@product-style"]
}`}
          language="json"
          filename="Request with References"
        />

        <p className="text-gray-300 leading-relaxed mt-6 mb-4">
          References can be:
        </p>
        <ul className="list-disc list-inside text-gray-300 space-y-2 mb-6">
          <li><strong>Project aliases:</strong> <InlineCode>@logo</InlineCode>, <InlineCode>@brand-style</InlineCode></li>
          <li><strong>Flow aliases:</strong> <InlineCode>@hero</InlineCode> (with flowId context)</li>
          <li><strong>Technical aliases:</strong> <InlineCode>@last</InlineCode>, <InlineCode>@first</InlineCode>, <InlineCode>@upload</InlineCode></li>
          <li><strong>Image UUIDs:</strong> <InlineCode>550e8400-e29b-41d4-a716-446655440000</InlineCode></li>
        </ul>

        <SectionHeader level={3} id="auto-detection" className="mb-4">
          Auto-Detection from Prompt
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Aliases in the prompt are automatically detected and used as references:
        </p>

        <CodeBlock
          code={`{
  "prompt": "Create a banner using @brand-logo with blue background"
}
// @brand-logo is auto-detected and added to referenceImages`}
          language="json"
          filename="Auto-Detection"
        />

        <SectionHeader level={3} id="reference-limits" className="mt-6 mb-4">
          Reference Limits
        </SectionHeader>
        <Table
          headers={['Constraint', 'Limit']}
          rows={referenceLimits.map(([constraint, limit]) => [
            constraint,
            <InlineCode key="limit">{limit}</InlineCode>,
          ])}
        />
      </section>

      {/* Alias Assignment */}
      <section id="alias-assignment" className="mb-12">
        <SectionHeader level={2} id="alias-assignment">
          Alias Assignment
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Assign aliases to generated images for easy referencing.
        </p>

        <SectionHeader level={3} id="project-alias" className="mb-4">
          Project-Scoped Alias
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Use <InlineCode>alias</InlineCode> parameter to assign a project-wide alias:
        </p>

        <CodeBlock
          code={`{
  "prompt": "A hero banner image",
  "alias": "@hero-banner"
}`}
          language="json"
          filename="Project Alias"
        />

        <SectionHeader level={3} id="flow-alias" className="mt-6 mb-4">
          Flow-Scoped Alias
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Use <InlineCode>flowAlias</InlineCode> parameter to assign a flow-specific alias:
        </p>

        <CodeBlock
          code={`{
  "prompt": "A hero image variation",
  "flowId": "550e8400-...",
  "flowAlias": "@best"
}`}
          language="json"
          filename="Flow Alias"
        />

        <SectionHeader level={3} id="alias-format" className="mt-6 mb-4">
          Alias Format
        </SectionHeader>
        <Table
          headers={['Rule', 'Description']}
          rows={aliasFormat.map(([rule, description]) => [
            rule,
            <InlineCode key="desc">{description}</InlineCode>,
          ])}
        />

        <div className="mt-6">
          <TipBox variant="compact" type="warning">
            <strong>Override Behavior:</strong> When assigning an existing alias, the new image gets
            the alias and the old image loses it. The old image is not deleted, just unlinked.
          </TipBox>
        </div>
      </section>

      {/* 3-Tier Alias Resolution */}
      <section id="alias-resolution" className="mb-12">
        <SectionHeader level={2} id="alias-resolution">
          3-Tier Alias Resolution
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Aliases are resolved in order of precedence:
        </p>

        <SectionHeader level={3} id="tier-1" className="mb-4">
          1. Technical Aliases (Highest Priority)
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Computed on-the-fly, require flow context:
        </p>
        <Table
          headers={['Alias', 'Returns']}
          rows={technicalAliases.map(([alias, returns]) => [
            <InlineCode key="alias">{alias}</InlineCode>,
            returns,
          ])}
        />

        <SectionHeader level={3} id="tier-2" className="mt-6 mb-4">
          2. Flow Aliases
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Stored in flow&apos;s <InlineCode>aliases</InlineCode> JSONB field.
          Different flows can have the same alias pointing to different images.
        </p>

        <SectionHeader level={3} id="tier-3" className="mt-6 mb-4">
          3. Project Aliases (Lowest Priority)
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Stored in image&apos;s <InlineCode>alias</InlineCode> column.
          Global across the project, unique per project.
        </p>

        <div className="mt-6">
          <CodeBlock
            code={`// Request with flowId
GET /api/v1/images/@hero?flowId=abc-123

// Resolution order:
// 1. Is "@hero" a technical alias? No
// 2. Does flow abc-123 have "@hero" in aliases? Check flows.aliases JSONB
// 3. Does any image have alias = "@hero"? Check images.alias column`}
            language="bash"
            filename="Resolution Example"
          />
        </div>
      </section>

      {/* Generation Flows */}
      <section id="flows" className="mb-12">
        <SectionHeader level={2} id="flows">
          Generation Flows
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Flows organize related generations into chains.
        </p>

        <SectionHeader level={3} id="lazy-creation" className="mb-4">
          Lazy Flow Creation
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          When <InlineCode>flowId</InlineCode> is not provided, a pending flow ID is generated.
          The flow record is created when a second generation uses the same flowId or a flowAlias is assigned.
        </p>

        <SectionHeader level={3} id="eager-creation" className="mt-6 mb-4">
          Eager Flow Creation
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          When <InlineCode>flowAlias</InlineCode> is provided, the flow is created immediately.
        </p>

        <SectionHeader level={3} id="flowid-behavior" className="mt-6 mb-4">
          flowId Behavior
        </SectionHeader>
        <Table
          headers={['Value', 'Behavior']}
          rows={flowIdBehavior.map(([value, behavior]) => [
            <InlineCode key="value">{value}</InlineCode>,
            behavior,
          ])}
        />
      </section>

      {/* Regeneration */}
      <section id="regeneration" className="mb-12">
        <SectionHeader level={2} id="regeneration">
          Regeneration
        </SectionHeader>

        <SectionHeader level={3} id="regenerate-endpoint" className="mb-4">
          Regenerate Generation
        </SectionHeader>
        <EndpointCard
          method="POST"
          endpoint="/api/v1/generations/:id/regenerate"
          baseUrl="https://api.banatie.app"
        />
        <p className="text-gray-300 leading-relaxed mt-4 mb-4">
          Recreate an image using the exact same parameters. The output image ID and URL are preserved.
        </p>

        <SectionHeader level={3} id="update-regenerate" className="mt-6 mb-4">
          Update and Regenerate
        </SectionHeader>
        <EndpointCard
          method="PUT"
          endpoint="/api/v1/generations/:id"
          baseUrl="https://api.banatie.app"
        />
        <p className="text-gray-300 leading-relaxed mt-4 mb-4">
          Modify parameters with smart regeneration:
        </p>

        <Table
          headers={['Changed Field', 'Triggers Regeneration']}
          rows={regenerationTriggers.map(([field, triggers]) => [
            <InlineCode key="field">{field}</InlineCode>,
            <span key="triggers" className={triggers === 'Yes' ? 'text-green-400' : 'text-gray-500'}>{triggers}</span>,
          ])}
        />

        <SectionHeader level={3} id="flow-regenerate" className="mt-6 mb-4">
          Flow Regenerate
        </SectionHeader>
        <EndpointCard
          method="POST"
          endpoint="/api/v1/flows/:id/regenerate"
          baseUrl="https://api.banatie.app"
        />
        <p className="text-gray-300 leading-relaxed mt-4">
          Regenerate the most recent generation in a flow.
        </p>
      </section>

      {/* Flow Management */}
      <section id="flow-management" className="mb-12">
        <SectionHeader level={2} id="flow-management">
          Flow Management
        </SectionHeader>

        <div className="space-y-6">
          <div>
            <EndpointCard
              method="GET"
              endpoint="/api/v1/flows"
              baseUrl="https://api.banatie.app"
            />
            <p className="text-gray-400 text-sm mt-2">List all flows with pagination</p>
          </div>

          <div>
            <EndpointCard
              method="GET"
              endpoint="/api/v1/flows/:id"
              baseUrl="https://api.banatie.app"
            />
            <p className="text-gray-400 text-sm mt-2">Get flow with computed counts and aliases</p>
          </div>

          <div>
            <EndpointCard
              method="GET"
              endpoint="/api/v1/flows/:id/generations"
              baseUrl="https://api.banatie.app"
            />
            <p className="text-gray-400 text-sm mt-2">List all generations in the flow</p>
          </div>

          <div>
            <EndpointCard
              method="GET"
              endpoint="/api/v1/flows/:id/images"
              baseUrl="https://api.banatie.app"
            />
            <p className="text-gray-400 text-sm mt-2">List all images in the flow (generated and uploaded)</p>
          </div>

          <div>
            <EndpointCard
              method="PUT"
              endpoint="/api/v1/flows/:id/aliases"
              baseUrl="https://api.banatie.app"
            />
            <p className="text-gray-400 text-sm mt-2">Update flow aliases (merges with existing)</p>
          </div>

          <div>
            <EndpointCard
              method="DELETE"
              endpoint="/api/v1/flows/:id"
              baseUrl="https://api.banatie.app"
            />
            <p className="text-gray-400 text-sm mt-2">Delete flow with cascade behavior</p>
          </div>
        </div>

        <div className="mt-6">
          <TipBox variant="prominent" type="warning">
            <strong>Cascade Delete:</strong> Deleting a flow hard-deletes all generations and images
            without project aliases. Images with project aliases are kept but unlinked from the flow.
          </TipBox>
        </div>
      </section>
    </DocPage>
  );
}
