import { useState, useEffect, useRef } from 'react'
import {
  Box, Typography, TextField, Chip, Avatar, IconButton,
  InputAdornment, Paper,
} from '@mui/material'
import { Search, Send, Paperclip, ArrowLeft, FileText, Bot, Building2 } from 'lucide-react'
import { mockInquiries } from '../../mock-data/inquiries'
import type { InquiryMessage } from '../../domain/inquiry'

const STATUS_CONFIG: Record<string, { label: string; color: string; bgColor: string }> = {
  new: { label: 'Neu', color: '#dc2626', bgColor: '#fef2f2' },
  in_progress: { label: 'Aktiv', color: '#d97706', bgColor: '#fffbeb' },
  answered: { label: 'Beantwortet', color: '#1a7a4a', bgColor: '#f0fdf4' },
  archived: { label: 'Archiviert', color: '#64748b', bgColor: '#f8fafc' },
}

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

function MessageBubble({ msg }: { msg: InquiryMessage }) {
  const isOwnMessage = msg.senderType === 'tenant'
  const isAI = msg.senderType === 'ai'
  const time = new Date(msg.createdAt).toLocaleTimeString('de-CH', { hour: '2-digit', minute: '2-digit' })
  const date = new Date(msg.createdAt).toLocaleDateString('de-CH', { day: '2-digit', month: '2-digit' })

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: isOwnMessage ? 'flex-end' : 'flex-start', mb: 0.5 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 0.375 }}>
        {!isOwnMessage && isAI && <Bot size={11} color="#7c3aed" />}
        {!isOwnMessage && msg.senderType === 'supply_user' && <Building2 size={11} color="#64748b" />}
        <Typography variant="caption" color="text.secondary" sx={{ fontSize: '0.7rem' }}>
          {msg.senderName} · {date} {time}
        </Typography>
      </Box>
      <Box
        sx={{
          maxWidth: { xs: '88%', md: '72%' },
          px: 2, py: 1.25,
          borderRadius: isOwnMessage ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
          bgcolor: isOwnMessage ? '#1e3a5f' : isAI ? '#f5f3ff' : 'white',
          border: isOwnMessage ? 'none' : isAI ? '1px solid #ddd6fe' : '1px solid #e2e8f0',
          boxShadow: isOwnMessage ? '0 2px 6px rgba(30,58,95,0.2)' : '0 1px 2px rgba(0,0,0,0.06)',
        }}
      >
        <Typography
          variant="body2"
          sx={{
            color: isOwnMessage ? 'white' : isAI ? '#5b21b6' : '#1e293b',
            whiteSpace: 'pre-wrap',
            lineHeight: 1.65,
            fontSize: '0.875rem',
          }}
        >
          {msg.body}
        </Typography>

        {msg.attachments.length > 0 && (
          <Box sx={{ mt: 1, display: 'flex', flexDirection: 'column', gap: 0.5 }}>
            {msg.attachments.map(att => (
              <Box
                key={att.id}
                sx={{
                  display: 'flex', alignItems: 'center', gap: 1,
                  px: 1.5, py: 0.75,
                  bgcolor: isOwnMessage ? 'rgba(255,255,255,0.12)' : '#f1f5f9',
                  borderRadius: 1.5, cursor: 'pointer',
                  '&:hover': { bgcolor: isOwnMessage ? 'rgba(255,255,255,0.2)' : '#e2e8f0' },
                }}
              >
                <FileText size={13} color={isOwnMessage ? 'rgba(255,255,255,0.75)' : '#64748b'} />
                <Typography variant="caption" sx={{ color: isOwnMessage ? 'rgba(255,255,255,0.9)' : '#475569', flex: 1 }} noWrap>
                  {att.fileName}
                </Typography>
                {att.fileSize && (
                  <Typography variant="caption" sx={{ color: isOwnMessage ? 'rgba(255,255,255,0.5)' : '#94a3b8', flexShrink: 0 }}>
                    {att.fileSize < 1024 * 1024
                      ? `${Math.round(att.fileSize / 1024)} KB`
                      : `${(att.fileSize / 1024 / 1024).toFixed(1)} MB`}
                  </Typography>
                )}
              </Box>
            ))}
          </Box>
        )}
      </Box>
    </Box>
  )
}

