import { useState, useEffect, useRef } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import {
  Box, Typography, TextField, Chip, Avatar, IconButton,
  InputAdornment, Alert,
} from '@mui/material'
import { Search, Send, Paperclip, ArrowLeft, Bot, Building2, Kanban } from 'lucide-react'
import { mockDemandInquiries } from '../../mock-data/demandInquiries'
import { useInquiryStore } from '../../stores/inquiryStore'
import { usePipelineItems, useMoveStage } from '../../hooks/usePipeline'
import type { InquiryMessage } from '../../domain/inquiry'
import { STAGE_ORDER, STAGE_LABELS, detectKiStage } from './anfragenKiDetection'
import { AnfragenMessageBubble } from '../../components/demand/AnfragenMessageBubble'
import { AnfragenInquiryItem } from '../../components/demand/AnfragenInquiryItem'
import { INQUIRY_STATUS_META, DS_COLORS, DS_TEXT, DS_BG, DS_BORDER, DS_SURFACE } from '../../lib/ds'
import { useSessionStore } from '../../stores/sessionStore'

// ── Config ────────────────────────────────────────────────────────────────────

const FILTER_TABS = [
  { key: 'all',         label: 'Alle' },
  { key: 'new',         label: 'Neu' },
  { key: 'in_progress', label: 'Aktiv' },
  { key: 'answered',    label: 'Beantwortet' },
]

// ── Anfragen page ─────────────────────────────────────────────────────────────

