import React, { useState } from 'react';

interface OverrideFormProps {
  api: any;
  tenant: any;
  onSuccess: (message: string) => void;
  onError: (msg: string) => void;
}

interface OverrideFormState {
  reason: string;
  extension_days: number;
}

const INITIAL: OverrideFormState = {
  reason: '',
  extension_days: 14,
};

export function OverrideForm({ api, tenant, onSuccess, onError }: OverrideFormProps) {
  const [form, setForm] = useState<OverrideFormState>(INITIAL);
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!tenant) return;
    setSubmitting(true);
    try {
      await api.post(`/tenants/${tenant.id}/override`, form);
      onSuccess(`Granted ${form.extension_days}-day write extension for ${tenant.name}`);
    } catch (err: any) {
      onError(err.response?.data?.error || err.message || 'Override failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <Field label="Rationale / Reason" required>
        <textarea
          required
          value={form.reason}
          onChange={e => setForm({ ...form, reason: e.target.value })}
          placeholder="e.g. Emergency access granted by platform owner, or billing extension"
          className="form-input text-xs font-mono h-24 resize-y"
        />
      </Field>
      <Field label="Extension Duration (Days)">
        <input
          type="number"
          min={1}
          value={form.extension_days}
          onChange={e => setForm({ ...form, extension_days: parseInt(e.target.value, 10) || 0 })}
          className="form-input text-xs font-mono"
        />
      </Field>
      <button
        type="submit"
        disabled={submitting}
        className="w-full py-3 bg-amber-500 hover:bg-amber-600 text-white font-bold text-xs uppercase tracking-wider rounded-xl transition-all mt-2 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        {submitting ? 'Granting…' : 'Grant Emergency Override'}
      </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 OverrideForm;
