import { useState } from 'react'
import { Check, Copy } from 'lucide-react'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'

const API_BASE = 'https://akotocreativesms.com/api/v1'

// Docs always show the production domain, so copied samples keep working
// even when the page is viewed on a preview or netlify.app URL.
export function useApiBase() {
  return API_BASE
}

function samples(base: string) {
  return [
    {
      id: 'curl',
      label: 'cURL',
      code: `curl -X POST ${base}/sms/send \\
  -H "Authorization: Bearer akc_live_YOUR_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "sender_id": "AmaFabrics",
    "message": "Your order #1042 is ready for pickup.",
    "recipients": ["0241234567", "0201234567"]
  }'`,
    },
    {
      id: 'php',
      label: 'PHP',
      code: `<?php
$ch = curl_init('${base}/sms/send');
curl_setopt_array($ch, [
  CURLOPT_POST => true,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer ' . getenv('AKOTO_SMS_KEY'),
    'Content-Type: application/json',
  ],
  CURLOPT_POSTFIELDS => json_encode([
    'sender_id'  => 'AmaFabrics',
    'message'    => 'Your order #1042 is ready for pickup.',
    'recipients' => ['0241234567', '0201234567'],
  ]),
]);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);`,
    },
    {
      id: 'node',
      label: 'Node.js',
      code: `const res = await fetch('${base}/sms/send', {
  method: 'POST',
  headers: {
    Authorization: \`Bearer \${process.env.AKOTO_SMS_KEY}\`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    sender_id: 'AmaFabrics',
    message: 'Your order #1042 is ready for pickup.',
    recipients: ['0241234567', '0201234567'],
  }),
})
const { ok, data, error } = await res.json()`,
    },
    {
      id: 'python',
      label: 'Python',
      code: `import os, requests

res = requests.post(
    "${base}/sms/send",
    headers={"Authorization": f"Bearer {os.environ['AKOTO_SMS_KEY']}"},
    json={
        "sender_id": "AmaFabrics",
        "message": "Your order #1042 is ready for pickup.",
        "recipients": ["0241234567", "0201234567"],
    },
)
print(res.json())`,
    },
  ]
}

export function CopyButton({ value, label = 'Copy', className }: { value: string; label?: string; className?: string }) {
  const [copied, setCopied] = useState(false)
  async function copy() {
    try {
      await navigator.clipboard.writeText(value)
      setCopied(true)
      setTimeout(() => setCopied(false), 1500)
    } catch {
      toast.error('Copy failed. Select the text and copy it manually.')
    }
  }
  return (
    <button
      type="button"
      onClick={copy}
      className={cn(
        'inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-xs font-semibold outline-none transition-colors focus-visible:ring-2 focus-visible:ring-[var(--gold-glow)]',
        className,
      )}
    >
      {copied ? <Check className="size-3.5" aria-hidden /> : <Copy className="size-3.5" aria-hidden />}
      {copied ? 'Copied' : label}
    </button>
  )
}

export function CodeBlock({ code, title }: { code: string; title?: string }) {
  return (
    <div className="overflow-hidden rounded-2xl bg-[var(--forest-950)] text-white ring-1 ring-white/10">
      <div className="flex items-center justify-between gap-3 border-b border-white/10 px-4 py-2">
        <span className="font-mono text-xs text-white/55">{title}</span>
        <CopyButton value={code} className="text-white/70 hover:bg-white/10 hover:text-white" />
      </div>
      <pre className="overflow-x-auto p-4 font-mono text-[13px] leading-relaxed text-white/85">
        <code>{code}</code>
      </pre>
    </div>
  )
}

// Tabbed send-SMS examples in the languages Ghanaian web developers use most.
export function ApiCodeSamples({ className }: { className?: string }) {
  const base = useApiBase()
  const list = samples(base)
  const [active, setActive] = useState(list[0].id)
  const current = list.find((s) => s.id === active) ?? list[0]
  return (
    <div className={cn('overflow-hidden rounded-3xl bg-[var(--forest-950)] text-white ring-1 ring-white/10 shadow-2xl', className)}>
      <div className="flex items-center justify-between gap-3 border-b border-white/10 px-3 py-2">
        <div role="tablist" aria-label="Code language" className="flex flex-wrap gap-1">
          {list.map((s) => (
            <button
              key={s.id}
              type="button"
              role="tab"
              aria-selected={s.id === active}
              onClick={() => setActive(s.id)}
              className={cn(
                'h-8 rounded-full px-3 text-xs font-semibold outline-none transition-colors focus-visible:ring-2 focus-visible:ring-[var(--gold-glow)]',
                s.id === active ? 'bg-white/15 text-white' : 'text-white/55 hover:text-white',
              )}
            >
              {s.label}
            </button>
          ))}
        </div>
        <CopyButton value={current.code} className="text-white/70 hover:bg-white/10 hover:text-white" />
      </div>
      <pre role="tabpanel" className="overflow-x-auto p-5 font-mono text-[13px] leading-relaxed text-white/85">
        <code>{current.code}</code>
      </pre>
    </div>
  )
}
