import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '../../lib/api';
import { useI18n } from '../../lib/i18n';
import { useLayoutContext } from '../Layout';

type Project = { id: string; name: string };

export default function McpIntegration({ project }: { project: Project }) {
  const [copied, setCopied] = useState<string | null>(null);
  const { onOpenSettings } = useLayoutContext();
  const { t } = useI18n();
  const mcpHost = window.location.hostname;
  const mcpUrl = `http://${mcpHost}:3001/mcp/${project.id}`;

  const { data: keyStatus } = useQuery({
    queryKey: ['api-key-status'],
    queryFn: () => apiFetch<{ hasKey: boolean; prefix: string | null }>('/auth/api-key/status'),
  });

  const serverName = project.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
  const configSnippet = JSON.stringify({
    mcpServers: {
      [serverName]: {
        type: 'http',
        url: mcpUrl,
        headers: { Authorization: 'Bearer <your-api-key>' },
      },
    },
  }, null, 2);

  const copyText = (text: string, key: string) => {
    navigator.clipboard.writeText(text);
    setCopied(key);
    setTimeout(() => setCopied(null), 2000);
  };

  return (
    <div className="max-w-2xl space-y-8">
      {/* MCP URL */}
      <section>
        <p className="section-title">{t('dashboard.mcp.urlTitle')}</p>
        <p className="section-desc mb-3">{t('dashboard.mcp.urlDesc')}</p>
        <div className="flex items-center gap-2">
          <code className="flex-1 px-3.5 py-2.5 rounded-lg bg-bg-tertiary border border-border-muted text-[13px] font-mono text-text-primary truncate">{mcpUrl}</code>
          <button onClick={() => copyText(mcpUrl, 'url')} className="btn-outline shrink-0">
            {copied === 'url' ? (
              <><svg className="w-3.5 h-3.5 text-success" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path d="M5 13l4 4L19 7" /></svg> {t('common.copied')}</>
            ) : (
              <><svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" /></svg> {t('common.copy')}</>
            )}
          </button>
        </div>
      </section>

      {/* Config snippet */}
      <section>
        <p className="section-title">{t('dashboard.mcp.configTitle')}</p>
        <p className="section-desc mb-3">{t('dashboard.mcp.configDesc')}</p>
        <div className="relative">
          <pre className="code-block text-xs">{configSnippet}</pre>
          <button onClick={() => copyText(configSnippet, 'config')} className="copy-btn absolute top-2.5 right-2.5">
            {copied === 'config' ? `${t('common.copied')}!` : t('common.copy')}
          </button>
        </div>

        {/* API Key guidance */}
        {keyStatus && (
          <div className="mt-3">
            {keyStatus.hasKey ? (
              <div className="flex items-center gap-2 px-3.5 py-2.5 rounded-lg bg-bg-tertiary border border-border-muted">
                <svg className="w-4 h-4 text-success shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M5 13l4 4L19 7" /></svg>
                <p className="text-[13px] text-text-secondary">
                  {t('dashboard.mcp.keyGenerated')}{' '}
                  <button onClick={onOpenSettings} className="text-accent hover:underline font-medium">{t('common.settings')}</button>
                  {' '}{t('dashboard.mcp.keyReplace')} <code className="text-xs font-mono bg-bg-inset px-1 py-0.5 rounded">&lt;your-api-key&gt;</code> {t('dashboard.mcp.keyAbove')}
                </p>
              </div>
            ) : (
              <div className="flex items-center gap-3 p-3.5 rounded-lg bg-warning-muted border border-warning/20">
                <svg className="w-4 h-4 text-warning shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" /></svg>
                <p className="text-[13px] text-text-secondary flex-1">{t('dashboard.mcp.noKeyWarning')}</p>
                <button onClick={onOpenSettings} className="btn-primary shrink-0 text-[13px] py-1.5 px-3">
                  {t('dashboard.mcp.openSettings')}
                </button>
              </div>
            )}
          </div>
        )}
      </section>

      {/* Available tools */}
      <section>
        <p className="section-title">{t('dashboard.mcp.toolsTitle')}</p>
        <p className="section-desc mb-3">{t('dashboard.mcp.toolsDesc')}</p>
        <div className="space-y-1.5 stagger-children">
          {[
            { name: 'get_project_overview', desc: t('dashboard.mcp.tool1Desc'), num: '1' },
            { name: 'list_modules', desc: t('dashboard.mcp.tool2Desc'), num: '2' },
            { name: 'list_endpoints', desc: t('dashboard.mcp.tool3Desc'), num: '3' },
            { name: 'get_endpoint_detail', desc: t('dashboard.mcp.tool4Desc'), num: '4' },
            { name: 'search_endpoints', desc: t('dashboard.mcp.tool5Desc'), num: '5' },
          ].map((tool) => (
            <div key={tool.name} className="card px-4 py-3 flex items-start gap-3">
              <span className="w-5 h-5 rounded-full bg-accent-muted text-accent text-[10px] font-bold flex items-center justify-center shrink-0 mt-0.5">{tool.num}</span>
              <div className="min-w-0">
                <code className="text-[13px] font-mono font-medium text-accent">{tool.name}</code>
                <p className="text-xs text-text-muted mt-0.5 leading-relaxed">{tool.desc}</p>
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}
