'use client';

import { useEffect, useState } from 'react';
import { fetchWithAuth } from '@/lib/auth';
import { useIsMobile } from '@/lib/useIsMobile';
import { useTranslation } from '@/lib/i18n';

const API = process.env.NEXT_PUBLIC_API_URL ?? '';
// CLI --api-host: use backend URL in dev, or page origin in production (same domain).
const CLI_API_HOST = API || (typeof window !== 'undefined' ? window.location.origin : '');

interface ApiKey {
  id: string;
  name: string;
  key_prefix: string;
  created_at: string;
  last_used_at: string | null;
}

interface NewKeyResult {
  id: string;
  name: string;
  key: string;
  key_prefix: string;
  created_at: string;
}

async function fetchApiKeys(): Promise<ApiKey[]> {
  const res = await fetchWithAuth(`${API}/api/user/api-keys`);
  if (!res.ok) return [];
  const data = await res.json();
  return data.api_keys ?? [];
}

async function createApiKey(name: string): Promise<NewKeyResult | null> {
  const res = await fetchWithAuth(`${API}/api/user/api-keys`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name }),
  });
  if (!res.ok) return null;
  return res.json();
}

async function revokeApiKey(id: string): Promise<boolean> {
  const res = await fetchWithAuth(`${API}/api/user/api-keys/${encodeURIComponent(id)}`, {
    method: 'DELETE',
  });
  return res.ok;
}

