'use client';

/**
 * Authentication Guide
 *
 * Refactored to use DocPage component for consistent layout
 * Layout handles SubsectionNav and Left Sidebar
 * DocPage handles Breadcrumb, Article structure, Next Steps, and TOC
 * This page provides only the content (Hero + sections)
 */

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,
} from '@/components/docs/blocks';

const tocItems = [
  { id: 'overview', text: 'Overview', level: 2 },
  { id: 'api-keys', text: 'API Keys', level: 2 },
  { id: 'key-types', text: 'Key Types', level: 3 },
  { id: 'creating-keys', text: 'Creating Keys', level: 3 },
  { id: 'using-keys', text: 'Using API Keys', level: 2 },
  { id: 'rate-limits', text: 'Rate Limits', level: 2 },
  { id: 'security', text: 'Security Best Practices', level: 2 },
  { id: 'next-steps', text: 'Next Steps', level: 2 },
];

export default function AuthenticationGuidePage() {
  return (
    <DocPage
      breadcrumbItems={[
        { label: 'Documentation', href: '/docs' },
        { label: 'Guides', href: '/docs/guides' },
        { label: 'Authentication' },
      ]}
      tocItems={tocItems}
      nextSteps={{
        links: [
          {
            href: '/docs/api/text-to-image',
            title: 'Start Generating Images',
            description: 'Explore the Text to Image API and start building your integration.',
            accent: 'primary',
          },
          {
            href: '/docs/guides/error-handling',
            title: 'Error Handling Guide',
            description: 'Learn how to handle authentication errors and implement retry logic.',
            accent: 'secondary',
          },
        ],
      }}
    >

        {/* Hero Section */}
        <Hero
          title="Authentication"
          subtitle="Learn how to authenticate with the Banatie API using API keys, manage rate limits, and implement security best practices."
        />

        {/* Overview */}
        <section id="overview" className="mb-12">
          <SectionHeader level={2} id="overview" className="mb-4">
            Overview
          </SectionHeader>
          <p className="text-gray-300 leading-relaxed mb-6">
            Banatie uses API keys to authenticate requests. All API endpoints require authentication
            via the <InlineCode>X-API-Key</InlineCode> header.
            API keys are tied to organizations and projects, providing fine-grained access control.
          </p>

          <TipBox variant="compact" type="info">
            <strong>Quick Start:</strong> New to API authentication? Check out our{' '}
            <a href="/docs" className="text-purple-400 hover:underline">
              Getting Started guide
            </a>{' '}
            for a step-by-step walkthrough.
          </TipBox>
        </section>

        {/* API Keys */}
        <section id="api-keys" className="mb-12">
          <SectionHeader level={2} id="api-keys" className="mb-6">
            API Keys
          </SectionHeader>

          <div id="key-types" className="mb-8">
            <SectionHeader level={3} id="key-types" className="mb-4">
              Key Types
            </SectionHeader>
            <p className="text-gray-300 leading-relaxed mb-6">
              Banatie supports two types of API keys, each with different permissions and use cases:
            </p>

            <Table
              headers={['Key Type', 'Permissions', 'Expiration', 'Use Case']}
              rows={[
                [
                  <InlineCode key="type">Master Key</InlineCode>,
                  'Full admin access, can create/revoke keys',
                  <span key="exp" className="text-green-400">Never expires</span>,
                  'Server-side admin operations, key management',
                ],
                [
                  <InlineCode key="type" color="success">Project Key</InlineCode>,
                  'Image generation only',
                  <span key="exp" className="text-amber-400">90 days</span>,
                  'Application integration, API requests',
                ],
              ]}
            />

            <div className="mt-6">
              <TipBox variant="prominent" type="warning">
                <strong className="text-amber-300">Master Key Security:</strong> Master keys have full
                administrative access and never expire. Store them securely in encrypted vaults or
                secret managers. Never expose master keys in client-side code, logs, or version control.
                Use project keys for application integration whenever possible.
              </TipBox>
            </div>
          </div>

          <div id="creating-keys" className="mb-8">
            <SectionHeader level={3} id="creating-keys" className="mb-4">
              Creating Keys
            </SectionHeader>
            <p className="text-gray-300 leading-relaxed mb-4">
              For first-time setup, use the bootstrap endpoint to create your initial master key:
            </p>

            <CodeBlock
              code={`# Bootstrap your first master key (one-time only)
curl -X POST https://api.banatie.com/api/bootstrap/initial-key

# Response
{
  "success": true,
  "data": {
    "key": "bnt_master_abc123...",
    "type": "master"
  }
}`}
              language="bash"
              filename="Bootstrap Master Key"
            />

            <div className="mt-6">
              <p className="text-gray-300 leading-relaxed mb-4">
                Once you have a master key, you can create project keys for your applications:
              </p>

              <CodeBlock
                code={`# Create a project key with master key authentication
curl -X POST https://api.banatie.com/api/admin/keys \\
  -H "X-API-Key: YOUR_MASTER_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "type": "project",
    "projectId": "my-app",
    "name": "Production API Key"
  }'

# Response
{
  "success": true,
  "data": {
    "key": "bnt_project_xyz789...",
    "type": "project",
    "expiresAt": "2025-04-14T00:00:00Z"
  }
}`}
                language="bash"
                filename="Create Project Key"
              />
            </div>
          </div>
        </section>

        {/* Using API Keys */}
        <section id="using-keys" className="mb-12">
          <SectionHeader level={2} id="using-keys" className="mb-4">
            Using API Keys
          </SectionHeader>
          <p className="text-gray-300 leading-relaxed mb-4">
            Include your API key in the <InlineCode>X-API-Key</InlineCode> header
            with every request:
          </p>

          <CodeBlock
            code={`# Example: Generate an image with project key
curl -X POST https://api.banatie.com/api/text-to-image \\
  -H "X-API-Key: bnt_project_xyz789..." \\
  -H "Content-Type: application/json" \\
  -d '{
    "prompt": "a sunset over the ocean",
    "aspectRatio": "16:9"
  }'`}
            language="bash"
            filename="Authenticated Request"
          />

          <div className="mt-6">
            <TipBox variant="compact" type="info">
              <strong>Environment Variables:</strong> Store API keys in environment variables, not
              hardcoded in your application. Example:{' '}
              <InlineCode>BANATIE_API_KEY</InlineCode>
            </TipBox>
          </div>
        </section>

        {/* Rate Limits */}
        <section id="rate-limits" className="mb-12">
          <SectionHeader level={2} id="rate-limits" className="mb-6">
            Rate Limits
          </SectionHeader>
          <p className="text-gray-300 leading-relaxed mb-6">
            API keys are subject to rate limits to ensure fair usage and system stability. Limits
            vary by key type and plan tier:
          </p>

          <Table
            headers={['Key Type', 'Rate Limit', 'Reset Window', 'Upgrade Available']}
            rows={[
              [
                <InlineCode key="type">Master Key</InlineCode>,
                <span key="limit" className="text-green-400">Unlimited</span>,
                'N/A',
                'N/A',
              ],
              [
                <InlineCode key="type" color="success">Project Key (Free)</InlineCode>,
                <span key="limit" className="text-amber-400">100 requests/hour</span>,
                '1 hour rolling',
                <a key="upgrade" href="/pricing" className="text-purple-400 hover:underline">Yes</a>,
              ],
              [
                <InlineCode key="type" color="success">Project Key (Pro)</InlineCode>,
                <span key="limit" className="text-green-400">1,000 requests/hour</span>,
                '1 hour rolling',
                <a key="upgrade" href="/pricing" className="text-purple-400 hover:underline">Yes</a>,
              ],
            ]}
          />

          <div className="mt-6">
            <p className="text-gray-300 leading-relaxed mb-4">
              When you exceed rate limits, the API returns a <InlineCode color="error">429 Too Many Requests</InlineCode> status.
              Check the response headers for retry timing:
            </p>

            <CodeBlock
              code={`# Rate limit response headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704153600

# Error response body
{
  "error": "Rate limit exceeded",
  "retryAfter": 3600
}`}
              language="bash"
              filename="Rate Limit Response"
            />
          </div>
        </section>

        {/* Security Best Practices */}
        <section id="security" className="mb-12">
          <SectionHeader level={2} id="security" className="mb-6">
            Security Best Practices
          </SectionHeader>

          <TipBox variant="prominent" type="warning">
            <strong className="text-amber-300">Critical Security Guidelines:</strong>
            <ul className="mt-3 space-y-2 list-disc list-inside">
              <li>Never commit API keys to version control systems (Git, SVN, etc.)</li>
              <li>Store keys in environment variables or secret management services</li>
              <li>Use project keys in applications, reserve master keys for admin operations</li>
              <li>Rotate keys regularly, especially after team member changes</li>
              <li>Implement server-side API calls for production applications</li>
              <li>Monitor API key usage in your dashboard for suspicious activity</li>
            </ul>
          </TipBox>

          <div className="mt-6">
            <h3 className="text-lg font-semibold text-white mb-3">Key Rotation Example</h3>
            <CodeBlock
              code={`# 1. Create new project key
curl -X POST https://api.banatie.com/api/admin/keys \\
  -H "X-API-Key: YOUR_MASTER_KEY" \\
  -d '{"type": "project", "projectId": "my-app", "name": "New Key"}'

# 2. Update your application to use new key
export BANATIE_API_KEY="bnt_project_new..."

# 3. Revoke old key
curl -X DELETE https://api.banatie.com/api/admin/keys/OLD_KEY_ID \\
  -H "X-API-Key: YOUR_MASTER_KEY"`}
              language="bash"
              filename="Key Rotation Process"
            />
          </div>
        </section>

    </DocPage>
  );
}
