import { useState } from 'react'
import { Box, Chip, MenuItem, Select, Typography } from '@mui/material'
import { Bot } from 'lucide-react'
import {
  AIMonitoringMetrics,
  AIOutputTable,
  AIOutputDetailPanel,
  AIMonitoringEmptyState,
} from '../../components/ai-monitoring'
import { useAIOutputs, useUpdateAIOutputReviewStatus } from '../../hooks/useAIMonitoring'
import { useToastStore } from '../../stores/toastStore'
import type { AIOutput, AIOutputType } from '../../domain/aiOutput'
import type { ReviewStatus } from '../../domain/enums'

interface Filters {
  type: AIOutputType | ''
  reviewStatus: ReviewStatus | ''
  hasError: boolean | null
}

const TYPE_LABELS: Record<AIOutputType, string> = {
  NEED_PARSE:           'Bedarf-Parsing',
  FOLLOW_UP_QUESTIONS:  'Rückfragen',
  MATCH_EXPLANATION:    'Match-Begründung',
  COMPARE_SUMMARY:      'Vergleich',
  DECISION_BRIEF:       'Entscheidungs-Brief',
  DATA_QUALITY_SUMMARY: 'Datenqualität',
}

const AI_OUTPUT_TYPES: AIOutputType[] = [
  'NEED_PARSE',
  'FOLLOW_UP_QUESTIONS',
  'MATCH_EXPLANATION',
  'COMPARE_SUMMARY',
  'DECISION_BRIEF',
  'DATA_QUALITY_SUMMARY',
]

const REVIEW_STATUSES: ReviewStatus[] = ['UNREVIEWED', 'IN_REVIEW', 'APPROVED', 'REJECTED', 'FLAGGED']
const STATUS_LABELS: Record<ReviewStatus, string> = {
  UNREVIEWED: 'Ungeprüft',
  IN_REVIEW:  'In Prüfung',
  APPROVED:   'Genehmigt',
  REJECTED:   'Abgelehnt',
  FLAGGED:    'Markiert',
}

function applyFilters(outputs: AIOutput[], filters: Filters): AIOutput[] {
  return outputs.filter(o => {
    if (filters.type && o.type !== filters.type) return false
    if (filters.reviewStatus && o.reviewStatus !== filters.reviewStatus) return false
    if (filters.hasError === true && !o.error) return false
    if (filters.hasError === false && !!o.error) return false
    return true
  })
}

