import { useMemo, useState } from 'react';
import { Select } from '@cameleer/design-system';
import { useInfiniteApplicationLogs } from '../../../../api/queries/logs';
import type { Deployment } from '../../../../api/queries/admin/apps';
import { instanceIdsFor } from './instance-id';
import styles from './CheckpointDetailDrawer.module.css';

interface Props {
  deployment: Deployment;
  appSlug: string;
  envSlug: string;
}

export function LogsPanel({ deployment, appSlug, envSlug }: Props) {
  const allInstanceIds = useMemo(
    () => instanceIdsFor(deployment, envSlug, appSlug),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [deployment.id, deployment.replicaStates, envSlug, appSlug]
  );

  const [replicaFilter, setReplicaFilter] = useState<'all' | number>('all');
  const filteredInstanceIds = replicaFilter === 'all'
    ? allInstanceIds
    : allInstanceIds.filter((_, i) => i === replicaFilter);

  const logs = useInfiniteApplicationLogs({
    application: appSlug,
    instanceIds: filteredInstanceIds,
    isAtTop: true,
  });

  const replicaOptions = [
    { value: 'all', label: `all (${deployment.replicaStates.length})` },
    ...deployment.replicaStates.map((_, i) => ({ value: String(i), label: String(i) })),
  ];

  return (
    <div>
      <div className={styles.filterBar}>
        <label className={styles.replicaLabel}>
          <span>Replica:</span>
          <Select
            value={String(replicaFilter)}
            onChange={(e) => {
              const v = e.target.value;
              setReplicaFilter(v === 'all' ? 'all' : Number(v));
            }}
            options={replicaOptions}
          />
        </label>
      </div>
      {logs.items.length === 0 && !logs.isLoading && (
        <div className={styles.emptyState}>No logs for this deployment.</div>
      )}
      {logs.items.map((entry, i) => (
        <div key={i} className={styles.logRow}>
          <span className={styles.logTimestamp}>{entry.timestamp}</span>{' '}
          <span>[{entry.level}]</span>{' '}
          <span>{entry.message}</span>
        </div>
      ))}
    </div>
  );
}
