import { Button } from '@cameleer/design-system';
import styles from './AppDeploymentPage.module.css';

export type PrimaryActionMode = 'save' | 'redeploy' | 'uploading' | 'deploying';

interface Props {
  mode: PrimaryActionMode;
  enabled: boolean;
  onClick: () => void;
  /** Upload percentage 0–100. Only meaningful when mode === 'uploading'. */
  progress?: number;
}

export function PrimaryActionButton({ mode, enabled, onClick, progress }: Props) {
  if (mode === 'uploading') {
    const pct = Math.max(0, Math.min(100, Math.round(progress ?? 0)));
    return (
      <span className={styles.uploadBtnWrap}>
        <Button size="sm" variant="primary" disabled>
          <span
            data-upload-fill
            className={styles.uploadBtnFill}
            style={{ width: `${pct}%` }}
          />
          <span className={styles.uploadBtnLabel}>Uploading… {pct}%</span>
        </Button>
      </span>
    );
  }
  if (mode === 'deploying') {
    return <Button size="sm" variant="primary" loading disabled>Deploying…</Button>;
  }
  if (mode === 'redeploy') {
    return <Button size="sm" variant="primary" disabled={!enabled} onClick={onClick}>Redeploy</Button>;
  }
  return <Button size="sm" variant="primary" disabled={!enabled} onClick={onClick}>Save</Button>;
}

export function computeMode({
  deploymentInProgress,
  uploading,
  hasLocalEdits,
  serverDirtyAgainstDeploy,
}: {
  deploymentInProgress: boolean;
  uploading: boolean;
  hasLocalEdits: boolean;
  serverDirtyAgainstDeploy: boolean;
}): PrimaryActionMode {
  if (deploymentInProgress) return 'deploying';
  if (uploading) return 'uploading';
  if (hasLocalEdits) return 'save';
  if (serverDirtyAgainstDeploy) return 'redeploy';
  return 'save';
}
