import { useMemo, useState } from 'react'
import { Box, Button, Checkbox, Chip, Collapse, Divider, IconButton, Tooltip, Typography } from '@mui/material'
import { ChevronDown, ChevronUp, Layers, Users } from 'lucide-react'
import { useNavigate } from 'react-router'
import type { Property, PropertyUnit, UnitNeedMatch } from '../../domain/property'
import { useUnitMatchesMap, useUnitBundle, useBundleMatches } from '../../hooks/useUnitMatches'
import { DS_BORDER, DS_PRE_MARKET, DS_SURFACE, DS_TEXT } from '../../lib/ds'
import { floorLabel } from './PropertyDetailHelpers'

function MatchPill({ m }: { m: UnitNeedMatch }) {
  const bg = m.matchScore >= 85 ? '#fef3c7' : '#e0e7ff'
  const color = m.matchScore >= 85 ? '#92400e' : '#3730a3'
  return (
    <Tooltip title={`${m.requiredSqmMin}–${m.requiredSqmMax} m² · ${m.matchType === 'partial' ? `Teilfläche ~${m.suggestedSqm} m²` : m.matchType === 'bundle' ? 'Kombination' : 'Passt'}`}>
      <Box sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.5, px: 0.75, py: 0.125, borderRadius: 1, bgcolor: bg, cursor: 'default' }}>
        <Users size={10} color={color} />
        <Typography sx={{ fontSize: '0.63rem', fontWeight: 700, color, lineHeight: 1 }}>
          {m.tenantCompany ?? m.tenantName}
        </Typography>
        <Typography sx={{ fontSize: '0.63rem', color, lineHeight: 1 }}>{m.matchScore}%</Typography>
      </Box>
    </Tooltip>
  )
}