export default function Anfragen() {
  const [inquiries, setInquiries] = useState(mockInquiries)
  const [selectedId, setSelectedId] = useState<string | null>(mockInquiries[0]?.id ?? null)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const [replyText, setReplyText] = useState('')
  const [mobileShowChat, setMobileShowChat] = useState(false)
  const threadRef = useRef<HTMLDivElement>(null)

  const filtered = inquiries.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)
    const matchesStatus = statusFilter === 'all' || inq.status === statusFilter
    return matchesSearch && matchesStatus
  })

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

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

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

  function handleSend() {
    if (!replyText.trim() || !selectedId) return
    const msg: InquiryMessage = {
      id: `msg-${Date.now()}`,
      inquiryId: selectedId,
      senderType: 'tenant',
      senderName: 'Sie',
      body: replyText.trim(),
      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('')
  }

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

      {/* ── Left panel: inquiry list ── */}
      <Box
        sx={{
          width: { xs: mobileShowChat ? 0 : '100%', md: 320 },
          minWidth: { md: 320 },
          flexShrink: 0,
          display: 'flex', flexDirection: 'column',
          borderRight: '1px solid #e2e8f0',
          overflow: 'hidden',
          bgcolor: 'white',
          transition: 'width 0.2s ease',
        }}
      >
        {/* List header */}
        <Box sx={{ px: 2, py: 2, borderBottom: '1px solid #e2e8f0' }}>
          <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: '#dc2626', color: 'white', fontWeight: 700, height: 20, fontSize: '0.7rem' }}
              />
            )}
          </Box>
          <TextField
            size="small"
            placeholder="Suchen..."
            fullWidth
            value={search}
            onChange={e => setSearch(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Search size={14} color="#94a3b8" />
                </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 ? '#1e3a5f' : '#f1f5f9',
                  color: statusFilter === tab.key ? 'white' : '#475569',
                  fontWeight: statusFilter === tab.key ? 700 : 400,
                  '&:hover': { bgcolor: statusFilter === tab.key ? '#1a3050' : '#e2e8f0' },
                }}
              />
            ))}
          </Box>
        </Box>

        {/* List body */}
        <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 => {
              const cfg = STATUS_CONFIG[inq.status ?? 'new']
              const isSelected = inq.id === selectedId
              const displayDate = new Date(inq.updatedAt).toLocaleDateString('de-CH', { day: '2-digit', month: '2-digit' })
              const lastMsg = inq.thread[inq.thread.length - 1]

              return (
                <Box
                  key={inq.id}
                  onClick={() => handleSelect(inq.id)}
                  sx={{
                    px: 2, py: 1.5,
                    borderBottom: '1px solid #f1f5f9',
                    cursor: 'pointer',
                    bgcolor: isSelected ? '#eff6ff' : !inq.isRead ? 'rgba(220,38,38,0.03)' : 'transparent',
                    borderLeft: isSelected ? '3px solid #1e3a5f' : '3px solid transparent',
                    '&:hover': { bgcolor: isSelected ? '#eff6ff' : '#f8fafc' },
                    transition: 'background-color 0.1s ease',
                  }}
                >
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 0.375 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, minWidth: 0 }}>
                      {!inq.isRead && (
                        <Box sx={{ width: 7, height: 7, borderRadius: '50%', bgcolor: '#dc2626', flexShrink: 0 }} />
                      )}
                      <Typography
                        variant="body2"
                        sx={{ fontWeight: !inq.isRead ? 700 : 500, fontSize: '0.8125rem' }}
                        noWrap
                      >
                        {inq.tenantName}
                      </Typography>
                    </Box>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, flexShrink: 0 }}>
                      {inq.unreadCount > 0 && (
                        <Box sx={{
                          width: 18, height: 18, borderRadius: '50%', bgcolor: '#dc2626',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                        }}>
                          <Typography sx={{ color: 'white', fontSize: '0.6rem', fontWeight: 700 }}>
                            {inq.unreadCount}
                          </Typography>
                        </Box>
                      )}
                      <Typography variant="caption" color="text.secondary" sx={{ fontSize: '0.7rem' }}>
                        {displayDate}
                      </Typography>
                    </Box>
                  </Box>

                  {inq.tenantCompany && (
                    <Typography variant="caption" color="text.secondary" sx={{ display: 'block', fontSize: '0.7rem', mb: 0.25 }} noWrap>
                      {inq.tenantCompany}
                    </Typography>
                  )}

                  <Typography
                    variant="caption"
                    sx={{ color: '#475569', display: 'block', mb: 0.5, fontWeight: !inq.isRead ? 600 : 400, fontSize: '0.75rem' }}
                    noWrap
                  >
                    {inq.subject}
                  </Typography>

                  {lastMsg && (
                    <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 0.5, fontSize: '0.7rem' }} noWrap>
                      {lastMsg.senderType === 'tenant' ? 'Sie: ' : `${lastMsg.senderName}: `}
                      {lastMsg.body.split('\n')[0]}
                    </Typography>
                  )}

                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Chip
                      label={cfg?.label ?? inq.status}
                      size="small"
                      sx={{ height: 16, fontSize: '0.6rem', bgcolor: cfg?.bgColor, color: cfg?.color, fontWeight: 600 }}
                    />
                    {inq.matchScore && (
                      <Typography
                        variant="caption"
                        sx={{ color: inq.matchScore >= 80 ? '#1a7a4a' : '#d97706', fontWeight: 700, fontSize: '0.7rem' }}
                      >
                        Match {inq.matchScore}%
                      </Typography>
                    )}
                  </Box>
                </Box>
              )
            })
          )}
        </Box>
      </Box>

      {/* ── Right panel: chat thread ── */}
      <Box
        sx={{
          flex: 1,
          display: { xs: mobileShowChat ? 'flex' : 'none', md: 'flex' },
          flexDirection: 'column',
          overflow: 'hidden',
          bgcolor: '#f8fafc',
          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, um die Konversation zu lesen.
            </Typography>
          </Box>
        ) : (
          <>
            {/* Chat header */}
            <Box sx={{ px: 3, py: 1.75, bgcolor: 'white', borderBottom: '1px solid #e2e8f0', 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: '#1e3a5f', fontSize: '0.8rem', flexShrink: 0 }}>
                  {selected.tenantName.split(' ').map(n => 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.tenantName}
                    </Typography>
                    {selected.tenantCompany && (
                      <Typography variant="caption" color="text.secondary">
                        {selected.tenantCompany}
                      </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 ? '#f0fdf4' : '#fffbeb',
                        color: selected.matchScore >= 80 ? '#1a7a4a' : '#d97706',
                        fontWeight: 700, height: 22, fontSize: '0.75rem',
                        border: `1px solid ${selected.matchScore >= 80 ? '#86efac' : '#fde68a'}`,
                      }}
                    />
                  )}
                  <Chip
                    label={STATUS_CONFIG[selected.status ?? 'new']?.label ?? selected.status}
                    size="small"
                    sx={{
                      bgcolor: STATUS_CONFIG[selected.status ?? 'new']?.bgColor,
                      color: STATUS_CONFIG[selected.status ?? 'new']?.color,
                      fontWeight: 600, height: 22, fontSize: '0.75rem',
                    }}
                  />
                </Box>
              </Box>
            </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 => (
                <MessageBubble key={msg.id} msg={msg} />
              ))}
            </Box>

            {/* Composer */}
            <Box sx={{ px: { xs: 2, md: 3 }, py: 2, bgcolor: 'white', borderTop: '1px solid #e2e8f0', 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: '#94a3b8' }}>
                    <Paperclip size={16} />
                  </IconButton>
                  <IconButton
                    size="small"
                    onClick={handleSend}
                    disabled={!replyText.trim()}
                    sx={{
                      bgcolor: '#1e3a5f', color: 'white',
                      '&:hover': { bgcolor: '#1a3050' },
                      '&:disabled': { bgcolor: '#e2e8f0', color: '#94a3b8' },
                    }}
                  >
                    <Send size={16} />
                  </IconButton>
                </Box>
              </Box>
              <Typography variant="caption" color="text.secondary" sx={{ mt: 0.5, display: 'block' }}>
                Ctrl + Enter zum Senden
              </Typography>
            </Box>
          </>
        )}
      </Box>
    </Box>
  )
}