export default function ApiKeysSection() {
  const { t, locale } = useTranslation();
  const [keys, setKeys] = useState<ApiKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [newKeyName, setNewKeyName] = useState('CLI Key');
  const [justCreated, setJustCreated] = useState<NewKeyResult | null>(null);
  const [copied, setCopied] = useState(false);
  const [copiedInit, setCopiedInit] = useState(false);
  const [copiedInstall, setCopiedInstall] = useState(false);
  const [revokingId, setRevokingId] = useState<string | null>(null);
  const isMobile = useIsMobile();

  const formatDate = (iso: string) => {
    const tag = locale === 'zh' ? 'zh-CN' : locale === 'ja' ? 'ja-JP' : 'en-US';
    return new Date(iso).toLocaleDateString(tag, {
      month: 'short', day: 'numeric', year: 'numeric',
    });
  };

  useEffect(() => {
    fetchApiKeys().then(ks => { setKeys(ks); setLoading(false); });
  }, []);

  const handleCreate = async () => {
    if (!newKeyName.trim()) return;
    setCreating(true);
    const result = await createApiKey(newKeyName.trim());
    setCreating(false);
    if (result) {
      setJustCreated(result);
      setKeys(prev => [{ id: result.id, name: result.name, key_prefix: result.key_prefix, created_at: result.created_at, last_used_at: null }, ...prev]);
      setNewKeyName('CLI Key');
    }
  };

  const handleCopy = () => {
    if (!justCreated) return;
    navigator.clipboard.writeText(justCreated.key).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const handleRevoke = async (id: string) => {
    setRevokingId(id);
    const ok = await revokeApiKey(id);
    setRevokingId(null);
    if (ok) {
      setKeys(prev => prev.filter(k => k.id !== id));
      if (justCreated?.id === id) setJustCreated(null);
    }
  };

  return (
    <div>
      <div style={{ marginBottom: '20px' }}>
        <div style={{ fontSize: '15px', fontWeight: 600, color: '#1a1a2e', marginBottom: '4px' }}>
          {t('apiKeys.title')}
        </div>
        <div style={{ fontSize: '13px', color: '#777' }}>
          {t('apiKeys.description')}
        </div>
      </div>

      {/* Create new key */}
      <div style={{
        border: '1px solid #e5e7eb',
        borderRadius: '10px',
        padding: '16px',
        marginBottom: '16px',
        background: '#fafafa',
      }}>
        <div style={{ fontSize: '13px', fontWeight: 600, color: '#374151', marginBottom: '10px' }}>
          {t('apiKeys.createNew')}
        </div>
        <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: '8px' }}>
          <input
            type="text"
            value={newKeyName}
            onChange={e => setNewKeyName(e.target.value)}
            placeholder={t('apiKeys.namePlaceholder')}
            onKeyDown={e => { if (e.key === 'Enter') handleCreate(); }}
            style={{
              flex: 1,
              padding: '7px 10px',
              borderRadius: '6px',
              border: '1px solid #d1d5db',
              fontSize: '13px',
              outline: 'none',
            }}
          />
          <button
            onClick={handleCreate}
            disabled={creating || !newKeyName.trim()}
            style={{
              padding: '7px 16px',
              borderRadius: '6px',
              border: 'none',
              background: creating || !newKeyName.trim() ? '#d1d5db' : '#5c5fbc',
              color: '#fff',
              fontSize: '13px',
              fontWeight: 600,
              cursor: creating || !newKeyName.trim() ? 'not-allowed' : 'pointer',
              whiteSpace: 'nowrap',
              width: isMobile ? '100%' : undefined,
            }}
          >
            {creating ? t('apiKeys.creating') : t('apiKeys.create')}
          </button>
        </div>

        {/* Newly created key — show once */}
        {justCreated && (
          <div style={{
            marginTop: '12px',
            padding: '12px',
            borderRadius: '8px',
            background: '#f0fdf4',
            border: '1px solid #bbf7d0',
          }}>
            <div style={{ fontSize: '12px', fontWeight: 600, color: '#166534', marginBottom: '6px' }}>
              {t('apiKeys.justCreatedNotice')}
            </div>
            <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
              <code style={{
                flex: 1,
                fontSize: '12px',
                fontFamily: 'monospace',
                background: '#fff',
                border: '1px solid #d1fae5',
                borderRadius: '4px',
                padding: '6px 8px',
                wordBreak: 'break-all',
                color: '#1a1a2e',
              }}>
                {justCreated.key}
              </code>
              <button
                onClick={handleCopy}
                style={{
                  padding: '6px 10px',
                  borderRadius: '6px',
                  border: '1px solid #d1d5db',
                  background: copied ? '#f0fdf4' : '#fff',
                  color: copied ? '#166534' : '#374151',
                  fontSize: '12px',
                  cursor: 'pointer',
                  whiteSpace: 'nowrap',
                  fontWeight: 600,
                  flexShrink: 0,
                  minWidth: '52px',
                  textAlign: 'center',
                }}
              >
                {copied ? '✓' : t('common.copy')}
              </button>
            </div>
            <div style={{ marginTop: '10px', fontSize: '12px', color: '#555' }}>
              {t('apiKeys.runCli')}
              <div style={{ display: 'flex', gap: '6px', alignItems: 'flex-start', marginTop: '4px' }}>
                <code style={{
                  flex: 1,
                  display: 'block',
                  padding: '6px 8px',
                  background: '#1a1a2e',
                  color: '#e0e0ff',
                  borderRadius: '4px',
                  fontFamily: 'monospace',
                  fontSize: '12px',
                  wordBreak: 'break-all',
                }}>
                  {`investibook init --api-host ${CLI_API_HOST} --api-key ${justCreated.key}`}
                </code>
                <button
                  onClick={() => {
                    navigator.clipboard.writeText(`investibook init --api-host ${CLI_API_HOST} --api-key ${justCreated.key}`).then(() => {
                      setCopiedInit(true);
                      setTimeout(() => setCopiedInit(false), 2000);
                    });
                  }}
                  style={{
                    padding: '6px 10px',
                    borderRadius: '6px',
                    border: '1px solid #d1d5db',
                    background: copiedInit ? '#f0fdf4' : '#fff',
                    color: copiedInit ? '#166534' : '#374151',
                    fontSize: '12px',
                    cursor: 'pointer',
                    whiteSpace: 'nowrap',
                    fontWeight: 600,
                    flexShrink: 0,
                    minWidth: '52px',
                    textAlign: 'center',
                  }}
                >
                  {copiedInit ? '✓' : t('common.copy')}
                </button>
              </div>
            </div>
            <div style={{ marginTop: '10px', fontSize: '12px', color: '#555' }}>
              {t('apiKeys.installOneCommand')}
              <div style={{ display: 'flex', gap: '6px', alignItems: 'flex-start', marginTop: '4px' }}>
                <code style={{
                  flex: 1,
                  display: 'block',
                  padding: '6px 8px',
                  background: '#1a1a2e',
                  color: '#e0e0ff',
                  borderRadius: '4px',
                  fontFamily: 'monospace',
                  fontSize: '12px',
                  wordBreak: 'break-all',
                  whiteSpace: 'pre-wrap',
                }}>
                  {`curl -fsSL "https://investibook-build.s3.amazonaws.com/install.sh" | bash -s -- --api-host ${CLI_API_HOST} --api-key ${justCreated.key}`}
                </code>
                <button
                  onClick={() => {
                    navigator.clipboard.writeText(`curl -fsSL "https://investibook-build.s3.amazonaws.com/install.sh" | bash -s -- --api-host ${CLI_API_HOST} --api-key ${justCreated.key}`).then(() => {
                      setCopiedInstall(true);
                      setTimeout(() => setCopiedInstall(false), 2000);
                    });
                  }}
                  style={{
                    padding: '6px 10px',
                    borderRadius: '6px',
                    border: '1px solid #d1d5db',
                    background: copiedInstall ? '#f0fdf4' : '#fff',
                    color: copiedInstall ? '#166534' : '#374151',
                    fontSize: '12px',
                    cursor: 'pointer',
                    whiteSpace: 'nowrap',
                    fontWeight: 600,
                    flexShrink: 0,
                    minWidth: '52px',
                    textAlign: 'center',
                  }}
                >
                  {copiedInstall ? '✓' : t('common.copy')}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Existing keys */}
      {loading ? (
        <div style={{ textAlign: 'center', padding: '24px 0', color: '#999', fontSize: '13px' }}>
          {t('common.loading')}
        </div>
      ) : keys.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '24px 0', color: '#aaa', fontSize: '13px' }}>
          {t('apiKeys.empty')}
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
          {keys.map(key => (
            <div
              key={key.id}
              style={{
                display: 'flex',
                flexDirection: isMobile ? 'column' : 'row',
                alignItems: isMobile ? 'flex-start' : 'center',
                justifyContent: 'space-between',
                padding: '12px 14px',
                gap: isMobile ? '8px' : undefined,
                border: '1px solid #e5e7eb',
                borderRadius: '8px',
                background: '#fff',
              }}
            >
              <div>
                <div style={{ fontSize: '13px', fontWeight: 600, color: '#1a1a2e' }}>
                  {key.name}
                </div>
                <div style={{ fontSize: '12px', color: '#9ca3af', marginTop: '2px' }}>
                  <code style={{ fontFamily: 'monospace' }}>{key.key_prefix}…</code>
                  {' · '}{t('apiKeys.created', { date: formatDate(key.created_at) })}
                  {key.last_used_at && ` · ${t('apiKeys.lastUsed', { date: formatDate(key.last_used_at) })}`}
                </div>
              </div>
              <button
                onClick={() => handleRevoke(key.id)}
                disabled={revokingId === key.id}
                style={{
                  padding: '5px 12px',
                  borderRadius: '6px',
                  border: '1px solid #fca5a5',
                  background: 'none',
                  color: revokingId === key.id ? '#9ca3af' : '#dc2626',
                  fontSize: '12px',
                  cursor: revokingId === key.id ? 'not-allowed' : 'pointer',
                  fontWeight: 600,
                  whiteSpace: 'nowrap',
                }}
                onMouseEnter={e => { if (revokingId !== key.id) e.currentTarget.style.background = '#fef2f2'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'none'; }}
              >
                {revokingId === key.id ? t('apiKeys.revoking') : t('apiKeys.revoke')}
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
