'use client'

import React, { useState } from 'react'
import { ModalBase } from './ModalBase'
import { apiFetch } from '../_api'

export function CreateTenantModal({ onClose, onCreated }: { onClose: () => void; onCreated: () => void }) {
  const [form, setForm] = useState({ name: '', slug: '', user_limit: 100, llm_quota: 100000 })
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSubmit = async () => {
    if (!form.name || !form.slug) { setError('Name und Slug sind Pflichtfelder'); return }
    setSaving(true)
    try {
      await apiFetch('tenants', { method: 'POST', body: JSON.stringify(form) })
      onCreated()
    } catch (e) { setError(e instanceof Error ? e.message : 'Fehler') }
    finally { setSaving(false) }
  }

  return (
    <ModalBase title="Mandant anlegen" onClose={onClose}>
      {error && <div className="mb-3 p-2 bg-red-50 text-red-700 rounded text-sm">{error}</div>}
      <div className="space-y-3">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
          <input type="text" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Slug</label>
          <input type="text" value={form.slug} onChange={e => setForm(f => ({ ...f, slug: e.target.value }))}
            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono" />
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">User-Limit</label>
            <input type="number" value={form.user_limit} onChange={e => setForm(f => ({ ...f, user_limit: +e.target.value }))}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">LLM-Quota</label>
            <input type="number" value={form.llm_quota} onChange={e => setForm(f => ({ ...f, llm_quota: +e.target.value }))}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" />
          </div>
        </div>
      </div>
      <div className="flex justify-end gap-2 mt-5">
        <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800">Abbrechen</button>
        <button onClick={handleSubmit} disabled={saving}
          className="px-4 py-2 bg-purple-600 text-white rounded-lg text-sm hover:bg-purple-700 disabled:opacity-50">
          {saving ? 'Speichern...' : 'Erstellen'}
        </button>
      </div>
    </ModalBase>
  )
}
