import { useEffect, useState } from 'react'
import { api } from '../api/client'
import { useAuth } from '../context/AuthContext'

interface Tenant {
  id: string; name: string; slug: string; plan: string; is_active: boolean
  country: string; user_count: number; active_user_count: number; admin_email: string | null
}
interface Me { first_name: string; last_name: string; role: string }

const empty = { name: '', country: 'DE', plan: 'trial', admin_email: '', admin_first_name: '', admin_last_name: '' }

export function ResellerCompaniesPage() {
  const { logout } = useAuth()
  const [me, setMe] = useState<Me | null>(null)
  const [companies, setCompanies] = useState<Tenant[]>([])
  const [error, setError] = useState<string | null>(null)
  const [showNew, setShowNew] = useState(false)
  const [form, setForm] = useState({ ...empty })
  const [busy, setBusy] = useState(false)
  const [cred, setCred] = useState<{ email: string; password: string } | null>(null)

  async function load() {
    try { setCompanies(await api.get<Tenant[]>('/reseller/companies')) }
    catch (e: unknown) { setError(e instanceof Error ? e.message : 'Fehler beim Laden') }
  }

  useEffect(() => {
    api.get<Me>('/auth/me').then(setMe).catch(() => {})
    load()
  }, [])

  async function createCompany() {
    setBusy(true); setError(null)
    try {
      const body = { ...form, admin_email: form.admin_email.trim() || undefined }
      const res = await api.post<Tenant & { initial_password?: string | null; admin_email?: string | null }>(
        '/reseller/companies', body,
      )
      setShowNew(false); setForm({ ...empty })
      if (res.initial_password) setCred({ email: res.admin_email ?? '', password: res.initial_password })
      await load()
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Fehler beim Anlegen')
    } finally { setBusy(false) }
  }

  async function toggle(t: Tenant) {
    try { await api.patch(`/reseller/companies/${t.id}`, { is_active: !t.is_active }); await load() }
    catch (e: unknown) { setError(e instanceof Error ? e.message : 'Fehler') }
  }

  const active = companies.filter(c => c.is_active).length

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white border-b border-gray-200 sticky top-0 z-30">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 h-14 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 bg-indigo-600 rounded-lg flex items-center justify-center">
              <span className="text-white font-bold text-sm">TM</span>
            </div>
            <span className="font-bold text-gray-800 text-sm">TimeMaster · Reseller</span>
          </div>
          <div className="flex items-center gap-3">
            <span className="text-sm text-gray-500 hidden sm:block">{me ? `${me.first_name} ${me.last_name}` : ''}</span>
            <button onClick={logout} title="Abmelden"
              className="p-2 rounded-lg text-gray-500 hover:text-red-600 hover:bg-red-50">
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.75}
                  d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
              </svg>
            </button>
          </div>
        </div>
      </header>

      <main className="max-w-5xl mx-auto px-4 sm:px-6 py-8 space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Meine Firmen</h1>
            <p className="text-sm text-gray-500">{active} aktiv · {companies.length} gesamt</p>
          </div>
          <button onClick={() => setShowNew(true)}
            className="px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-lg hover:bg-indigo-700">
            + Firma anlegen
          </button>
        </div>

        {error && <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>}

        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {companies.map(t => (
            <div key={t.id} className={`bg-white rounded-xl shadow-sm border p-5 space-y-3 ${t.is_active ? 'border-gray-200' : 'border-gray-200 opacity-60'}`}>
              <div className="flex items-start justify-between gap-2">
                <div>
                  <h3 className="font-semibold text-gray-800">{t.name}</h3>
                  <p className="text-xs text-gray-400">{t.slug}</p>
                </div>
                <span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600">{t.plan}</span>
              </div>
              <div className="text-sm text-gray-600">👥 {t.active_user_count}/{t.user_count} Nutzer</div>
              {t.admin_email && <div className="text-xs text-gray-400 truncate">Admin: {t.admin_email}</div>}
              <button onClick={() => toggle(t)}
                className={`w-full text-xs px-2 py-1.5 rounded-lg font-medium ${
                  t.is_active ? 'bg-green-50 text-green-700 hover:bg-green-100' : 'bg-red-50 text-red-700 hover:bg-red-100'
                }`}>
                {t.is_active ? '● aktiv – zum Deaktivieren klicken' : '○ deaktiviert – zum Aktivieren klicken'}
              </button>
            </div>
          ))}
          {companies.length === 0 && (
            <div className="col-span-full text-center text-gray-400 py-12">Noch keine Firmen angelegt.</div>
          )}
        </div>
      </main>

      {showNew && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4" onClick={() => setShowNew(false)}>
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 space-y-4" onClick={e => e.stopPropagation()}>
            <h2 className="text-lg font-bold text-gray-900">Neue Firma anlegen</h2>
            <div className="space-y-3">
              <L label="Firmenname"><input className={inp} value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} /></L>
              <div className="grid grid-cols-2 gap-3">
                <L label="Land"><input className={inp} value={form.country} onChange={e => setForm({ ...form, country: e.target.value })} /></L>
                <L label="Plan"><input className={inp} value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })} /></L>
              </div>
              <hr />
              <p className="text-xs text-gray-500">Erster Administrator. Mit E-Mail wird eine Einladung verschickt – ohne E-Mail erhältst du ein einmaliges Temporär-Passwort zum Weitergeben.</p>
              <L label="Admin E-Mail (optional)"><input className={inp} placeholder="leer lassen für Temp-Passwort" value={form.admin_email} onChange={e => setForm({ ...form, admin_email: e.target.value })} /></L>
              <div className="grid grid-cols-2 gap-3">
                <L label="Vorname"><input className={inp} value={form.admin_first_name} onChange={e => setForm({ ...form, admin_first_name: e.target.value })} /></L>
                <L label="Nachname"><input className={inp} value={form.admin_last_name} onChange={e => setForm({ ...form, admin_last_name: e.target.value })} /></L>
              </div>
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <button onClick={() => setShowNew(false)} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
              <button onClick={createCompany} disabled={busy}
                className="px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-lg hover:bg-indigo-700 disabled:opacity-50">
                {busy ? 'Speichern…' : 'Anlegen'}
              </button>
            </div>
          </div>
        </div>
      )}

      {cred && <CredDialog title="Zugangsdaten Firmen-Administrator" cred={cred} onClose={() => setCred(null)} />}
    </div>
  )
}

