import { useState } from 'react'
import { Box, Chip, Typography } from '@mui/material'
import { ShieldCheck } from 'lucide-react'
import {
  ReviewFilterBar,
  ReviewTaskCard,
  ReviewDetailPanel,
  ReviewEmptyState,
} from '../../components/review'
import { useReviewQueue, useUpdateReviewStatus, useAddReviewNote } from '../../hooks/useReviewQueue'
import { useSessionStore } from '../../stores/sessionStore'
import { useToastStore } from '../../stores/toastStore'
import type { ReviewTask, ReviewTaskStatus } from '../../domain/review'
import type { ReviewFilters } from '../../provider/IReviewProvider'

function filterTasks(tasks: ReviewTask[], filters: ReviewFilters): ReviewTask[] {
  return tasks.filter(t => {
    if (filters.status && t.status !== filters.status) return false
    if (filters.priority && t.priority !== filters.priority) return false
    if (filters.entityType && t.entityType !== filters.entityType) return false
    if (filters.assignedTo && t.assignedTo !== filters.assignedTo) return false
    return true
  })
}

export default function ReviewQueue() {
  const { currentUser } = useSessionStore()
  const showToast = useToastStore((s) => s.showToast)
  const userRole = currentUser?.role ?? 'REVIEWER'

  const [filters, setFilters] = useState<ReviewFilters>({})
  const [selectedTask, setSelectedTask] = useState<ReviewTask | null>(null)

  const { data: allTasks = [], isLoading } = useReviewQueue()
  const updateStatus = useUpdateReviewStatus()
  const addNote = useAddReviewNote()

  const filtered = filterTasks(allTasks, filters)

  const pendingCount = allTasks.filter(t => t.status === 'PENDING').length
  const inReviewCount = allTasks.filter(t => t.status === 'IN_REVIEW').length
  const escalatedCount = allTasks.filter(t => t.status === 'ESCALATED').length
  const criticalCount = allTasks.filter(t => t.priority === 'CRITICAL' && (t.status === 'PENDING' || t.status === 'IN_REVIEW')).length

  const STATUS_TOAST: Record<ReviewTaskStatus, string> = {
    PENDING: 'Status auf "Ausstehend" gesetzt.',
    IN_REVIEW: 'Aufgabe zur Prüfung übernommen.',
    APPROVED: 'Aufgabe genehmigt.',
    REJECTED: 'Aufgabe abgelehnt.',
    ESCALATED: 'Aufgabe eskaliert.',
    NEEDS_MORE_DATA: 'Weitere Daten angefordert.',
  }

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

  const handleAddNote = (content: string) => {
    if (!selectedTask) return
    addNote.mutate(
      { id: selectedTask.id, content },
      {
        onSuccess: (res) => {
          setSelectedTask(res.data)
          showToast('Notiz hinzugefügt.')
        },
        onError: () => showToast('Notiz konnte nicht gespeichert werden.', 'error'),
      }
    )
  }

  const handleSelect = (task: ReviewTask) => {
    setSelectedTask(task)
  }

  const isSubmitting = updateStatus.isPending || addNote.isPending

  if (!currentUser || !currentUser.allowedWorkspaces.includes('OPERATIONS')) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 56px)', overflow: 'hidden' }}>
        <ReviewEmptyState variant="no-permission" />
      </Box>
    )
  }

  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 }}>
          <ShieldCheck size={18} color="#1e3a5f" />
          <Typography variant="h6" sx={{ fontWeight: 700, fontSize: '1rem', color: '#1e293b' }}>
            Review Queue
          </Typography>
          <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap' }}>
            {pendingCount > 0 && (
              <Chip
                label={`${pendingCount} Ausstehend`}
                size="small"
                sx={{ bgcolor: '#fef3c7', color: '#92400e', fontWeight: 600, fontSize: '0.7rem' }}
              />
            )}
            {inReviewCount > 0 && (
              <Chip
                label={`${inReviewCount} In Prüfung`}
                size="small"
                sx={{ bgcolor: '#e0f2fe', color: '#075985', fontWeight: 600, fontSize: '0.7rem' }}
              />
            )}
            {escalatedCount > 0 && (
              <Chip
                label={`${escalatedCount} Eskaliert`}
                size="small"
                sx={{ bgcolor: '#fff7ed', color: '#c2410c', fontWeight: 600, fontSize: '0.7rem' }}
              />
            )}
            {criticalCount > 0 && (
              <Chip
                label={`${criticalCount} Kritisch`}
                size="small"
                sx={{ bgcolor: '#fee2e2', color: '#991b1b', fontWeight: 600, fontSize: '0.7rem' }}
              />
            )}
          </Box>
        </Box>
        <Typography variant="caption" color="text.secondary">
          Human-in-the-loop Governance für KI-Outputs, Matches und Datenfehler
        </Typography>
      </Box>

      {/* Filter bar */}
      <ReviewFilterBar
        filters={filters}
        onChange={setFilters}
        totalCount={allTasks.length}
        filteredCount={filtered.length}
      />

      {/* Body */}
      <Box sx={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* Left: task list */}
        <Box
          sx={{
            width: 360,
            flexShrink: 0,
            borderRight: '1px solid #e2e8f0',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
          }}
        >
          {isLoading ? (
            <Box sx={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Typography variant="caption" color="text.secondary">Laden…</Typography>
            </Box>
          ) : filtered.length === 0 ? (
            <ReviewEmptyState variant={allTasks.length === 0 ? 'empty-queue' : 'empty-queue'} />
          ) : (
            <Box sx={{ flex: 1, overflowY: 'auto' }}>
              {filtered.map(task => (
                <ReviewTaskCard
                  key={task.id}
                  task={task}
                  isSelected={selectedTask?.id === task.id}
                  onSelect={handleSelect}
                />
              ))}
            </Box>
          )}
        </Box>

        {/* Right: detail panel */}
        <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', bgcolor: 'white' }}>
          {selectedTask ? (
            <ReviewDetailPanel
              task={selectedTask}
              userRole={userRole}
              onClose={() => setSelectedTask(null)}
              onAction={handleAction}
              onAddNote={handleAddNote}
              isSubmitting={isSubmitting}
            />
          ) : (
            <ReviewEmptyState variant="no-selection" />
          )}
        </Box>
      </Box>
    </Box>
  )
}
