'use client';

import type { Id } from '@spoon/backend/convex/_generated/dataModel.js';
import { Checkbox, Label } from '@spoon/ui';

type Secret = {
  _id: Id<'spoonSecrets'>;
  name: string;
  valuePreview?: string;
  description?: string;
};

export const SecretSelector = ({
  secrets,
  selectedSecretIds,
  onChange,
}: {
  secrets: Secret[];
  selectedSecretIds: Id<'spoonSecrets'>[];
  onChange: (secretIds: Id<'spoonSecrets'>[]) => void;
}) => {
  const toggle = (secretId: Id<'spoonSecrets'>, checked: boolean) => {
    onChange(
      checked
        ? [...selectedSecretIds, secretId]
        : selectedSecretIds.filter((id) => id !== secretId),
    );
  };

  if (!secrets.length) {
    return (
      <p className='text-muted-foreground text-sm'>
        No Spoon secrets saved. Add project secrets in Settings when a job needs
        environment variables.
      </p>
    );
  }

  return (
    <div className='grid gap-2'>
      {secrets.map((secret) => (
        <label
          key={secret._id}
          className='border-border flex items-start gap-3 rounded-md border p-3'
        >
          <Checkbox
            checked={selectedSecretIds.includes(secret._id)}
            onCheckedChange={(checked) => toggle(secret._id, checked === true)}
          />
          <span className='grid gap-1'>
            <Label className='font-mono text-xs'>{secret.name}</Label>
            <span className='text-muted-foreground text-xs'>
              {secret.description ?? secret.valuePreview ?? 'Configured'}
            </span>
          </span>
        </label>
      ))}
    </div>
  );
};
