import { useState } from 'react';
import { useTranslation } from 'react-i18next';

interface CreateInput {
  team: string;
  allowedModels?: string[];
  tokensBudget?: number | null;
  rateLimitRpm?: number | null;
}

interface Props {
  onCancel: () => void;
  onSubmit: (input: CreateInput) => Promise<void>;
  submitting?: boolean;
  error?: string | null;
}

/**
 * Modal for issuing a new gateway virtual key. The team field is
 * required; allowed_models / tokens_budget / rate_limit_rpm are
 * optional and empty = "no limit".
 *
 * After submit succeeds the parent shows the GatewayKeyRawKeyDialog
 * with the raw bearer; this dialog never displays it.
 */
export function GatewayKeyCreateDialog({ onCancel, onSubmit, submitting, error }: Props) {
  const { t } = useTranslation('settings');
  const [team, setTeam] = useState('');
  const [allowedModelsText, setAllowedModelsText] = useState('');
  const [tokensBudgetText, setTokensBudgetText] = useState('');
  const [rateLimitRpmText, setRateLimitRpmText] = useState('');

  function buildPayload(): CreateInput | { error: string } {
    const t = team.trim();
    if (!/^[a-zA-Z0-9._-]{1,64}$/.test(t)) {
      return { error: 'team must match /^[a-zA-Z0-9._-]{1,64}$/' };
    }
    const allowedModels = allowedModelsText
      .split(/[\n,]/)
      .map(s => s.trim())
      .filter(s => s.length > 0);
    const tokensBudget = tokensBudgetText.trim() === '' ? null : Number(tokensBudgetText);
    const rateLimitRpm = rateLimitRpmText.trim() === '' ? null : Number(rateLimitRpmText);
    if (tokensBudget !== null && (!Number.isFinite(tokensBudget) || tokensBudget <= 0)) {
      return { error: 'tokens budget must be a positive integer' };
    }
    if (rateLimitRpm !== null && (!Number.isFinite(rateLimitRpm) || rateLimitRpm <= 0)) {
      return { error: 'rate limit (rpm) must be a positive integer' };
    }
    return {
      team: t,
      allowedModels: allowedModels.length > 0 ? allowedModels : undefined,
      tokensBudget,
      rateLimitRpm,
    };
  }

  const [localError, setLocalError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLocalError(null);
    const payload = buildPayload();
    if ('error' in payload) {
      setLocalError(payload.error);
      return;
    }
    await onSubmit(payload);
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <form
        onSubmit={handleSubmit}
        className="bg-surface rounded-lg shadow-xl max-w-md w-full mx-4 p-6"
      >
        <h3 className="text-lg font-semibold text-slate-800 mb-4">{t('gateway.createDialog.title')}</h3>

        <label className="block text-xs font-medium text-slate-600 mb-1">
          team <span className="text-red-600">*</span>
        </label>
        <input
          type="text"
          value={team}
          onChange={(e) => setTeam(e.target.value)}
          placeholder="alpha"
          autoFocus
          required
          className="w-full px-2 py-1.5 text-sm border border-slate-300 rounded mb-3"
        />

        <label className="block text-xs font-medium text-slate-600 mb-1">
          {t('gateway.createDialog.allowedModelsLabel')}
        </label>
        <textarea
          value={allowedModelsText}
          onChange={(e) => setAllowedModelsText(e.target.value)}
          placeholder="qwen3:8b&#10;qwen3:14b"
          rows={2}
          className="w-full px-2 py-1.5 text-sm border border-slate-300 rounded mb-3 font-mono"
        />

        <div className="grid grid-cols-2 gap-3 mb-3">
          <div>
            <label className="block text-xs font-medium text-slate-600 mb-1">
              Tokens budget / month
            </label>
            <input
              type="number"
              min="1"
              value={tokensBudgetText}
              onChange={(e) => setTokensBudgetText(e.target.value)}
              placeholder={t('gateway.createDialog.unlimited')}
              className="w-full px-2 py-1.5 text-sm border border-slate-300 rounded"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-slate-600 mb-1">
              Rate limit (rpm)
            </label>
            <input
              type="number"
              min="1"
              value={rateLimitRpmText}
              onChange={(e) => setRateLimitRpmText(e.target.value)}
              placeholder={t('gateway.createDialog.unlimited')}
              className="w-full px-2 py-1.5 text-sm border border-slate-300 rounded"
            />
          </div>
        </div>

        {(localError || error) && (
          <div className="text-sm text-red-600 mb-3">{localError ?? error}</div>
        )}

        <div className="flex justify-end gap-2 mt-4">
          <button
            type="button"
            onClick={onCancel}
            disabled={submitting}
            className="px-3 py-1.5 text-sm rounded border border-slate-300 hover:bg-slate-50 disabled:opacity-40"
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={submitting}
            className="px-3 py-1.5 text-sm rounded bg-accent text-white hover:bg-accent-strong disabled:opacity-50"
          >
            {submitting ? t('gateway.createDialog.issuing') : t('gateway.createDialog.issue')}
          </button>
        </div>
      </form>
    </div>
  );
}