export function UnitStructurePanel({ p }: { p: Property }) {
  const navigate = useNavigate()
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [expandedUnit, setExpandedUnit] = useState<string | null>(null)

  const freeUnits = useMemo(() => (p.units ?? []).filter(u => u.available), [p.units])

  const unitMatches = useUnitMatchesMap(freeUnits, p)

  const selectedFreeUnits = freeUnits.filter(u => selectedIds.has(u.id))
  const bundle = useUnitBundle(selectedFreeUnits)
  const bundleMatches = useBundleMatches(selectedFreeUnits, p)

  const toggleUnit = (id: string) => {
    setSelectedIds(prev => {
      const next = new Set(prev)
      next.has(id) ? next.delete(id) : next.add(id)
      return next
    })
  }

  if (!p.units || p.units.length === 0) return null

  return (
    <>
      <Divider sx={{ my: 2 }} />
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
        <Typography variant="body2" sx={{ fontWeight: 700, color: '#0f172a', fontSize: '0.8125rem' }}>
          Stockwerkstruktur
        </Typography>
        {freeUnits.length >= 2 && (
          <Typography variant="caption" sx={{ color: DS_TEXT.muted, fontSize: '0.7rem' }}>
            Freie Einheiten auswählen zum Kombinieren
          </Typography>
        )}
      </Box>

      <Box sx={{ border: `1px solid ${DS_BORDER.default}`, borderRadius: 1.5, overflow: 'hidden', mb: 1.5 }}>
        {/* Header */}
        <Box sx={{ display: 'grid', gridTemplateColumns: '28px 72px 88px 1fr auto 80px', bgcolor: DS_SURFACE.neutral.bg, px: 1.5, py: 0.75, borderBottom: `1px solid ${DS_BORDER.default}`, alignItems: 'center' }}>
          {['', 'Stockwerk', 'Einheit', 'Mieter / Status', 'Matches', 'Fläche'].map(h => (
            <Typography key={h} variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, fontSize: '0.63rem', textTransform: 'uppercase' }}>{h}</Typography>
          ))}
        </Box>

        {p.units!.map((u: PropertyUnit, i: number) => {
          const matches = u.available ? (unitMatches[u.id] ?? []) : []
          const topMatch = matches[0]
          const isExpanded = expandedUnit === u.id
          const isSelected = selectedIds.has(u.id)
          const isLastRow = i === p.units!.length - 1 && !isExpanded

          return (
            <Box key={u.id}>
              <Box
                sx={{
                  display: 'grid',
                  gridTemplateColumns: '28px 72px 88px 1fr auto 80px',
                  px: 1.5,
                  py: 0.875,
                  borderBottom: isLastRow ? 'none' : `1px solid ${DS_BORDER.muted}`,
                  alignItems: 'center',
                  bgcolor: isSelected ? DS_SURFACE.blue.bg : 'transparent',
                  transition: 'background 0.15s',
                }}
              >
                {/* Checkbox — only for free units */}
                <Box>
                  {u.available && freeUnits.length >= 2 && (
                    <Checkbox
                      size="small"
                      checked={isSelected}
                      onChange={() => toggleUnit(u.id)}
                      sx={{ p: 0, color: DS_TEXT.disabled, '&.Mui-checked': { color: '#2563eb' } }}
                    />
                  )}
                </Box>

                {/* Floor */}
                <Typography variant="caption" sx={{ fontWeight: 600, color: '#0f172a' }}>
                  {floorLabel(u)}
                </Typography>

                {/* Unit label */}
                <Typography variant="caption" sx={{ color: '#374151' }}>{u.unitLabel ?? '–'}</Typography>

                {/* Status */}
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, flexWrap: 'wrap' }}>
                  {u.available ? (
                    <>
                      <Chip label="Frei" size="small" sx={{ height: 16, fontSize: '0.6rem', bgcolor: DS_SURFACE.success.bg, color: '#166534', border: `1px solid ${DS_SURFACE.success.border}` }} />
                      {u.isFlexible && (
                        <Chip label="Teilfläche möglich" size="small" sx={{ height: 16, fontSize: '0.58rem', bgcolor: DS_SURFACE.blue.bg, color: '#1d4ed8', border: `1px solid ${DS_SURFACE.blue.border}` }} />
                      )}
                      <Button
                        size="small"
                        variant="text"
                        sx={{ height: 16, fontSize: '0.58rem', p: 0, minWidth: 0, color: DS_PRE_MARKET.accent, textTransform: 'none', lineHeight: 1 }}
                        onClick={() => navigate('/supply/new-listing', {
                          state: {
                            prefill: {
                              assetType: p.assetType,
                              street: p.address?.street,
                              houseNumber: p.address?.houseNumber,
                              postalCode: p.address?.postalCode,
                              city: p.address?.city,
                              areaSqm: u.offeredSqm ?? u.areaSqm,
                              rentPricePerSqm: u.rentPricePerSqm ?? p.rentPricePerSqm,
                              unitLabel: u.unitLabel,
                              propertyId: p.id,
                            },
                          },
                        })}
                      >
                        + Inserat
                      </Button>
                    </>
                  ) : (
                    <Typography variant="caption" sx={{ color: DS_TEXT.muted }} noWrap>{u.currentTenant ?? 'Vermietet'}</Typography>
                  )}
                </Box>

                {/* Top match pill + expand */}
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  {topMatch && <MatchPill m={topMatch} />}
                  {matches.length > 1 && (
                    <IconButton
                      size="small"
                      onClick={() => setExpandedUnit(isExpanded ? null : u.id)}
                      sx={{ p: 0.25, color: DS_TEXT.disabled }}
                    >
                      {isExpanded ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
                    </IconButton>
                  )}
                </Box>

                {/* Area */}
                <Box sx={{ textAlign: 'right' }}>
                  <Typography variant="caption" sx={{ color: '#374151', fontWeight: u.available ? 600 : 400 }}>
                    {(u.offeredSqm ?? u.areaSqm).toLocaleString('de-CH')} m²
                  </Typography>
                  {u.isFlexible && u.minLettableSqm && (
                    <Typography variant="caption" sx={{ color: DS_TEXT.disabled, fontSize: '0.6rem', display: 'block' }}>
                      ab {u.minLettableSqm} m²
                    </Typography>
                  )}
                </Box>
              </Box>

              {/* Expanded: show all matches for this unit */}
              <Collapse in={isExpanded}>
                <Box sx={{ px: 2, py: 1, bgcolor: DS_SURFACE.neutral.bg, borderBottom: i < p.units!.length - 1 ? `1px solid ${DS_BORDER.default}` : 'none' }}>
                  <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, fontSize: '0.65rem', textTransform: 'uppercase', display: 'block', mb: 0.75 }}>
                    Passende Suchanfragen für diese Einheit
                  </Typography>
                  <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
                    {matches.map(m => (
                      <Box key={m.needId} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <MatchPill m={m} />
                        <Typography variant="caption" sx={{ color: DS_TEXT.muted, fontSize: '0.68rem' }}>
                          {m.requiredSqmMin}–{m.requiredSqmMax} m²
                          {m.matchType === 'partial' && m.suggestedSqm && ` · Teilfläche ~${m.suggestedSqm} m² anbieten`}
                        </Typography>
                      </Box>
                    ))}
                    {matches.length === 0 && (
                      <Typography variant="caption" sx={{ color: DS_TEXT.disabled, fontSize: '0.7rem' }}>Keine passenden Suchanfragen</Typography>
                    )}
                  </Box>
                </Box>
              </Collapse>
            </Box>
          )
        })}
      </Box>

      {/* Bundle panel */}
      {bundle && (
        <Box
          sx={{
            border: `1px solid ${DS_SURFACE.blue.border}`,
            borderRadius: 1.5,
            bgcolor: DS_SURFACE.blue.bg,
            p: 1.5,
            mb: 1.5,
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
            <Layers size={14} color="#1d4ed8" />
            <Typography variant="body2" sx={{ fontWeight: 700, color: '#1d4ed8', fontSize: '0.8125rem' }}>
              Kombination: {bundle.label}
            </Typography>
            <Chip
              label={`${bundle.combinedSqm.toLocaleString('de-CH')} m² gesamt`}
              size="small"
              sx={{ bgcolor: '#dbeafe', color: '#1e40af', border: '1px solid #93c5fd', height: 18, fontSize: '0.65rem', ml: 'auto' }}
            />
          </Box>
          <Typography variant="caption" sx={{ color: '#1e40af', fontSize: '0.72rem', display: 'block', mb: 1 }}>
            Diese Einheiten können gemeinsam oder separat vermietet werden.
            {selectedFreeUnits.some(u => u.isFlexible) && ' Flexible Teilflächen möglich — Restfläche bleibt nach Vertragsabschluss verfügbar.'}
          </Typography>
          {bundleMatches.length > 0 ? (
            <Box>
              <Typography variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, fontSize: '0.63rem', textTransform: 'uppercase', display: 'block', mb: 0.5 }}>
                Passende Suchanfragen für Kombination
              </Typography>
              <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap' }}>
                {bundleMatches.map(m => <MatchPill key={m.needId} m={m} />)}
              </Box>
            </Box>
          ) : (
            <Typography variant="caption" sx={{ color: DS_TEXT.disabled, fontSize: '0.7rem' }}>
              Keine direkt passenden Suchanfragen für diese Kombination
            </Typography>
          )}
        </Box>
      )}
    </>
  )
}
