import { useState } from 'react';
import type { UseFormRegister, FieldError } from 'react-hook-form';
import { PasswordField } from '../ui/PasswordField';

type AuthMethod = 'sas' | 'key';

interface AzureAuthToggleProps {
  register: UseFormRegister<any>;
  errors: {
    key?: FieldError;
    sas_url?: FieldError;
  };
}

export function AzureAuthToggle({ register, errors }: AzureAuthToggleProps) {
  const [authMethod, setAuthMethod] = useState<AuthMethod>('sas');

  return (
    <div className="flex flex-col gap-3">
      {/* Segmented control */}
      <div className="flex rounded-md border border-gray-300 overflow-hidden">
        <button
          type="button"
          onClick={() => setAuthMethod('sas')}
          className={[
            'flex-1 py-1.5 text-sm font-medium transition-colors',
            authMethod === 'sas'
              ? 'bg-blue-600 text-white'
              : 'bg-white text-gray-700 hover:bg-gray-50',
          ].join(' ')}
        >
          SAS URL
        </button>
        <button
          type="button"
          onClick={() => setAuthMethod('key')}
          className={[
            'flex-1 py-1.5 text-sm font-medium transition-colors',
            authMethod === 'key'
              ? 'bg-blue-600 text-white'
              : 'bg-white text-gray-700 hover:bg-gray-50',
          ].join(' ')}
        >
          Access Key
        </button>
      </div>

      {/* Both fields always registered — only active one visible via CSS */}
      <div className={authMethod === 'sas' ? 'block' : 'hidden'}>
        <PasswordField
          id="sas_url"
          label="SAS URL"
          error={errors.sas_url}
          registration={register('sas_url')}
          placeholder="https://mystorageaccount.blob.core.windows.net/?sv=..."
          helpText="Full SAS URL including account and container"
        />
      </div>
      <div className={authMethod === 'key' ? 'block' : 'hidden'}>
        <PasswordField
          id="key"
          label="Access Key"
          error={errors.key}
          registration={register('key')}
          helpText="Base64-encoded storage account key"
        />
      </div>
    </div>
  );
}
