import { useRef, type ReactNode } from 'react';
import { SectionHeader, Input, MonoText, Button } from '@cameleer/design-system';
import type { App, AppVersion } from '../../../api/queries/admin/apps';
import type { Environment } from '../../../api/queries/admin/environments';
import { envColorVar } from '../../../components/env-colors';
import styles from './AppDeploymentPage.module.css';

function slugify(name: string): string {
  return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').substring(0, 100);
}

function formatBytes(bytes: number): string {
  if (bytes >= 1_048_576) return `${(bytes / 1_048_576).toFixed(1)} MB`;
  if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${bytes} B`;
}

interface IdentitySectionProps {
  mode: 'net-new' | 'deployed';
  environment: Environment;
  app: App | null;
  currentVersion: AppVersion | null;
  name: string;
  onNameChange: (next: string) => void;
  stagedJar: File | null;
  onStagedJarChange: (file: File | null) => void;
  deploying: boolean;
  checkpointsSlot?: ReactNode;
  children?: ReactNode;
}

export function IdentitySection({
  mode, environment, app, currentVersion,
  name, onNameChange, stagedJar, onStagedJarChange, deploying,
  checkpointsSlot, children,
}: IdentitySectionProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const slug = app?.slug ?? slugify(name);

  const externalUrl = (() => {
    const defaults = environment.defaultContainerConfig ?? {};
    const domain = String(defaults.routingDomain ?? '');
    if (defaults.routingMode === 'subdomain' && domain) {
      return `https://${slug || '...'}-${environment.slug}.${domain}/`;
    }
    const base = domain ? `https://${domain}` : window.location.origin;
    return `${base}/${environment.slug}/${slug || '...'}/`;
  })();

  return (
    <div className={styles.section}>
      <SectionHeader>Identity & Artifact</SectionHeader>
      <div className={styles.configGrid}>
        <span className={styles.configLabel}>Application Name</span>
        {mode === 'deployed' ? (
          <span className={styles.readOnlyValue}>{name}</span>
        ) : (
          <Input
            value={name}
            onChange={(e) => onNameChange(e.target.value)}
            placeholder="e.g. Payment Gateway"
            disabled={deploying}
          />
        )}

        <span className={styles.configLabel}>Slug</span>
        <MonoText size="sm">{slug || '...'}</MonoText>

        <span className={styles.configLabel}>Environment</span>
        <span
          className={styles.envPill}
          style={{ backgroundColor: envColorVar(environment.color) }}
          title={environment.displayName}
        >
          {environment.displayName}
        </span>

        <span className={styles.configLabel}>External URL</span>
        <MonoText size="sm">{externalUrl}</MonoText>

        {currentVersion && (
          <>
            <span className={styles.configLabel}>Current Version</span>
            <span className={styles.readOnlyValue}>
              v{currentVersion.version} · {currentVersion.jarFilename} · {formatBytes(currentVersion.jarSizeBytes)}
            </span>
          </>
        )}

        <span className={styles.configLabel}>Application JAR</span>
        <div className={styles.fileRow}>
          <input
            ref={fileInputRef}
            type="file"
            accept=".jar"
            className={styles.visuallyHidden}
            onChange={(e) => onStagedJarChange(e.target.files?.[0] ?? null)}
          />
          <Button
            size="sm"
            variant="secondary"
            type="button"
            onClick={() => fileInputRef.current?.click()}
            disabled={deploying}
          >
            {currentVersion ? 'Change JAR' : 'Select JAR'}
          </Button>
          {stagedJar && (
            <span className={styles.stagedJar}>
              staged: {stagedJar.name} ({formatBytes(stagedJar.size)})
            </span>
          )}
        </div>

        {checkpointsSlot}
      </div>
      {children}
    </div>
  );
}
