import { useState } from 'react'
import {
  Box,
  Button,
  Card,
  Chip,
  Typography,
  Stack,
  CircularProgress,
} from '@mui/material'
import {
  Building2,
  Edit,
  CheckCircle,
  XCircle,
  TrendingUp,
  Search,
  ClipboardList,
} from 'lucide-react'
import { useQuery } from '@tanstack/react-query'
import { governanceService, type ActivityEventType, type ActivityEvent } from '../../services/governanceService'
import { EmptyState } from '../../components/ui'

function getEventLabel(type: ActivityEventType): string {
  switch (type) {
    case 'PROPERTY_CREATED': return 'Objekt erstellt'
    case 'PROPERTY_UPDATED': return 'Objekt aktualisiert'
    case 'MATCH_APPROVED': return 'Match genehmigt'
    case 'MATCH_REJECTED': return 'Match abgelehnt'
    case 'SIGNAL_VERIFIED': return 'Signal verifiziert'
    case 'NEED_CREATED': return 'Bedarf erstellt'
    case 'REVIEW_REQUESTED': return 'Überprüfung angefordert'
  }
}

function getEventDescription(event: ActivityEvent): string {
  const actor = event.performedBy
  const action = getEventLabel(event.type)
  const entity = `${event.entityType} ${event.entityId}`
  return `${actor} hat ${entity} — ${action}`
}

function getEventColor(type: ActivityEventType): string {
  switch (type) {
    case 'PROPERTY_CREATED': return '#1e3a5f'
    case 'PROPERTY_UPDATED': return '#1e3a5f'
    case 'MATCH_APPROVED': return '#1a7a4a'
    case 'MATCH_REJECTED': return '#c0392b'
    case 'SIGNAL_VERIFIED': return '#7c3aed'
    case 'NEED_CREATED': return '#0891b2'
    case 'REVIEW_REQUESTED': return '#d97706'
  }
}

function getEventIcon(type: ActivityEventType) {
  const size = 14
  switch (type) {
    case 'PROPERTY_CREATED': return <Building2 size={size} color="white" />
    case 'PROPERTY_UPDATED': return <Edit size={size} color="white" />
    case 'MATCH_APPROVED': return <CheckCircle size={size} color="white" />
    case 'MATCH_REJECTED': return <XCircle size={size} color="white" />
    case 'SIGNAL_VERIFIED': return <TrendingUp size={size} color="white" />
    case 'NEED_CREATED': return <Search size={size} color="white" />
    case 'REVIEW_REQUESTED': return <ClipboardList size={size} color="white" />
  }
}

const ALL_EVENT_TYPES: ActivityEventType[] = [
  'PROPERTY_CREATED',
  'PROPERTY_UPDATED',
  'MATCH_APPROVED',
  'MATCH_REJECTED',
  'SIGNAL_VERIFIED',
  'NEED_CREATED',
  'REVIEW_REQUESTED',
]

function formatDateTime(dateStr: string): string {
  const d = new Date(dateStr)
  return d.toLocaleDateString('de-CH', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  }) + ', ' + d.toLocaleTimeString('de-CH', { hour: '2-digit', minute: '2-digit' })
}

function isToday(dateStr: string): boolean {
  const d = new Date(dateStr)
  const now = new Date()
  return d.getFullYear() === now.getFullYear() &&
    d.getMonth() === now.getMonth() &&
    d.getDate() === now.getDate()
}

