/**
 * API Keys tab — list of stored keys with usage telemetry.
 *
 * Backend redacts the key value to a prefix; frontend never sees the full key
 * after creation. Edit dialog requires re-entering it if rotation is needed.
 */
import React from 'react';
import {
  Box, TableContainer, Table, TableHead, TableBody, TableRow, TableCell,
  Button, Chip, IconButton, Switch,
} from '@mui/material';
import { Add as AddIcon, Edit as EditIcon, Delete as DeleteIcon } from '@mui/icons-material';
import type { ApiKey } from '../ProvidersManagement.types';

interface Props {
  apiKeys: ApiKey[];
  hasProviders: boolean;
  onAdd: () => void;
  onEdit: (k: ApiKey) => void;
  onDelete: (k: ApiKey) => void;
  onToggleActive: (k: ApiKey) => void;
}

export const ApiKeysTab: React.FC<Props> = ({ apiKeys, hasProviders, onAdd, onEdit, onDelete, onToggleActive }) => (
  <>
    <Box display="flex" justifyContent="flex-end" mb={2}>
      <Button variant="contained" startIcon={<AddIcon />} onClick={onAdd} disabled={!hasProviders}>
        Add API Key
      </Button>
    </Box>
    <TableContainer>
      <Table size="small">
        <TableHead>
          <TableRow>
            <TableCell>Key Name</TableCell>
            <TableCell>Provider</TableCell>
            <TableCell>Prefix</TableCell>
            <TableCell>Usage</TableCell>
            <TableCell>Last Used</TableCell>
            <TableCell>Active</TableCell>
            <TableCell>Actions</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {apiKeys.map((k) => (
            <TableRow key={k.api_key_id} hover>
              <TableCell><strong>{k.key_name}</strong></TableCell>
              <TableCell><Chip label={k.provider_code} size="small" /></TableCell>
              <TableCell><code>{k.key_prefix}...</code></TableCell>
              <TableCell>{k.usage_count} calls</TableCell>
              <TableCell>{k.last_used_at ? new Date(k.last_used_at).toLocaleDateString() : 'Never'}</TableCell>
              <TableCell>
                <Switch checked={k.is_active} onChange={() => onToggleActive(k)} size="small" />
              </TableCell>
              <TableCell>
                <IconButton size="small" onClick={() => onEdit(k)}><EditIcon /></IconButton>
                <IconButton size="small" onClick={() => onDelete(k)} color="error"><DeleteIcon /></IconButton>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  </>
);
