'use client';

import { useState, useMemo } from 'react';
import { Webhook, Copy, Check } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { API_BASE_URL } from '@/lib/apiClient';
import { useI18n } from '@/lib/i18n';

function getWebhookSnippet(): string {
  const baseUrl = API_BASE_URL.replace(/\/$/, '');
  return `curl -X POST ${baseUrl}/api/v1/translate \\
  -H "Authorization: Bearer sk_live_YOUR_API_KEY" \\
  -H "Content-Type: multipart/form-data" \\
  -F "file=@document.xlsx" \\
  -F "source_lang=en" \\
  -F "target_lang=fr" \\
  -F "webhook_url=https://your-app.com/webhook/complete"`;
}

export function WebhookSnippet() {
  const { t } = useI18n();
  const [copied, setCopied] = useState(false);

  const webhookSnippet = useMemo(() => getWebhookSnippet(), []);

  const copySnippet = () => {
    navigator.clipboard.writeText(webhookSnippet);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <Webhook className="h-5 w-5 text-accent" />
          <CardTitle className="text-base">{t('apiKeys.webhook.title')}</CardTitle>
        </div>
      </CardHeader>
      <CardContent className="space-y-3">
        <p className="text-sm text-muted-foreground">
          {t('apiKeys.webhook.descriptionBefore')}<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{t('apiKeys.webhook.codeParam')}</code>{t('apiKeys.webhook.descriptionAfter')}
        </p>
        <div className="relative">
          <Button
            variant="ghost"
            size="icon-sm"
            className="absolute right-2 top-2 z-10"
            onClick={copySnippet}
          >
            {copied ? (
              <Check className="h-3.5 w-3.5 text-accent" />
            ) : (
              <Copy className="h-3.5 w-3.5" />
            )}
          </Button>
          <pre className="overflow-x-auto rounded-lg border border-border bg-foreground p-4 text-xs leading-relaxed text-background/90">
            <code>{webhookSnippet}</code>
          </pre>
        </div>
      </CardContent>
    </Card>
  );
}