export function CredDialog({ title, cred, onClose }: {
  title: string; cred: { email: string; password: string }; onClose: () => void
}) {
  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-[60] p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6 space-y-4">
        <h2 className="text-lg font-bold text-gray-900">{title}</h2>
        <div className="rounded-lg border-2 border-amber-300 bg-amber-50 p-4 space-y-3">
          <p className="text-xs font-semibold text-amber-800">⚠ Jetzt notieren – das Passwort wird nur einmal angezeigt.</p>
          <div>
            <p className="text-xs text-gray-500">Login</p>
            <p className="font-mono text-sm break-all">{cred.email}</p>
          </div>
          <div>
            <p className="text-xs text-gray-500">Temporäres Passwort</p>
            <p className="font-mono text-sm break-all select-all">{cred.password}</p>
          </div>
        </div>
        <div className="flex justify-end gap-2">
          <button onClick={() => navigator.clipboard?.writeText(`${cred.email} / ${cred.password}`)}
            className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Kopieren</button>
          <button onClick={onClose}
            className="px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-lg hover:bg-indigo-700">Verstanden</button>
        </div>
      </div>
    </div>
  )
}

const inp = 'w-full px-3 py-2 border border-gray-300 rounded-lg text-sm'
function L({ label, children }: { label: string; children: React.ReactNode }) {
  return <label className="block space-y-1"><span className="text-xs font-medium text-gray-600">{label}</span>{children}</label>
}
