import { useState } from 'react'
import { Alert, Box, Button, Chip, TextField, Typography } from '@mui/material'
import { useNavigate } from 'react-router'
import { CheckCircle, Columns2, Pencil } from 'lucide-react'
import { ShortlistStatusBadge } from './ShortlistStatusBadge'
import { ShortlistItemCard } from './ShortlistItemCard'
import { ShortlistEmptyState } from './ShortlistEmptyState'
import { useUpdateShortlist } from '../../hooks/useShortlists'
import { useCompareStore } from '../../stores/compareStore'
import { useToastStore } from '../../stores/toastStore'
import { ShortlistStatus } from '../../domain/enums'
import type { Shortlist } from '../../domain/shortlist'

interface Props {
  shortlist: Shortlist
}

export function ShortlistDetail({ shortlist }: Props) {
  const navigate = useNavigate()
  const updateShortlist = useUpdateShortlist()
  const { addToCompare, compareItems } = useCompareStore()
  const showToast = useToastStore((s) => s.showToast)

  const [editingTitle, setEditingTitle] = useState(false)
  const [titleDraft, setTitleDraft] = useState(shortlist.title)

  const isFinalized = shortlist.status === ShortlistStatus.FINALIZED
  const isDraft = shortlist.status === ShortlistStatus.DRAFT
  const isReviewReady = shortlist.status === ShortlistStatus.REVIEW_READY

  function handleTitleSave() {
    if (titleDraft.trim() && titleDraft.trim() !== shortlist.title) {
      updateShortlist.mutate(
        { id: shortlist.id, data: { title: titleDraft.trim() } },
        {
          onSuccess: () => showToast('Titel gespeichert.'),
          onError: () => showToast('Titel konnte nicht gespeichert werden.', 'error'),
        }
      )
    }
    setEditingTitle(false)
  }

  function handleMarkReviewReady() {
    updateShortlist.mutate(
      { id: shortlist.id, data: { status: ShortlistStatus.REVIEW_READY } },
      {
        onSuccess: () => showToast('Shortlist als prüfbereit markiert.'),
        onError: () => showToast('Statusänderung fehlgeschlagen.', 'error'),
      }
    )
  }

  function handleFinalize() {
    updateShortlist.mutate(
      { id: shortlist.id, data: { status: ShortlistStatus.FINALIZED } },
      {
        onSuccess: () => showToast('Shortlist finalisiert.'),
        onError: () => showToast('Finalisierung fehlgeschlagen.', 'error'),
      }
    )
  }

  function handleOpenCompare() {
    for (const item of shortlist.items) {
      if (item.resultType === 'FUTURE_AVAILABILITY') continue
      // Build a minimal UnifiedMatchResult-compatible object for compare
      const fakeResult = {
        matchId: item.resultId,
        needId: '',
        matchScore: item.matchScore,
        resultType: item.resultType as 'VERIFIED_PORTFOLIO' | 'EXTERNAL_MARKET',
        property: { id: item.propertyId ?? item.resultId, title: item.title } as any,
        match: { id: item.resultId, matchScore: item.matchScore, confidenceLevel: item.confidenceScore ?? 0.8 } as any,
      }
      if (compareItems.length < 4) addToCompare(fakeResult as any)
    }
    navigate('/demand/compare')
  }

  const updatedDate = new Date(shortlist.updatedAt).toLocaleDateString('de-CH', {
    day: '2-digit', month: '2-digit', year: 'numeric',
  })

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      {/* Header */}
      <Box sx={{ px: 3, py: 2.5, borderBottom: '1px solid #e2e8f0', bgcolor: 'white', flexShrink: 0 }}>
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1.5, mb: 1.5 }}>
          {editingTitle ? (
            <TextField
              size="small"
              autoFocus
              value={titleDraft}
              onChange={e => setTitleDraft(e.target.value)}
              onBlur={handleTitleSave}
              onKeyDown={e => { if (e.key === 'Enter') handleTitleSave(); if (e.key === 'Escape') { setTitleDraft(shortlist.title); setEditingTitle(false) } }}
              sx={{ flex: 1, '& .MuiInputBase-input': { fontSize: '1.1rem', fontWeight: 700 } }}
            />
          ) : (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, flex: 1 }}>
              <Typography variant="h6" sx={{ fontWeight: 700 }}>{shortlist.title}</Typography>
              {!isFinalized && (
                <Button
                  size="small"
                  onClick={() => { setTitleDraft(shortlist.title); setEditingTitle(true) }}
                  sx={{ minWidth: 0, p: 0.5, color: '#94a3b8' }}
                >
                  <Pencil size={14} />
                </Button>
              )}
            </Box>
          )}
          <ShortlistStatusBadge status={shortlist.status} />
        </Box>

        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: '4px 16px', mb: 1.5 }}>
          <Typography variant="caption" color="text.secondary">
            <strong>{shortlist.items.length}</strong> Objekte
          </Typography>
          <Typography variant="caption" color="text.secondary">
            Erstellt von {shortlist.createdBy}
          </Typography>
          {shortlist.organizationId && (
            <Typography variant="caption" color="text.secondary">
              {shortlist.organizationId}
            </Typography>
          )}
          <Typography variant="caption" color="text.secondary">
            Aktualisiert {updatedDate}
          </Typography>
        </Box>

        {isFinalized && (
          <Alert severity="warning" icon={<CheckCircle size={16} />} sx={{ mb: 1.5, py: 0.25 }}>
            Diese Shortlist ist finalisiert — keine Änderungen möglich.
          </Alert>
        )}

        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
          {isDraft && (
            <Button
              size="small"
              variant="outlined"
              onClick={handleMarkReviewReady}
              disabled={updateShortlist.isPending}
              sx={{ color: '#d97706', borderColor: '#d97706' }}
            >
              Prüfbereit markieren
            </Button>
          )}
          {isReviewReady && (
            <Button
              size="small"
              variant="outlined"
              onClick={handleFinalize}
              disabled={updateShortlist.isPending}
              sx={{ color: '#1a7a4a', borderColor: '#1a7a4a' }}
            >
              Finalisieren
            </Button>
          )}
          {shortlist.items.length > 0 && (
            <Button
              size="small"
              variant="outlined"
              startIcon={<Columns2 size={14} />}
              onClick={handleOpenCompare}
            >
              Im Vergleich öffnen
            </Button>
          )}
          {shortlist.description && (
            <Chip label={shortlist.description} size="small" variant="outlined" sx={{ fontSize: 11 }} />
          )}
        </Box>
      </Box>

      {/* Items */}
      <Box sx={{ flex: 1, overflowY: 'auto' }}>
        {shortlist.items.length === 0
          ? <ShortlistEmptyState context="empty-shortlist" />
          : shortlist.items.map(item => (
              <ShortlistItemCard
                key={item.resultId}
                item={item}
                shortlistId={shortlist.id}
                isFinalized={isFinalized}
              />
            ))
        }
      </Box>
    </Box>
  )
}
