import { FormEvent, useCallback, useEffect, useState } from 'react';
import Layout from '../../components/Layout';
import { api } from '../../lib/api';
import { useRequireAuth } from '../../lib/auth-context';

interface ApiKeyRow {
  id: string;
  name: string;
  keyPrefix: string;
  scopes: string[];
  expiresAt: string | null;
  lastUsedAt: string | null;
  revokedAt: string | null;
  createdAt: string;
}

const ALL_SCOPES = ['jobs:read', 'jobs:write', 'points:read', 'points:write', 'devices:read'];

export default function ApiKeysPage() {
  const { user, activeOrg, loading } = useRequireAuth();
  const orgId = activeOrg?.org.id ?? null;
  const isAdmin = activeOrg?.role === 'ORG_ADMIN';

  const [keys, setKeys] = useState<ApiKeyRow[]>([]);
  const [name, setName] = useState('');
  const [scopes, setScopes] = useState<string[]>(['jobs:read', 'points:read']);
  const [createdKey, setCreatedKey] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const reload = useCallback(() => {
    if (!orgId || !isAdmin) {
      return;
    }
    api
      .get<ApiKeyRow[]>(`/api/orgs/${orgId}/api-keys`)
      .then((rows) => {
        setKeys(rows);
        setError(null);
      })
      .catch((err) => setError(err.message));
  }, [orgId, isAdmin]);

  useEffect(reload, [reload]);

  const toggleScope = (scope: string) =>
    setScopes((s) => (s.includes(scope) ? s.filter((x) => x !== scope) : [...s, scope]));

  const createKey = async (e: FormEvent) => {
    e.preventDefault();
    try {
      const created = await api.post<ApiKeyRow & { key: string }>(`/api/orgs/${orgId}/api-keys`, { name, scopes });
      setCreatedKey(created.key);
      setName('');
      reload();
    } catch (err: any) {
      setError(err.message);
    }
  };

  const revoke = async (keyId: string) => {
    try {
      await api.delete(`/api/orgs/${orgId}/api-keys/${keyId}`);
      reload();
    } catch (err: any) {
      setError(err.message);
    }
  };

  if (loading || !user) {
    return null;
  }

  if (!isAdmin) {
    return (
      <Layout title="API Keys">
        <h1>API Keys</h1>
        <p>Only organization admins can manage API keys.</p>
      </Layout>
    );
  }

  return (
    <Layout title="API Keys">
      <h1>API Keys</h1>
      <p style={{ color: '#666' }}>
        Send keys in the <code>X-API-Key</code> header. Access is limited to this organization and the selected scopes.
      </p>
      {error && <p style={{ color: '#c62828' }}>{error}</p>}

      {createdKey && (
        <div style={{ background: '#e8f5e9', border: '1px solid #388e3c', borderRadius: 6, padding: '1rem', margin: '1rem 0' }}>
          <strong>Copy this key now — it will not be shown again:</strong>
          <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginTop: '0.5rem' }}>
            <code style={{ wordBreak: 'break-all' }}>{createdKey}</code>
            <button onClick={() => navigator.clipboard.writeText(createdKey)}>Copy</button>
            <button onClick={() => setCreatedKey(null)}>Dismiss</button>
          </div>
        </div>
      )}

      <form onSubmit={createKey} style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap', marginBottom: '1.5rem' }}>
        <input
          placeholder="key name (e.g. GIS export)"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
          style={{ padding: '0.4rem', width: 220 }}
        />
        {ALL_SCOPES.map((scope) => (
          <label key={scope} style={{ whiteSpace: 'nowrap' }}>
            <input type="checkbox" checked={scopes.includes(scope)} onChange={() => toggleScope(scope)} /> {scope}
          </label>
        ))}
        <button type="submit" disabled={scopes.length === 0}>
          Create key
        </button>
      </form>

      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr style={{ textAlign: 'left', borderBottom: '2px solid #ddd' }}>
            <th style={{ padding: '0.5rem' }}>Name</th>
            <th>Prefix</th>
            <th>Scopes</th>
            <th>Last used</th>
            <th>Status</th>
            <th />
          </tr>
        </thead>
        <tbody>
          {keys.map((k) => (
            <tr key={k.id} style={{ borderBottom: '1px solid #eee' }}>
              <td style={{ padding: '0.5rem' }}>{k.name}</td>
              <td>
                <code>{k.keyPrefix}…</code>
              </td>
              <td>{k.scopes.join(', ')}</td>
              <td>{k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleString() : 'never'}</td>
              <td style={{ color: k.revokedAt ? '#c62828' : '#388e3c' }}>{k.revokedAt ? 'revoked' : 'active'}</td>
              <td style={{ textAlign: 'right' }}>
                {!k.revokedAt && <button onClick={() => revoke(k.id)}>Revoke</button>}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </Layout>
  );
}