export default function Anfragen() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const { data: pipelineItems = [] } = usePipelineItems()
  const { mutate: moveStage } = useMoveStage()


  const preselectedId = searchParams.get('inquiry')

  const { currentUser } = useSessionStore()
  const storeInquiries = useInquiryStore(s => s.sentInquiries)
  const [inquiries, setInquiries] = useState(mockDemandInquiries)
  const allInquiries = [...storeInquiries, ...inquiries]

  const [selectedId, setSelectedId] = useState<string | null>(
    preselectedId ?? mockDemandInquiries[0]?.id ?? null
  )
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const [replyText, setReplyText] = useState('')
  const [mobileShowChat, setMobileShowChat] = useState(!!preselectedId)
  const [kiAlert, setKiAlert] = useState<{ title: string; stage: string } | null>(null)
  const threadRef = useRef<HTMLDivElement>(null)

  const filtered = allInquiries.filter(inq => {
    const q = search.toLowerCase()
    const matchesSearch = !q ||
      inq.tenantName.toLowerCase().includes(q) ||
      inq.subject.toLowerCase().includes(q) ||
      (inq.tenantCompany?.toLowerCase().includes(q) ?? false) ||
      (inq.propertyAddress?.toLowerCase().includes(q) ?? false) ||
      (inq.propertyManagerName?.toLowerCase().includes(q) ?? false) ||
      (inq.propertyManagerCompany?.toLowerCase().includes(q) ?? false)
    const matchesStatus = statusFilter === 'all' || inq.status === statusFilter
    return matchesSearch && matchesStatus
  })

  const selected = allInquiries.find(i => i.id === selectedId) ?? null
  const totalUnread = allInquiries.reduce((sum, i) => sum + i.unreadCount, 0)

  // Pipeline link for currently selected inquiry
  const linkedPipelineItem = selected?.propertyId
    ? pipelineItems.find(i => i.propertyId === selected.propertyId)
    : (selected ? pipelineItems.find(i => i.inquiryId === selected.id) : undefined)

  useEffect(() => {
    if (threadRef.current) {
      threadRef.current.scrollTop = threadRef.current.scrollHeight
    }
  }, [selected?.thread.length])

  // Auto-dismiss KI alert after 6s
  useEffect(() => {
    if (!kiAlert) return
    const t = setTimeout(() => setKiAlert(null), 6000)
    return () => clearTimeout(t)
  }, [kiAlert])

  function handleSelect(id: string) {
    setSelectedId(id)
    setInquiries(prev => prev.map(i => i.id === id ? { ...i, isRead: true, unreadCount: 0 } : i))
    setMobileShowChat(true)
    setKiAlert(null)
  }

  function handleSend() {
    if (!replyText.trim() || !selectedId) return
    const text = replyText.trim()

    const msg: InquiryMessage = {
      id: `msg-${Date.now()}`,
      inquiryId: selectedId,
      senderType: 'tenant',
      senderName: 'Sie',
      body: text,
      attachments: [],
      createdAt: new Date().toISOString(),
    }
    setInquiries(prev => prev.map(i =>
      i.id === selectedId
        ? { ...i, thread: [...i.thread, msg], status: 'in_progress', updatedAt: new Date().toISOString() }
        : i
    ))
    setReplyText('')

    // KI: detect stage transition from message content
    const ki = detectKiStage(text)
    if (ki && selected) {
      const pipelineItem = selected.propertyId
        ? pipelineItems.find(i => i.propertyId === selected.propertyId)
        : pipelineItems.find(i => i.inquiryId === selectedId)
      if (pipelineItem) {
        const currentIdx = STAGE_ORDER.indexOf(pipelineItem.stage)
        const targetIdx = STAGE_ORDER.indexOf(ki.stage)
        if (targetIdx > currentIdx) {
          moveStage({ id: pipelineItem.id, stage: ki.stage })
          setKiAlert({ title: pipelineItem.title, stage: STAGE_LABELS[ki.stage] })
        }
      }
    }
  }

  return (
    <Box sx={{ display: 'flex', height: '100%', overflow: 'hidden' }}>

      {/* ── Left panel ── */}
      <Box
        sx={{
          width: { xs: mobileShowChat ? 0 : '100%', md: 280, lg: 300, xl: 320 },
          minWidth: { md: 280, lg: 300, xl: 320 },
          flexShrink: 0,
          display: 'flex', flexDirection: 'column',
          borderRight: `1px solid ${DS_BORDER.default}`,
          overflow: 'hidden',
          bgcolor: 'white',
          transition: 'width 0.2s ease',
        }}
      >
        <Box sx={{ px: 2, py: 2, borderBottom: `1px solid ${DS_BORDER.default}` }}>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1.5 }}>
            <Typography variant="h6" sx={{ fontWeight: 700, fontSize: '1rem' }}>Anfragen</Typography>
            {totalUnread > 0 && (
              <Chip label={`${totalUnread} neu`} size="small"
                sx={{ bgcolor: INQUIRY_STATUS_META.new.fg, color: 'white', fontWeight: 700, height: 20, fontSize: '0.7rem' }} />
            )}
          </Box>
          <TextField
            size="small" placeholder="Suchen..." fullWidth
            value={search} onChange={e => setSearch(e.target.value)}
            slotProps={{ input: { startAdornment: <InputAdornment position="start"><Search size={14} color={DS_TEXT.disabled} /></InputAdornment> } }}
            sx={{ mb: 1.25 }}
          />
          <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
            {FILTER_TABS.map(tab => (
              <Chip key={tab.key} label={tab.label} size="small" onClick={() => setStatusFilter(tab.key)}
                sx={{
                  height: 22, fontSize: '0.7rem', cursor: 'pointer',
                  bgcolor: statusFilter === tab.key ? 'primary.main' : DS_BG.subtle,
                  color: statusFilter === tab.key ? 'white' : DS_TEXT.secondary,
                  fontWeight: statusFilter === tab.key ? 700 : 400,
                  '&:hover': { bgcolor: statusFilter === tab.key ? 'primary.dark' : DS_BG.muted },
                }}
              />
            ))}
          </Box>
        </Box>

        <Box sx={{ flex: 1, overflowY: 'auto' }}>
          {filtered.length === 0 ? (
            <Box sx={{ p: 3, textAlign: 'center' }}>
              <Typography variant="body2" color="text.secondary">Keine Anfragen gefunden.</Typography>
            </Box>
          ) : filtered.map(inq => (
            <AnfragenInquiryItem
              key={inq.id}
              inq={inq}
              isSelected={inq.id === selectedId}
              hasPipeline={!!(inq.propertyId ? pipelineItems.find(i => i.propertyId === inq.propertyId) : pipelineItems.find(i => i.inquiryId === inq.id))}
              perspective="demand"
              onSelect={handleSelect}
            />
          ))}
        </Box>
      </Box>

      {/* ── Right panel: chat ── */}
      <Box sx={{
        flex: 1,
        display: { xs: mobileShowChat ? 'flex' : 'none', md: 'flex' },
        flexDirection: 'column',
        overflow: 'hidden',
        bgcolor: DS_BG.page,
        minWidth: 0,
      }}>
        {!selected ? (
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', flexDirection: 'column', gap: 1 }}>
            <Typography variant="body1" color="text.secondary" sx={{ fontWeight: 500 }}>Anfrage auswählen</Typography>
            <Typography variant="caption" color="text.secondary">Wählen Sie links eine Anfrage aus.</Typography>
          </Box>
        ) : (
          <>
            {/* Chat header */}
            <Box sx={{ px: 3, py: 1.75, bgcolor: 'white', borderBottom: `1px solid ${DS_BORDER.default}`, flexShrink: 0 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                <IconButton size="small" sx={{ display: { md: 'none' }, mr: -0.5 }} onClick={() => setMobileShowChat(false)}>
                  <ArrowLeft size={16} />
                </IconButton>
                <Avatar sx={{ width: 36, height: 36, bgcolor: 'primary.main', fontSize: '0.8rem', flexShrink: 0 }}>
                  {(selected.propertyAddress ?? selected.subject).split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2)}
                </Avatar>
                <Box sx={{ flex: 1, minWidth: 0 }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
                    <Typography variant="body2" sx={{ fontWeight: 700, fontSize: '0.9rem' }}>{selected.propertyAddress ?? selected.subject}</Typography>
                    {(selected.propertyManagerCompany ?? selected.propertyManagerName) && (
                      <Typography variant="caption" color="text.secondary">
                        {selected.propertyManagerCompany ?? selected.propertyManagerName ?? ''}
                      </Typography>
                    )}
                  </Box>
                  <Typography variant="caption" color="text.secondary" noWrap sx={{ display: 'block' }}>
                    {selected.subject}
                  </Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexShrink: 0 }}>
                  {selected.matchScore && (
                    <Chip label={`${selected.matchScore}%`} size="small" sx={{
                      bgcolor: selected.matchScore >= 80 ? DS_SURFACE.success.bg : DS_SURFACE.warning.bg,
                      color: selected.matchScore >= 80 ? DS_TEXT.success : DS_TEXT.warning,
                      fontWeight: 700, height: 22, fontSize: '0.75rem',
                      border: `1px solid ${selected.matchScore >= 80 ? DS_SURFACE.success.border : DS_SURFACE.warning.border}`,
                    }} />
                  )}
                  <Chip
                    label={INQUIRY_STATUS_META[selected.status ?? 'new']?.label ?? selected.status}
                    size="small"
                    sx={{ bgcolor: INQUIRY_STATUS_META[selected.status ?? 'new']?.bg, color: INQUIRY_STATUS_META[selected.status ?? 'new']?.fg, fontWeight: 600, height: 22, fontSize: '0.75rem' }}
                  />
                  {/* Pipeline link */}
                  {linkedPipelineItem && (
                    <Chip
                      icon={<Kanban size={11} />}
                      label={STAGE_LABELS[linkedPipelineItem.stage] ?? linkedPipelineItem.stage}
                      size="small"
                      onClick={() => navigate('/demand/pipeline')}
                      sx={{
                        height: 22, fontSize: '0.75rem', cursor: 'pointer',
                        bgcolor: DS_COLORS.futureCard.signal.headerBg, fontWeight: 600,
                        color: 'primary.main',
                        border: `1px solid ${DS_COLORS.futureCard.signal.border}`,
                        '& .MuiChip-icon': { color: 'primary.main' },
                        '&:hover': { bgcolor: DS_COLORS.futureCard.signal.badgeBg },
                      }}
                    />
                  )}
                </Box>
              </Box>

              {/* Property reference */}
              {(linkedPipelineItem?.propertyAddress ?? selected.subject) && (
                <Box sx={{ mt: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Building2 size={12} color={DS_TEXT.muted} />
                  <Typography variant="caption" color="text.secondary">
                    {linkedPipelineItem?.propertyAddress ?? selected.subject}
                  </Typography>
                </Box>
              )}
            </Box>

            {/* KI stage-change alert */}
            {kiAlert && (
              <Box sx={{ px: 3, pt: 1.5, flexShrink: 0 }}>
                <Alert
                  severity="info"
                  icon={<Bot size={16} />}
                  onClose={() => setKiAlert(null)}
                  sx={{ py: 0.5, bgcolor: DS_COLORS.futureCard.controlled.headerBg, color: DS_COLORS.futureCard.controlled.badgeText, border: `1px solid ${DS_COLORS.futureCard.controlled.border}`, '& .MuiAlert-icon': { color: DS_COLORS.futureCard.controlled.accent } }}
                >
                  <strong>KI erkannt:</strong> „{kiAlert.title}" wurde in der Pipeline auf <strong>{kiAlert.stage}</strong> verschoben.{' '}
                  <Box component="span" sx={{ cursor: 'pointer', textDecoration: 'underline' }} onClick={() => navigate('/demand/pipeline')}>
                    Pipeline öffnen
                  </Box>
                </Alert>
              </Box>
            )}

            {/* Thread */}
            <Box ref={threadRef} sx={{ flex: 1, overflowY: 'auto', px: { xs: 2, md: 3 }, py: 2.5, display: 'flex', flexDirection: 'column', gap: 0.5 }}>
              {selected.thread.map(msg => (
                <AnfragenMessageBubble key={msg.id} msg={msg} currentUserName={currentUser?.name ?? undefined} />
              ))}
            </Box>

            {/* Composer */}
            <Box sx={{ px: { xs: 2, md: 3 }, py: 2, bgcolor: 'white', borderTop: `1px solid ${DS_BORDER.default}`, flexShrink: 0 }}>
              <Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-end' }}>
                <TextField
                  multiline minRows={2} maxRows={6} fullWidth size="small"
                  placeholder="Antwort schreiben…"
                  value={replyText}
                  onChange={e => setReplyText(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter' && e.ctrlKey) handleSend() }}
                  sx={{ '& .MuiOutlinedInput-root': { borderRadius: 2 } }}
                />
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
                  <IconButton size="small" sx={{ color: DS_TEXT.disabled }}><Paperclip size={16} /></IconButton>
                  <IconButton size="small" onClick={handleSend} disabled={!replyText.trim()}
                    sx={{ bgcolor: 'primary.main', color: 'white', '&:hover': { bgcolor: 'primary.dark' }, '&:disabled': { bgcolor: DS_BG.muted, color: DS_TEXT.disabled } }}>
                    <Send size={16} />
                  </IconButton>
                </Box>
              </Box>
              <Typography variant="caption" color="text.secondary" sx={{ mt: 0.5, display: 'block' }}>
                Ctrl + Enter · KI erkennt Terminvereinbarungen automatisch
              </Typography>
            </Box>
          </>
        )}
      </Box>
    </Box>
  )
}