export default function AIMonitoring() {
  const [filters, setFilters] = useState<Filters>({ type: '', reviewStatus: '', hasError: null })
  const [selectedOutput, setSelectedOutput] = useState<AIOutput | null>(null)

  const showToast = useToastStore((s) => s.showToast)
  const { data: allOutputs = [], isLoading } = useAIOutputs()
  const updateStatus = useUpdateAIOutputReviewStatus()

  const filtered = applyFilters(allOutputs, filters)

  const failedCount = allOutputs.filter(o => !!o.error).length
  const pendingCount = allOutputs.filter(o => o.reviewStatus === 'UNREVIEWED' || o.reviewStatus === 'FLAGGED').length

  const STATUS_TOAST: Record<ReviewStatus, string> = {
    UNREVIEWED: 'Status zurückgesetzt.',
    IN_REVIEW: 'Output zur Prüfung markiert.',
    APPROVED: 'Output genehmigt.',
    REJECTED: 'Output abgelehnt.',
    FLAGGED: 'Output markiert.',
  }

  const handleUpdateStatus = (status: ReviewStatus) => {
    if (!selectedOutput) return
    updateStatus.mutate(
      { id: selectedOutput.id, status },
      {
        onSuccess: (res) => {
          setSelectedOutput(res.data)
          showToast(STATUS_TOAST[status] ?? 'Status aktualisiert.')
        },
        onError: () => showToast('Statusänderung fehlgeschlagen.', 'error'),
      }
    )
  }

  const activeFilterCount = [filters.type, filters.reviewStatus, filters.hasError !== null].filter(Boolean).length

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 56px)', overflow: 'hidden' }}>
      {/* Header */}
      <Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e2e8f0', px: 2.5, py: 1.5, flexShrink: 0 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 0.5 }}>
          <Bot size={18} color="#4f46e5" />
          <Typography variant="h6" sx={{ fontWeight: 700, fontSize: '1rem', color: '#1e293b' }}>
            AI Monitoring
          </Typography>
          <Box sx={{ display: 'flex', gap: 0.75 }}>
            {failedCount > 0 && (
              <Chip
                label={`${failedCount} Fehler`}
                size="small"
                sx={{ bgcolor: '#fee2e2', color: '#991b1b', fontWeight: 600, fontSize: '0.7rem' }}
              />
            )}
            {pendingCount > 0 && (
              <Chip
                label={`${pendingCount} ausstehend`}
                size="small"
                sx={{ bgcolor: '#fef3c7', color: '#92400e', fontWeight: 600, fontSize: '0.7rem' }}
              />
            )}
          </Box>
        </Box>
        <Typography variant="caption" color="text.secondary">
          Transparenz und Governance für KI-generierte Outputs
        </Typography>
      </Box>

      {/* Metrics strip */}
      {!isLoading && <AIMonitoringMetrics outputs={allOutputs} />}

      {/* Filter bar */}
      <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', px: 2, py: 0.875, borderBottom: '1px solid #e2e8f0', bgcolor: '#fafafa', flexShrink: 0, flexWrap: 'wrap' }}>
        <Select
          size="small"
          value={filters.type}
          onChange={e => setFilters(f => ({ ...f, type: e.target.value as AIOutputType | '' }))}
          displayEmpty
          sx={{ fontSize: '0.75rem', minWidth: 155 }}
        >
          <MenuItem value="">Alle Typen</MenuItem>
          {AI_OUTPUT_TYPES.map(t => (
            <MenuItem key={t} value={t} sx={{ fontSize: '0.75rem' }}>{TYPE_LABELS[t]}</MenuItem>
          ))}
        </Select>

        <Select
          size="small"
          value={filters.reviewStatus}
          onChange={e => setFilters(f => ({ ...f, reviewStatus: e.target.value as ReviewStatus | '' }))}
          displayEmpty
          sx={{ fontSize: '0.75rem', minWidth: 130 }}
        >
          <MenuItem value="">Alle Status</MenuItem>
          {REVIEW_STATUSES.map(s => (
            <MenuItem key={s} value={s} sx={{ fontSize: '0.75rem' }}>{STATUS_LABELS[s]}</MenuItem>
          ))}
        </Select>

        <Chip
          label="Nur Fehler"
          size="small"
          onClick={() => setFilters(f => ({ ...f, hasError: f.hasError === true ? null : true }))}
          sx={{
            cursor: 'pointer',
            bgcolor: filters.hasError === true ? '#fee2e2' : '#f1f5f9',
            color: filters.hasError === true ? '#991b1b' : '#64748b',
            fontWeight: filters.hasError === true ? 700 : 400,
            fontSize: '0.75rem',
          }}
        />

        {activeFilterCount > 0 && (
          <Chip
            label="Filter zurücksetzen"
            size="small"
            onClick={() => setFilters({ type: '', reviewStatus: '', hasError: null })}
            sx={{ cursor: 'pointer', fontSize: '0.75rem', color: '#64748b' }}
          />
        )}

        <Typography variant="caption" color="text.secondary" sx={{ ml: 'auto', whiteSpace: 'nowrap' }}>
          {activeFilterCount > 0 ? `${filtered.length} / ${allOutputs.length}` : `${allOutputs.length} Outputs`}
        </Typography>
      </Box>

      {/* Body */}
      <Box sx={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* Left: table */}
        <Box sx={{ flex: 1, minWidth: 0, overflowY: 'auto', overflowX: 'auto' }}>
          {isLoading ? (
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200 }}>
              <Typography variant="caption" color="text.secondary">Laden…</Typography>
            </Box>
          ) : (
            <AIOutputTable
              outputs={filtered}
              selectedId={selectedOutput?.id ?? null}
              onSelect={setSelectedOutput}
              isEmpty={allOutputs.length === 0}
            />
          )}
        </Box>

        {/* Right: detail panel */}
        <Box
          sx={{
            width: selectedOutput ? 380 : 0,
            flexShrink: 0,
            borderLeft: selectedOutput ? '1px solid #e2e8f0' : 'none',
            overflow: 'hidden',
            transition: 'width 0.15s ease',
            bgcolor: 'white',
          }}
        >
          {selectedOutput ? (
            <AIOutputDetailPanel
              output={selectedOutput}
              onClose={() => setSelectedOutput(null)}
              onUpdateStatus={handleUpdateStatus}
              isSubmitting={updateStatus.isPending}
            />
          ) : null}
        </Box>

        {/* Empty selection hint when no panel open */}
        {!selectedOutput && filtered.length > 0 && (
          <Box
            sx={{
              width: 260,
              flexShrink: 0,
              borderLeft: '1px solid #e2e8f0',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              bgcolor: '#fafafa',
            }}
          >
            <AIMonitoringEmptyState context="no-selection" />
          </Box>
        )}
      </Box>
    </Box>
  )
}
