import { useTranslation } from 'react-i18next';
import { HelpText } from './HelpText';
import { EnvOverrideWarning, FieldLabel, FieldInput } from './formUtils';
import type { SectionFormProps } from './types';

/**
 * Paths & Storage — config v2 `storage.*` block.
 *
 * Reads from the new `storage.*` keys emitted by `GET /api/config` (after
 * #360 normalization + #362 v2 API shape). Old flat keys (`worktreeDir` etc.)
 * are rejected by `PUT /api/config` since v2, so this form only writes
 * `storage.*`.
 */
export function PathsStorageForm({ config, onChange, overriddenByEnv }: SectionFormProps) {
  const { t } = useTranslation('settings');
  const storage = config.storage ?? {};

  return (
    <div className="space-y-5">
      <h2 className="text-base font-semibold text-slate-800">Paths &amp; Storage</h2>
      <HelpText>
        {t('pathsStorage.intro')}
      </HelpText>

      <div>
        <FieldLabel>Worktree Directory</FieldLabel>
        <FieldInput
          value={storage.worktreeDir ?? ''}
          onChange={v => onChange('storage.worktreeDir', v || undefined)}
          disabled={!!overriddenByEnv['storage.worktreeDir'] || !!overriddenByEnv['worktreeDir']}
          disabledReason={t('pathsStorage.worktreeOverride')}
        />
        {(overriddenByEnv['storage.worktreeDir'] || overriddenByEnv['worktreeDir']) && <EnvOverrideWarning />}
        <HelpText>{t('pathsStorage.worktreeHelp')}</HelpText>
      </div>

      <div>
        <FieldLabel>Custom Pieces Directory</FieldLabel>
        <FieldInput
          value={storage.customPiecesDir ?? ''}
          onChange={v => onChange('storage.customPiecesDir', v || undefined)}
          placeholder="/path/to/your/custom-pieces"
        />
        <HelpText>{t('pathsStorage.customPiecesHelp')}</HelpText>
      </div>

      <div>
        <FieldLabel>User Folder Root</FieldLabel>
        <FieldInput
          value={storage.userFolderRoot ?? ''}
          onChange={v => onChange('storage.userFolderRoot', v || undefined)}
          placeholder="./data/users"
        />
        <HelpText>{t('pathsStorage.userFolderHelp')}</HelpText>
      </div>

      <div>
        <FieldLabel>{t('pathsStorage.taskUploadLabel')}</FieldLabel>
        <FieldInput
          type="number"
          value={storage.taskUploadMaxSizeMb ?? 50}
          onChange={v => onChange('storage.taskUploadMaxSizeMb', v ? Number(v) : undefined)}
        />
        <HelpText>
          {t('pathsStorage.taskUploadHelp')}
        </HelpText>
      </div>

      <div>
        <FieldLabel>{t('pathsStorage.trashLabel')}</FieldLabel>
        <FieldInput
          type="number"
          value={storage.trashRetentionDays ?? 30}
          onChange={v => onChange('storage.trashRetentionDays', v ? Number(v) : undefined)}
        />
        <HelpText>
          {t('pathsStorage.trashHelp')}
        </HelpText>
      </div>
    </div>
  );
}
