import { useState } from 'react'
import { useNavigate } from 'react-router'
import {
  Box, Card, Chip, IconButton, Typography,
  Dialog, DialogTitle, DialogContent, DialogActions, Button, TextField,
} from '@mui/material'
import { X, MessageSquare, ExternalLink } from 'lucide-react'
import { useRemoveFromShortlist } from '../../hooks/useShortlists'
import { useToastStore } from '../../stores/toastStore'
import type { ShortlistItem } from '../../domain/shortlist'

const RESULT_TYPE_LABEL: Record<string, string> = {
  VERIFIED_PORTFOLIO: 'Portfolio',
  MAISON_WORK: 'Maison Work',
  FUTURE_AVAILABILITY: 'Signal',
}

const SCORE_COLOR = (s: number) => s >= 75 ? '#1a7a4a' : s >= 55 ? '#d97706' : '#c0392b'

interface Props {
  item: ShortlistItem
  shortlistId: string
  isFinalized: boolean
  view?: 'list' | 'grid'
}

export function ShortlistItemCard({ item, shortlistId, isFinalized, view = 'list' }: Props) {
  const navigate = useNavigate()
  const removeItem = useRemoveFromShortlist()
  const showToast = useToastStore((s) => s.showToast)
  const [inquiryOpen, setInquiryOpen] = useState(false)
  const [inquiryMsg, setInquiryMsg] = useState('')

  const addedDate = new Date(item.addedAt).toLocaleDateString('de-CH', { day: '2-digit', month: '2-digit', year: 'numeric' })

  const detailPath = item.propertyId
    ? `/demand/property/${item.propertyId}`
    : `/demand/results/${item.resultId}`

  function handleCardClick() {
    navigate(detailPath)
  }

  function handleSendInquiry() {
    if (!inquiryMsg.trim()) return
    showToast('Anfrage gesendet. Sie finden sie unter Anfragen.')
    setInquiryOpen(false)
    setInquiryMsg('')
    navigate('/demand/anfragen')
  }

  const removeBtn = !isFinalized && (
    <IconButton
      size="small"
      disabled={removeItem.isPending}
      onClick={e => {
        e.stopPropagation()
        removeItem.mutate(
          { shortlistId, resultId: item.resultId },
          {
            onSuccess: () => showToast('Objekt aus Shortlist entfernt.'),
            onError: () => showToast('Entfernen fehlgeschlagen.', 'error'),
          }
        )
      }}
      sx={{ color: '#94a3b8', '&:hover': { color: '#c0392b' }, flexShrink: 0 }}
    >
      <X size={14} />
    </IconButton>
  )

  const inquiryDialog = (
    <Dialog open={inquiryOpen} onClose={() => setInquiryOpen(false)} maxWidth="sm" fullWidth>
      <DialogTitle sx={{ fontWeight: 700, fontSize: '1rem', pb: 1 }}>
        Anfrage stellen
      </DialogTitle>
      <DialogContent sx={{ pt: 0 }}>
        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
          <strong>{item.title}</strong>
        </Typography>
        <TextField
          label="Betreff"
          size="small"
          fullWidth
          defaultValue={`Anfrage zu ${item.title}`}
          sx={{ mb: 2 }}
        />
        <TextField
          label="Nachricht"
          multiline
          minRows={4}
          fullWidth
          size="small"
          placeholder="Beschreiben Sie Ihr Interesse und Ihre Anforderungen…"
          value={inquiryMsg}
          onChange={e => setInquiryMsg(e.target.value)}
        />
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button size="small" onClick={() => setInquiryOpen(false)}>Abbrechen</Button>
        <Button
          size="small"
          variant="contained"
          onClick={handleSendInquiry}
          disabled={!inquiryMsg.trim()}
          sx={{ bgcolor: '#152642', '&:hover': { bgcolor: '#1a3050' } }}
        >
          Anfrage senden
        </Button>
      </DialogActions>
    </Dialog>
  )

  if (view === 'grid') {
    return (
      <>
        <Card
          onClick={handleCardClick}
          sx={{
            p: 2, opacity: isFinalized ? 0.75 : 1,
            display: 'flex', flexDirection: 'column', gap: 1, height: '100%',
            cursor: 'pointer',
            '&:hover': { boxShadow: '0 4px 12px rgba(0,0,0,0.12)', borderColor: '#bfdbfe' },
            transition: 'box-shadow 0.15s ease, border-color 0.15s ease',
            border: '1px solid #e2e8f0',
          }}
        >
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <Box sx={{
              width: 44, height: 44, borderRadius: '50%', flexShrink: 0,
              bgcolor: SCORE_COLOR(item.matchScore),
              display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
            }}>
              <Typography sx={{ fontWeight: 800, fontSize: '0.95rem', color: 'white', lineHeight: 1 }}>
                {item.matchScore}
              </Typography>
            </Box>
            <Box sx={{ display: 'flex', gap: 0.25 }}>
              {!isFinalized && item.resultType !== 'FUTURE_AVAILABILITY' && (
                <IconButton
                  size="small"
                  onClick={e => { e.stopPropagation(); setInquiryOpen(true) }}
                  sx={{ color: '#94a3b8', '&:hover': { color: '#152642' } }}
                >
                  <MessageSquare size={14} />
                </IconButton>
              )}
              {removeBtn}
            </Box>
          </Box>
          <Typography variant="body2" sx={{ fontWeight: 700, lineHeight: 1.3 }}>{item.title}</Typography>
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
            <Chip
              label={RESULT_TYPE_LABEL[item.resultType] ?? item.resultType}
              size="small"
              sx={{ fontSize: 10, height: 18 }}
            />
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mt: 'auto' }}>
            <Typography variant="caption" color="text.secondary" sx={{ flex: 1 }}>
              {item.addedBy} · {addedDate}
            </Typography>
            <ExternalLink size={11} color="#94a3b8" />
          </Box>
          {item.note && (
            <Typography variant="caption" sx={{ color: '#475569', fontStyle: 'italic' }}>
              {item.note}
            </Typography>
          )}
        </Card>
        {inquiryDialog}
      </>
    )
  }

  return (
    <>
      <Box
        onClick={handleCardClick}
        sx={{
          p: 2,
          borderBottom: '1px solid #f1f5f9',
          opacity: isFinalized ? 0.75 : 1,
          display: 'flex',
          gap: 1.5,
          alignItems: 'flex-start',
          cursor: 'pointer',
          '&:hover': { bgcolor: '#f8fafc' },
          transition: 'background-color 0.1s ease',
        }}
      >
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
            <Typography variant="body2" sx={{ fontWeight: 600, color: '#152642' }}>{item.title}</Typography>
            <Chip
              label={RESULT_TYPE_LABEL[item.resultType] ?? item.resultType}
              size="small"
              sx={{ fontSize: 10, height: 18 }}
            />
            <Chip
              label={`${item.matchScore}`}
              size="small"
              sx={{ bgcolor: SCORE_COLOR(item.matchScore), color: 'white', fontSize: 10, height: 18, fontWeight: 700 }}
            />
          </Box>
          <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
            {item.sourceLabel ?? item.resultType} · {item.addedBy} · {addedDate}
          </Typography>
          {item.note && (
            <Typography variant="caption" sx={{ display: 'block', mt: 0.5, color: '#475569', fontStyle: 'italic' }}>
              {item.note}
            </Typography>
          )}
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.25 }}>
          {!isFinalized && item.resultType !== 'FUTURE_AVAILABILITY' && (
            <IconButton
              size="small"
              onClick={e => { e.stopPropagation(); setInquiryOpen(true) }}
              sx={{ color: '#94a3b8', '&:hover': { color: '#152642' } }}
              title="Anfrage stellen"
            >
              <MessageSquare size={14} />
            </IconButton>
          )}
          {removeBtn}
        </Box>
      </Box>
      {inquiryDialog}
    </>
  )
}
