import { useState } from 'react'
import {
  Box,
  Button,
  Card,
  Chip,
  Typography,
  TextField,
  Stack,
  CircularProgress,
  Divider,
  Alert,
} from '@mui/material'
import { Target, TrendingUp } from 'lucide-react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { matchService } from '../../services/matchService'
import { futureSignalService } from '../../services/futureSignalService'
import { RiskLevel } from '../../domain/enums'
import { EmptyState } from '../../components/ui'

type ReviewItemType = 'MATCH' | 'SIGNAL'

interface ReviewItem {
  id: string
  type: ReviewItemType
  title: string
  confidence: number
  risk?: RiskLevel
  summary?: string
  probability?: number
}

function getPriorityLabel(confidence: number): string {
  return confidence > 0.8 ? 'Kritisch' : 'Normal'
}

function getPriorityColor(confidence: number): 'error' | 'primary' {
  return confidence > 0.8 ? 'error' : 'primary'
}

function getRiskLabel(risk?: RiskLevel): string {
  if (!risk) return '–'
  switch (risk) {
    case RiskLevel.LOW: return 'Niedrig'
    case RiskLevel.MEDIUM: return 'Mittel'
    case RiskLevel.HIGH: return 'Hoch'
    case RiskLevel.CRITICAL: return 'Kritisch'
  }
}

function getRiskColor(risk?: RiskLevel): 'success' | 'warning' | 'error' | 'default' {
  if (!risk) return 'default'
  if (risk === RiskLevel.LOW) return 'success'
  if (risk === RiskLevel.MEDIUM) return 'warning'
  return 'error'
}