export default function Governance() {
  const [filterType, setFilterType] = useState<ActivityEventType | 'ALL'>('ALL')

  const { data: activityResp, isLoading, error } = useQuery({
    queryKey: ['activity', 'org-wincasa'],
    queryFn: () => governanceService.getActivityLog('org-wincasa'),
  })

  const events = activityResp?.data ?? []

  const presentTypes = [...new Set(events.map(e => e.type))]
  const todayCount = events.filter(e => isToday(e.createdAt)).length
  const uniqueUsers = new Set(events.map(e => e.performedBy)).size

  const filtered = filterType === 'ALL'
    ? events
    : events.filter(e => e.type === filterType)

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', py: 12 }}>
        <CircularProgress />
      </Box>
    )
  }

  if (error) {
    return (
      <Box sx={{ px: 3, py: 4 }}>
        <Typography color="error">Fehler beim Laden des Aktivitätslogs.</Typography>
      </Box>
    )
  }

  return (
    <Box>
      {/* Page Header */}
      <Box
        sx={{
          bgcolor: 'white',
          borderBottom: '1px solid #e2e8f0',
          px: 3,
          py: 2,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <Box>
          <Typography variant="h5" sx={{ fontWeight: 700 }} color="text.primary">
            Governance & Aktivitätslog
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Vollständiger Audit-Trail aller Plattformaktionen
          </Typography>
        </Box>
        <Button variant="outlined" size="small" disabled>
          Exportieren
        </Button>
      </Box>

      <Box sx={{ px: 3, py: 3 }}>
        {/* Stats row */}
        <Box className="grid grid-cols-3 gap-4" sx={{ mb: 3 }}>
          <Card sx={{ p: 2.5 }}>
            <Typography variant="overline" color="text.secondary" sx={{ lineHeight: 1.4, display: 'block' }}>
              Ereignisse gesamt
            </Typography>
            <Typography variant="h3" sx={{ fontWeight: 700 }}>
              {events.length}
            </Typography>
            <Typography variant="caption" color="text.secondary">Alle Aktivitäten</Typography>
          </Card>
          <Card sx={{ p: 2.5 }}>
            <Typography variant="overline" color="text.secondary" sx={{ lineHeight: 1.4, display: 'block' }}>
              Ereignisse heute
            </Typography>
            <Typography variant="h3" sx={{ fontWeight: 700 }}>
              {todayCount}
            </Typography>
            <Typography variant="caption" color="text.secondary">Heutige Aktivitäten</Typography>
          </Card>
          <Card sx={{ p: 2.5 }}>
            <Typography variant="overline" color="text.secondary" sx={{ lineHeight: 1.4, display: 'block' }}>
              Aktive Benutzer
            </Typography>
            <Typography variant="h3" sx={{ fontWeight: 700 }}>
              {uniqueUsers}
            </Typography>
            <Typography variant="caption" color="text.secondary">Unterschiedliche Nutzer</Typography>
          </Card>
        </Box>

        {/* Filter chips */}
        <Stack direction="row" spacing={0.5} sx={{ flexWrap: 'wrap', gap: 0.5, mb: 2 }}>
          <Chip
            label="Alle"
            size="small"
            clickable
            onClick={() => setFilterType('ALL')}
            sx={{
              bgcolor: filterType === 'ALL' ? '#1e3a5f' : 'transparent',
              color: filterType === 'ALL' ? 'white' : 'text.secondary',
              border: `1px solid ${filterType === 'ALL' ? '#1e3a5f' : '#e2e8f0'}`,
              fontWeight: filterType === 'ALL' ? 600 : 400,
            }}
          />
          {ALL_EVENT_TYPES.filter(t => presentTypes.includes(t)).map(t => (
            <Chip
              key={t}
              label={getEventLabel(t)}
              size="small"
              clickable
              onClick={() => setFilterType(t)}
              sx={{
                bgcolor: filterType === t ? getEventColor(t) : 'transparent',
                color: filterType === t ? 'white' : 'text.secondary',
                border: `1px solid ${filterType === t ? getEventColor(t) : '#e2e8f0'}`,
                fontWeight: filterType === t ? 600 : 400,
              }}
            />
          ))}
        </Stack>

        {/* Activity Timeline */}
        <Card sx={{ p: 2.5 }}>
          <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2 }}>
            Aktivitätslog
          </Typography>

          {filtered.length === 0 ? (
            <EmptyState
              title="Keine Ereignisse"
              description="Für diesen Filter wurden keine Aktivitäten gefunden."
            />
          ) : (
            <Box sx={{ position: 'relative' }}>
              {/* Vertical line */}
              <Box
                sx={{
                  position: 'absolute',
                  left: 15,
                  top: 16,
                  bottom: 16,
                  width: 2,
                  bgcolor: '#e2e8f0',
                  zIndex: 0,
                }}
              />

              <Stack spacing={0}>
                {filtered.map((event, idx) => (
                  <Box
                    key={event.id}
                    sx={{
                      display: 'flex',
                      gap: 2,
                      py: 1.5,
                      borderBottom: idx < filtered.length - 1 ? '1px solid #f8fafc' : 'none',
                      position: 'relative',
                    }}
                  >
                    {/* Icon dot */}
                    <Box
                      sx={{
                        width: 32,
                        height: 32,
                        borderRadius: '50%',
                        bgcolor: getEventColor(event.type),
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flexShrink: 0,
                        zIndex: 1,
                        boxShadow: '0 0 0 3px white',
                      }}
                    >
                      {getEventIcon(event.type)}
                    </Box>

                    {/* Content */}
                    <Box sx={{ flex: 1, minWidth: 0, pt: 0.5 }}>
                      <Typography variant="body2">
                        {getEventDescription(event)}
                      </Typography>
                      {event.notes && (
                        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.25 }}>
                          {event.notes}
                        </Typography>
                      )}
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
                        <Chip
                          label={event.organizationId}
                          size="small"
                          sx={{ fontSize: 10, height: 18, bgcolor: '#f1f5f9', color: '#475569' }}
                        />
                      </Box>
                    </Box>

                    {/* Timestamp */}
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      sx={{ flexShrink: 0, pt: 0.5, textAlign: 'right', minWidth: 110 }}
                    >
                      {formatDateTime(event.createdAt)}
                    </Typography>
                  </Box>
                ))}
              </Stack>
            </Box>
          )}
        </Card>
      </Box>
    </Box>
  )
}
