import type { Deployment, AppVersion } from '../../../../api/queries/admin/apps';
import { DeploymentProgress } from '../../../../components/DeploymentProgress';
import { StartupLogPanel } from '../../../../components/StartupLogPanel';
import { EmptyState } from '@cameleer/design-system';
import { StatusCard } from './StatusCard';
import styles from '../AppDeploymentPage.module.css';

interface Props {
  deployments: Deployment[];
  versions: AppVersion[];
  appSlug: string;
  envSlug: string;
  externalUrl: string;
}

export function DeploymentTab({ deployments, versions, appSlug, envSlug, externalUrl }: Props) {
  const latest = deployments
    .slice()
    .sort((a, b) => (b.createdAt ?? '').localeCompare(a.createdAt ?? ''))[0] ?? null;

  if (!latest) {
    return <EmptyState title="No deployments yet" description="Save your configuration and click Redeploy to launch." />;
  }

  const version = versions.find((v) => v.id === latest.appVersionId) ?? null;

  return (
    <div className={styles.deploymentTab}>
      <StatusCard
        deployment={latest}
        version={version}
        externalUrl={externalUrl}
      />
      {latest.status === 'STARTING' && (
        <DeploymentProgress currentStage={latest.deployStage} failed={false} />
      )}
      {latest.status === 'FAILED' && (
        <DeploymentProgress currentStage={latest.deployStage} failed />
      )}
      <StartupLogPanel deployment={latest} appSlug={appSlug} envSlug={envSlug}
                       className={styles.logFill} />
    </div>
  );
}