export default function ReviewQueue() {
  const queryClient = useQueryClient()
  const [activeItem, setActiveItem] = useState<string | null>(null)
  const [reviewNotes, setReviewNotes] = useState('')
  const [approvedIds, setApprovedIds] = useState<Set<string>>(new Set())
  const [rejectedIds, setRejectedIds] = useState<Set<string>>(new Set())

  const { data: matchResp, isLoading: matchLoading } = useQuery({
    queryKey: ['matches'],
    queryFn: () => matchService.getAll(),
  })
  const { data: signalResp, isLoading: signalLoading } = useQuery({
    queryKey: ['futureSignals'],
    queryFn: () => futureSignalService.getAll(),
  })

  const matches = matchResp?.data ?? []
  const signals = signalResp?.data ?? []

  // Review items = matches NOT approved + future signals NOT verified
  const matchItems: ReviewItem[] = matches
    .filter(m => !m.isApproved && !approvedIds.has(m.id) && !rejectedIds.has(m.id))
    .map(m => ({
      id: m.id,
      type: 'MATCH' as ReviewItemType,
      title: `Match: ${m.propertyId} / ${m.needId}`,
      confidence: m.confidenceLevel,
      risk: m.riskLevel,
      summary: m.explainabilitySummary,
    }))

  const signalItems: ReviewItem[] = signals
    .filter(s => !s.isVerified && !approvedIds.has(s.id) && !rejectedIds.has(s.id))
    .map(s => ({
      id: s.id,
      type: 'SIGNAL' as ReviewItemType,
      title: `${s.signalType}: ${s.locationHint}`,
      confidence: s.confidenceScore,
      risk: s.riskLevel,
      probability: s.probability,
      summary: s.disclaimer,
    }))

  const allItems = [...matchItems, ...signalItems]
  const selectedItem = allItems.find(i => i.id === activeItem)

  const isLoading = matchLoading || signalLoading

  const handleApprove = async () => {
    if (!activeItem) return
    const item = allItems.find(i => i.id === activeItem)
    if (item?.type === 'MATCH') {
      await matchService.approve(activeItem, 'admin@ideal-sharing.ch')
      await queryClient.invalidateQueries({ queryKey: ['matches'] })
    } else if (item?.type === 'SIGNAL') {
      await futureSignalService.verify(activeItem, 'admin@ideal-sharing.ch')
      await queryClient.invalidateQueries({ queryKey: ['futureSignals'] })
    }
    setApprovedIds(prev => new Set([...prev, activeItem]))
    setActiveItem(null)
    setReviewNotes('')
  }

  const handleReject = () => {
    if (!activeItem) return
    setRejectedIds(prev => new Set([...prev, activeItem]))
    setActiveItem(null)
    setReviewNotes('')
  }

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

  const totalPending = matchItems.length + signalItems.length

  return (
    <Box>
      {/* Page Header */}
      <Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e2e8f0', px: 3, py: 2, display: 'flex', alignItems: 'center', gap: 2 }}>
        <Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
            <Typography variant="h5" sx={{ fontWeight: 700 }} color="text.primary">
              Review Queue
            </Typography>
            {totalPending > 0 && (
              <Chip
                label={totalPending}
                size="small"
                sx={{ bgcolor: '#d97706', color: 'white', fontWeight: 700 }}
              />
            )}
          </Box>
          <Typography variant="body2" color="text.secondary">
            Human-in-the-loop Prüfung
          </Typography>
        </Box>
      </Box>

      <Box sx={{ px: 3, py: 3 }}>
        {/* Stats row */}
        <Box className="grid grid-cols-2 gap-4" sx={{ mb: 3 }}>
          <Card sx={{ p: 2.5 }}>
            <Typography variant="overline" color="text.secondary" sx={{ lineHeight: 1.4, display: 'block' }}>
              Offene Reviews
            </Typography>
            <Typography variant="h3" sx={{ fontWeight: 700, color: totalPending > 0 ? 'warning.main' : 'text.primary' }}>
              {totalPending}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              Ausstehende Prüfungen
            </Typography>
          </Card>
          <Card sx={{ p: 2.5 }}>
            <Typography variant="overline" color="text.secondary" sx={{ lineHeight: 1.4, display: 'block' }}>
              Signale zur Prüfung
            </Typography>
            <Typography variant="h3" sx={{ fontWeight: 700, color: signalItems.length > 0 ? 'warning.main' : 'text.primary' }}>
              {signalItems.length}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              Unverifizierte Signale
            </Typography>
          </Card>
        </Box>

        {/* Two-column layout */}
        <Box className="grid grid-cols-2 gap-4" sx={{ alignItems: 'start' }}>
          {/* Left: Item List */}
          <Card sx={{ p: 0, overflow: 'hidden' }}>
            <Box sx={{ px: 2, py: 1.5, borderBottom: '1px solid #f1f5f9' }}>
              <Typography variant="subtitle2" sx={{ fontWeight: 600 }}>
                Ausstehende Elemente
              </Typography>
            </Box>

            {allItems.length === 0 ? (
              <EmptyState
                title="Keine ausstehenden Reviews"
                description="Alle Elemente wurden geprüft."
              />
            ) : (
              <Box>
                {allItems.map(item => (
                  <Box
                    key={item.id}
                    onClick={() => {
                      setActiveItem(item.id)
                      setReviewNotes('')
                    }}
                    sx={{
                      px: 2,
                      py: 1.5,
                      cursor: 'pointer',
                      borderBottom: '1px solid #f8fafc',
                      bgcolor: activeItem === item.id ? '#eff6ff' : 'white',
                      '&:hover': { bgcolor: activeItem === item.id ? '#eff6ff' : '#fafafa' },
                      display: 'flex',
                      alignItems: 'flex-start',
                      gap: 1.5,
                    }}
                  >
                    <Box
                      sx={{
                        width: 32,
                        height: 32,
                        borderRadius: '50%',
                        bgcolor: item.type === 'MATCH' ? '#eff6ff' : '#faf5ff',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flexShrink: 0,
                        mt: 0.25,
                      }}
                    >
                      {item.type === 'MATCH'
                        ? <Target size={16} color="#1e3a5f" />
                        : <TrendingUp size={16} color="#7c3aed" />
                      }
                    </Box>
                    <Box sx={{ flex: 1, minWidth: 0 }}>
                      <Typography variant="body2" sx={{ fontWeight: 500 }} noWrap>
                        {item.title}
                      </Typography>
                      <Stack direction="row" spacing={0.5} sx={{ mt: 0.5, flexWrap: 'wrap' }}>
                        <Chip
                          label={getPriorityLabel(item.confidence)}
                          size="small"
                          color={getPriorityColor(item.confidence)}
                          variant="outlined"
                          sx={{ fontSize: 10 }}
                        />
                        <Chip
                          label="Ausstehend"
                          size="small"
                          sx={{ bgcolor: '#fef3c7', color: '#92400e', fontSize: 10 }}
                        />
                      </Stack>
                    </Box>
                  </Box>
                ))}
              </Box>
            )}
          </Card>

          {/* Right: Review Panel */}
          <Card sx={{ p: 0, overflow: 'hidden' }}>
            {!selectedItem ? (
              <EmptyState
                title="Wählen Sie ein Element zur Prüfung"
                description="Klicken Sie auf ein Element in der Liste, um es zu prüfen."
              />
            ) : (
              <Box>
                <Box sx={{ px: 2.5, py: 2, borderBottom: '1px solid #f1f5f9' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
                    <Chip
                      label={selectedItem.type === 'MATCH' ? 'Match' : 'Signal'}
                      size="small"
                      sx={{
                        bgcolor: selectedItem.type === 'MATCH' ? '#eff6ff' : '#faf5ff',
                        color: selectedItem.type === 'MATCH' ? '#1e3a5f' : '#7c3aed',
                        fontWeight: 600,
                      }}
                    />
                    <Typography variant="subtitle2" sx={{ fontWeight: 600 }}>
                      {selectedItem.title}
                    </Typography>
                  </Box>
                </Box>

                <Box sx={{ px: 2.5, py: 2 }}>
                  {/* Key facts */}
                  <Stack spacing={1} sx={{ mb: 2 }}>
                    <Box sx={{ display: 'flex', gap: 3 }}>
                      <Box>
                        <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>Konfidenz</Typography>
                        <Typography variant="body2" sx={{ fontWeight: 600 }}>
                          {Math.round(selectedItem.confidence * 100)}%
                        </Typography>
                      </Box>
                      {selectedItem.probability != null && (
                        <Box>
                          <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>Wahrscheinlichkeit</Typography>
                          <Typography variant="body2" sx={{ fontWeight: 600 }}>
                            {Math.round(selectedItem.probability * 100)}%
                          </Typography>
                        </Box>
                      )}
                      <Box>
                        <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>Risiko</Typography>
                        <Chip label={getRiskLabel(selectedItem.risk)}
                          size="small"
                          color={getRiskColor(selectedItem.risk)}
                          variant="outlined"
                        />
                      </Box>
                    </Box>
                  </Stack>

                  {selectedItem.summary && (
                    <Alert severity="info" sx={{ mb: 2, '& .MuiAlert-message': { fontSize: 13 } }}>
                      {selectedItem.summary}
                    </Alert>
                  )}

                  <Divider sx={{ mb: 2 }} />

                  {/* Notes */}
                  <Typography variant="caption" sx={{ fontWeight: 600, display: 'block', mb: 1 }} color="text.secondary">
                    Notizen
                  </Typography>
                  <TextField
                    multiline
                    rows={3}
                    fullWidth
                    placeholder="Optionale Anmerkungen zur Entscheidung..."
                    value={reviewNotes}
                    onChange={e => setReviewNotes(e.target.value)}
                    size="small"
                    sx={{ mb: 2 }}
                  />

                  {/* Decision buttons */}
                  <Stack spacing={1}>
                    <Button
                      variant="contained"
                      fullWidth
                      onClick={handleApprove}
                      sx={{ bgcolor: '#1a7a4a', '&:hover': { bgcolor: '#155f3a' } }}
                    >
                      Genehmigen
                    </Button>
                    <Button
                      variant="outlined"
                      fullWidth
                      color="error"
                      onClick={handleReject}
                    >
                      Ablehnen
                    </Button>
                    <Button
                      variant="outlined"
                      fullWidth
                      sx={{ color: '#64748b', borderColor: '#e2e8f0' }}
                    >
                      Weiterleiten
                    </Button>
                  </Stack>
                </Box>
              </Box>
            )}
          </Card>
        </Box>
      </Box>
    </Box>
  )
}
