'use client'

import { useState, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import { Eye, Loader2 } from 'lucide-react'
import type { TenantRecord } from './admin-constants'

export function ProjectsTab() {
  const [projects, setProjects] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [tenants, setTenants] = useState<TenantRecord[]>([])
  const [tenantFilter, setTenantFilter] = useState<string>('all')

  const fetchProjects = useCallback(async (filter?: string) => {
    setLoading(true)
    try {
      const url = filter && filter !== 'all'
        ? `/api/admin/projects?tenantId=${filter}`
        : '/api/admin/projects'
      const res = await fetch(url)
      if (res.ok) setProjects((await res.json()).projects || [])
    } catch {}
    setLoading(false)
  }, [])

  useEffect(() => {
    fetchProjects()
    fetch('/api/admin/tenants').then(r => r.ok ? r.json() : { tenants: [] }).then(d => setTenants(d.tenants || [])).catch(() => {})
  }, [fetchProjects])

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-4 flex-wrap">
        <p className="text-sm text-muted-foreground">{projects.length} Einsatz/Einsätze</p>
        <div className="flex items-center gap-2">
          <span className="text-sm text-muted-foreground">Feuerwehr:</span>
          <Select value={tenantFilter} onValueChange={(val) => { setTenantFilter(val); fetchProjects(val) }}>
            <SelectTrigger className="w-[220px]"><SelectValue placeholder="Alle Mandanten" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Alle Mandanten</SelectItem>
              {tenants.map(t => <SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>)}
            </SelectContent>
          </Select>
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-12"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>
      ) : projects.length === 0 ? (
        <p className="text-center text-muted-foreground py-8">Keine Einsätze gefunden.</p>
      ) : (
        <div className="border rounded-lg overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr>
                <th className="text-left px-4 py-2.5 font-medium">Einsatz-Nr</th>
                <th className="text-left px-4 py-2.5 font-medium">Titel</th>
                <th className="text-left px-4 py-2.5 font-medium">Ort</th>
                <th className="text-left px-4 py-2.5 font-medium">Erstellt von</th>
                <th className="text-left px-4 py-2.5 font-medium">Feuerwehr</th>
                <th className="text-left px-4 py-2.5 font-medium">Elemente</th>
                <th className="text-left px-4 py-2.5 font-medium">Geändert</th>
                <th className="text-left px-4 py-2.5 font-medium">Aktion</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {projects.map((p: any) => (
                <tr key={p.id} className="hover:bg-muted/30">
                  <td className="px-4 py-2.5 font-mono text-xs">{p.einsatzNr || '—'}</td>
                  <td className="px-4 py-2.5 font-semibold">{p.title}</td>
                  <td className="px-4 py-2.5 text-muted-foreground truncate max-w-[200px]">{p.location || '—'}</td>
                  <td className="px-4 py-2.5"><span className="text-xs">{p.owner?.name || p.owner?.email || '—'}</span></td>
                  <td className="px-4 py-2.5"><span className="text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded">{p.tenant?.name || '—'}</span></td>
                  <td className="px-4 py-2.5 text-center">{p._count?.features || 0}</td>
                  <td className="px-4 py-2.5 text-xs text-muted-foreground">{new Date(p.updatedAt).toLocaleString('de-CH')}</td>
                  <td className="px-4 py-2.5">
                    <Button size="sm" variant="outline" className="h-7 text-xs" onClick={() => window.open(`/app?project=${p.id}`, '_blank')}>
                      <Eye className="w-3 h-3 mr-1" />
                      Öffnen
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
