import { useState } from 'react';
import { SideDrawer } from '../../../../components/SideDrawer';
import { Tabs, Button, Badge } from '@cameleer/design-system';
import type { Deployment, AppVersion } from '../../../../api/queries/admin/apps';
import type { DeploymentPageFormState } from '../hooks/useDeploymentPageState';
import { LogsPanel } from './LogsPanel';
import { ConfigPanel } from './ConfigPanel';
import { timeAgo } from '../../../../utils/format-utils';
import styles from './CheckpointDetailDrawer.module.css';

interface Props {
  open: boolean;
  onClose: () => void;
  deployment: Deployment;
  version?: AppVersion;
  appSlug: string;
  envSlug: string;
  onRestore: (deploymentId: string) => void;
  currentForm?: DeploymentPageFormState;
}

type TabId = 'logs' | 'config';

export function CheckpointDetailDrawer({
  open, onClose, deployment, version, appSlug, envSlug, onRestore, currentForm,
}: Props) {
  const [tab, setTab] = useState<TabId>('config');
  const archived = !version;

  const title = (
    <div className={styles.titleRow}>
      <Badge label={version ? `v${version.version}` : '?'} color="auto" />
      <span className={styles.titleJar}>
        {version?.jarFilename ?? 'JAR pruned'}
      </span>
      <span className={styles.statusPill}>
        {deployment.status}
      </span>
    </div>
  );

  const footer = (
    <div className={styles.footerRow}>
      <span className={styles.footerHint}>
        Restoring hydrates the form — you'll still need to Redeploy.
      </span>
      <Button
        variant="primary"
        disabled={archived}
        title={archived ? 'JAR was pruned by the environment retention policy' : undefined}
        onClick={() => { onRestore(deployment.id); onClose(); }}
      >
        Restore this checkpoint
      </Button>
    </div>
  );

  return (
    <SideDrawer open={open} onClose={onClose} title={title} size="lg" footer={footer}>
      <div className={styles.metaLine}>
        Deployed by <b>{deployment.createdBy ?? '—'}</b>
        {deployment.deployedAt && <> · {timeAgo(deployment.deployedAt)} ({deployment.deployedAt})</>}
        {' · '}Strategy: {deployment.deploymentStrategy === 'BLUE_GREEN' ? 'blue/green' : 'rolling'}
        {' · '}{deployment.replicaStates.length} replicas
      </div>
      <Tabs
        active={tab}
        onChange={(t) => setTab(t as TabId)}
        tabs={[
          { value: 'config', label: 'Config' },
          { value: 'logs', label: 'Logs' },
        ]}
      />
      <div className={styles.tabContent}>
        {tab === 'logs' && (
          <LogsPanel deployment={deployment} appSlug={appSlug} envSlug={envSlug} />
        )}
        {tab === 'config' && (
          <ConfigPanel deployment={deployment} appSlug={appSlug} envSlug={envSlug} archived={archived} currentForm={currentForm} />
        )}
      </div>
    </SideDrawer>
  );
}
