import { useMemo } from 'react';
import { useNavigate } from 'react-router';
import {
  Badge,
  Button,
  DataTable,
  StatusDot,
} from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { useEnvironmentStore } from '../../api/environment-store';
import { useEnvironments } from '../../api/queries/admin/environments';
import { useApps } from '../../api/queries/admin/apps';
import type { App } from '../../api/queries/admin/apps';
import type { Environment } from '../../api/queries/admin/environments';
import { useCatalog } from '../../api/queries/catalog';
import type { CatalogApp } from '../../api/queries/catalog';
import { PageLoader } from '../../components/PageLoader';
import { timeAgo } from '../../utils/format-utils';
import styles from './AppsTab.module.css';

const STATUS_COLORS: Record<string, 'success' | 'warning' | 'error' | 'auto' | 'running'> = {
  RUNNING: 'running', STARTING: 'warning', FAILED: 'error', STOPPED: 'auto',
  DEGRADED: 'warning', STOPPING: 'auto',
};

const DEPLOY_STATUS_DOT: Record<string, 'live' | 'stale' | 'dead' | 'success' | 'warning' | 'error' | 'running'> = {
  RUNNING: 'live', STARTING: 'running', DEGRADED: 'stale',
  STOPPING: 'stale', STOPPED: 'dead', FAILED: 'error',
};

export default function AppsTab() {
  const selectedEnv = useEnvironmentStore((s) => s.environment);
  const { data: environments = [] } = useEnvironments();
  return <AppListView selectedEnv={selectedEnv} environments={environments} />;
}

// ═══════════════════════════════════════════════════════════════════
//  LIST VIEW
// ═══════════════════════════════════════════════════════════════════

function AppListView({ selectedEnv, environments }: { selectedEnv: string | undefined; environments: Environment[] }) {
  const navigate = useNavigate();
  const { data: envApps = [], isLoading: envLoading } = useApps(selectedEnv);
  const { data: catalog = [] } = useCatalog(selectedEnv);

  // Apps are env-scoped; without an env selection there is no managed-app list
  // to show. The Runtime tab (catalog) is the cross-env discovery surface.
  const apps = selectedEnv ? envApps : [];
  const isLoading = selectedEnv ? envLoading : false;

  const envMap = useMemo(() => new Map(environments.map((e) => [e.id, e])), [environments]);

  // Build slug → deployment status map from catalog
  const deployStatusMap = useMemo(() => {
    const map = new Map<string, string>();
    for (const app of catalog as CatalogApp[]) {
      if (app.deployment) map.set(app.slug, app.deployment.status);
    }
    return map;
  }, [catalog]);

  type AppRow = App & { id: string; envName: string };
  const rows: AppRow[] = useMemo(
    () => apps.map((a) => ({ ...a, envName: envMap.get(a.environmentId)?.displayName ?? '?' })),
    [apps, envMap],
  );

  const columns: Column<AppRow>[] = useMemo(() => [
    { key: 'displayName', header: 'Name', sortable: true,
      render: (_v: unknown, row: AppRow) => (
        <div><div className={styles.cellName}>{row.displayName}</div><div className={styles.cellMeta}>{row.slug}</div></div>
      ),
    },
    ...(!selectedEnv ? [{ key: 'envName', header: 'Environment', sortable: true,
      render: (_v: unknown, row: AppRow) => <Badge label={row.envName} color={'auto' as const} />,
    }] : []),
    { key: 'slug', header: 'Status', sortable: false,
      render: (_v: unknown, row: AppRow) => {
        const status = deployStatusMap.get(row.slug);
        if (!status) return <span className={styles.cellMeta}>—</span>;
        const dotVariant = DEPLOY_STATUS_DOT[status] ?? 'dead';
        const badgeColor = STATUS_COLORS[status] ?? 'auto';
        return (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <StatusDot variant={dotVariant} />
            <Badge label={status} color={badgeColor} />
          </span>
        );
      },
    },
    { key: 'updatedAt', header: 'Updated', sortable: true,
      render: (_v: unknown, row: AppRow) => <span className={styles.cellMeta}>{timeAgo(row.updatedAt)}</span>,
    },
    { key: 'createdAt', header: 'Created', sortable: true,
      render: (_v: unknown, row: AppRow) => <span className={styles.cellMeta}>{new Date(row.createdAt).toLocaleDateString()}</span>,
    },
  ], [selectedEnv, deployStatusMap]);

  if (isLoading) return <PageLoader />;

  return (
    <div className={styles.container}>
      <div className={styles.toolbar}>
        <Button size="sm" variant="primary" onClick={() => navigate('/apps/new')}>+ Create App</Button>
      </div>
      <DataTable columns={columns} data={rows} onRowClick={(row) => navigate(`/apps/${row.slug}`)} />
    </div>
  );
}
