'use client'

import React, { useState } from 'react'
import { AlertTriangle, Loader2 } from 'lucide-react'
import type { CreateTenantForm } from '../_types'
import { EMPTY_CREATE_FORM } from './constants'
import { apiFetch, slugify } from './helpers'
import { Modal } from './Modal'

export function CreateTenantModal({
  open,
  onClose,
  onCreated,
}: {
  open: boolean
  onClose: () => void
  onCreated: () => void
}) {
  const [form, setForm] = useState<CreateTenantForm>({ ...EMPTY_CREATE_FORM })
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [slugManual, setSlugManual] = useState(false)

  const handleNameChange = (name: string) => {
    setForm((prev) => ({
      ...prev,
      name,
      slug: slugManual ? prev.slug : slugify(name),
    }))
  }

  const handleSlugChange = (slug: string) => {
    setSlugManual(true)
    setForm((prev) => ({ ...prev, slug: slugify(slug) }))
  }

  const isValid = form.name.trim().length >= 2 && form.slug.trim().length >= 2

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!isValid) return
    setSaving(true)
    setError(null)
    try {
      await apiFetch('/tenants', {
        method: 'POST',
        body: JSON.stringify({
          name: form.name.trim(),
          slug: form.slug.trim(),
          max_users: form.max_users,
          llm_quota_monthly: form.llm_quota_monthly,
        }),
      })
      setForm({ ...EMPTY_CREATE_FORM })
      setSlugManual(false)
      onCreated()
      onClose()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Fehler beim Erstellen')
    } finally {
      setSaving(false)
    }
  }

  const handleClose = () => {
    setForm({ ...EMPTY_CREATE_FORM })
    setSlugManual(false)
    setError(null)
    onClose()
  }

  return (
    <Modal open={open} onClose={handleClose} title="Neuen Mandanten erstellen">
      <form onSubmit={handleSubmit} className="space-y-4">
        {error && (
          <div className="flex items-center gap-2 p-3 text-sm text-red-700 bg-red-50 rounded-lg border border-red-200">
            <AlertTriangle className="w-4 h-4 shrink-0" />
            {error}
          </div>
        )}

        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">
            Name <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            value={form.name}
            onChange={(e) => handleNameChange(e.target.value)}
            placeholder="z.B. Musterfirma GmbH"
            className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            autoFocus
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">
            Slug <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            value={form.slug}
            onChange={(e) => handleSlugChange(e.target.value)}
            placeholder="musterfirma-gmbh"
            className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
          />
          <p className="mt-1 text-xs text-slate-400">
            Kleinbuchstaben, keine Leerzeichen. Wird automatisch aus dem Namen generiert.
          </p>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              Max. Benutzer
            </label>
            <input
              type="number"
              value={form.max_users}
              onChange={(e) => setForm((prev) => ({ ...prev, max_users: parseInt(e.target.value) || 0 }))}
              min={1}
              className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">
              LLM Kontingent / Monat
            </label>
            <input
              type="number"
              value={form.llm_quota_monthly}
              onChange={(e) => setForm((prev) => ({ ...prev, llm_quota_monthly: parseInt(e.target.value) || 0 }))}
              min={0}
              step={1000}
              className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            />
          </div>
        </div>

        <div className="flex items-center justify-end gap-3 pt-4 border-t border-slate-200">
          <button
            type="button"
            onClick={handleClose}
            className="px-4 py-2 text-sm font-medium text-slate-600 bg-slate-100 hover:bg-slate-200 rounded-lg transition-colors"
          >
            Abbrechen
          </button>
          <button
            type="submit"
            disabled={!isValid || saving}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors"
          >
            {saving && <Loader2 className="w-4 h-4 animate-spin" />}
            Mandant erstellen
          </button>
        </div>
      </form>
    </Modal>
  )
}
