'use client'

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

export function CreateRoleModal({ onClose, onCreated }: { onClose: () => void; onCreated: () => void }) {
  const [form, setForm] = useState({ name: '', description: '', permissions: '' })
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSubmit = async () => {
    if (!form.name) { setError('Name ist Pflichtfeld'); return }
    setSaving(true)
    try {
      await apiFetch('roles', {
        method: 'POST',
        body: JSON.stringify({
          name: form.name,
          description: form.description,
          permissions: form.permissions.split(',').map(s => s.trim()).filter(Boolean),
        }),
      })
      onCreated()
    } catch (e) { setError(e instanceof Error ? e.message : 'Fehler') }
    finally { setSaving(false) }
  }

  return (
    <ModalBase title="Rolle erstellen" 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">Beschreibung</label>
          <input type="text" value={form.description} onChange={e => setForm(f => ({ ...f, description: 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">Berechtigungen (kommagetrennt)</label>
          <textarea value={form.permissions} onChange={e => setForm(f => ({ ...f, permissions: e.target.value }))}
            placeholder="llm:read, llm:write, audit:read"
            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono h-20" />
        </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>
  )
}
