'use client'

import { useState, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { Plus, Shield, Loader2 } from 'lucide-react'
import { TenantDetailDialog } from './tenant-detail-dialog'
import type { TenantRecord } from './admin-constants'

export function TenantsTab() {
  const { toast } = useToast()
  const [tenants, setTenants] = useState<TenantRecord[]>([])
  const [isLoading, setIsLoading] = useState(true)

  const [isTenantDialogOpen, setIsTenantDialogOpen] = useState(false)
  const [tenantName, setTenantName] = useState('')
  const [tenantSlug, setTenantSlug] = useState('')
  const [tenantDescription, setTenantDescription] = useState('')

  const [selectedTenantId, setSelectedTenantId] = useState<string | null>(null)
  const [isTenantDetailOpen, setIsTenantDetailOpen] = useState(false)

  const fetchTenants = useCallback(async () => {
    setIsLoading(true)
    try {
      const res = await fetch('/api/admin/tenants')
      if (res.ok) setTenants((await res.json()).tenants || [])
    } catch (e) {
      console.error('Error fetching tenants:', e)
    } finally {
      setIsLoading(false)
    }
  }, [])

  useEffect(() => { fetchTenants() }, [fetchTenants])

  const handleSaveTenant = async () => {
    try {
      const res = await fetch('/api/admin/tenants', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: tenantName, slug: tenantSlug, description: tenantDescription || undefined }),
      })
      if (res.ok) {
        toast({ title: 'Mandant erstellt' })
        setIsTenantDialogOpen(false); setTenantName(''); setTenantSlug(''); setTenantDescription('')
        fetchTenants()
      } else {
        const err = await res.json(); throw new Error(err.error)
      }
    } catch (error) {
      toast({ title: 'Fehler', description: error instanceof Error ? error.message : 'Fehler', variant: 'destructive' })
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <p className="text-sm text-muted-foreground">{tenants.length} Mandant(en)</p>
        <Button onClick={() => { setTenantName(''); setTenantSlug(''); setTenantDescription(''); setIsTenantDialogOpen(true) }}>
          <Plus className="w-4 h-4 mr-2" />
          Neuer Mandant
        </Button>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center py-12"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>
      ) : tenants.length === 0 ? (
        <div className="border-2 border-dashed rounded-lg p-12 text-center">
          <Shield className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
          <h3 className="font-medium text-lg mb-2">Keine Mandanten</h3>
          <p className="text-muted-foreground mb-4">Erstellen Sie einen Mandanten (Organisation/Feuerwehr)</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {tenants.map(t => (
            <div key={t.id} className="border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer" onClick={() => { setSelectedTenantId(t.id); setIsTenantDetailOpen(true) }}>
              <div className="flex items-start justify-between">
                <div>
                  <h3 className="font-medium">{t.name}</h3>
                  <p className="text-xs text-muted-foreground font-mono mt-0.5">{t.slug}</p>
                  {t.description && <p className="text-sm text-muted-foreground mt-1">{t.description}</p>}
                  <div className="flex gap-3 mt-2 text-xs text-muted-foreground">
                    <span>{t._count?.memberships || 0} Benutzer</span>
                    <span>{t._count?.projects || 0} Projekte</span>
                  </div>
                </div>
                <span className={`text-xs px-2 py-0.5 rounded-full ${t.isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                  {t.isActive ? 'Aktiv' : 'Inaktiv'}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Tenant Dialog */}
      <Dialog open={isTenantDialogOpen} onOpenChange={setIsTenantDialogOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Neuer Mandant</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div><Label>Name</Label><Input value={tenantName} onChange={e => { setTenantName(e.target.value); setTenantSlug(e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')) }} placeholder="z.B. Feuerwehr Wohlen" /></div>
            <div><Label>Slug (URL-freundlich)</Label><Input value={tenantSlug} onChange={e => setTenantSlug(e.target.value)} placeholder="z.B. feuerwehr-wohlen" className="font-mono" /></div>
            <div><Label>Beschreibung (optional)</Label><Input value={tenantDescription} onChange={e => setTenantDescription(e.target.value)} placeholder="Kurze Beschreibung" /></div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsTenantDialogOpen(false)}>Abbrechen</Button>
            <Button onClick={handleSaveTenant} disabled={!tenantName.trim() || !tenantSlug.trim()}>Erstellen</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Tenant Detail Dialog */}
      <TenantDetailDialog
        tenantId={selectedTenantId}
        open={isTenantDetailOpen}
        onOpenChange={setIsTenantDetailOpen}
        onUpdated={fetchTenants}
      />
    </div>
  )
}
