import React, { useState } from 'react';

interface SpawnInstanceFormProps {
  api: any;
  onSuccess: (port: number) => void;
  onError: (msg: string) => void;
}

interface SpawnFormState {
  name: string;
  code: string;
  contact_email: string;
  max_students: number;
  term_name: string;
  port_server: number;
  port_client: number;
}

const INITIAL: SpawnFormState = {
  name: '',
  code: '',
  contact_email: '',
  max_students: 1000,
  term_name: 'Term 1',
  port_server: 3010,
  port_client: 5180,
};

export function SpawnInstanceForm({ api, onSuccess, onError }: SpawnInstanceFormProps) {
  const [form, setForm] = useState<SpawnFormState>(INITIAL);
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      await api.post('/instances/spawn', form);
      onSuccess(form.port_server);
    } catch (err: any) {
      onError(err.response?.data?.error || err.message || 'Instance spawning failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <Field label="School Name" required>
        <input
          type="text"
          required
          value={form.name}
          onChange={e => setForm({ ...form, name: e.target.value })}
          placeholder="e.g. Churchill Boys High School"
          className="form-input text-xs font-mono"
        />
      </Field>
      <div className="grid grid-cols-2 gap-3">
        <Field label="Server Port">
          <input
            type="number"
            min={1}
            value={form.port_server}
            onChange={e => setForm({ ...form, port_server: parseInt(e.target.value, 10) || 0 })}
            className="form-input text-xs font-mono"
          />
        </Field>
        <Field label="Client Port">
          <input
            type="number"
            min={1}
            value={form.port_client}
            onChange={e => setForm({ ...form, port_client: parseInt(e.target.value, 10) || 0 })}
            className="form-input text-xs font-mono"
          />
        </Field>
      </div>
      <button
        type="submit"
        disabled={submitting}
        className="w-full py-3 bg-primary hover:bg-primary-dark text-white font-bold text-xs uppercase tracking-wider rounded-xl transition-all mt-4 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        {submitting ? 'Provisioning…' : 'Provision & Boot Instance'}
      </button>
    </form>
  );
}

function Field({ label, required, children }: { label: string; required?: boolean; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-bold uppercase tracking-wider text-muted-foreground mb-1">
        {label}
        {required && <span className="text-rose-500 ml-1">*</span>}
      </label>
      {children}
    </div>
  );
}

export default SpawnInstanceForm;
