import { useMemo, useState } from 'react'
import { Box, Button, Checkbox, Chip, Collapse, Divider, IconButton, Switch, TextField, Tooltip, Typography } from '@mui/material'
import { ChevronDown, ChevronUp, ExternalLink, FileText, Layers, Pencil, Users } from 'lucide-react'
import { useNavigate } from 'react-router'
import type { Property, PropertyUnit, UnitNeedMatch } from '../../domain/property'
import type { Lease } from '../../domain/lease'
import { useUnitMatchesMap, useUnitBundle, useBundleMatches } from '../../hooks/useUnitMatches'
import { useUpdateUnit } from '../../hooks/useProperties'
import { DS_BORDER, DS_PRE_MARKET, DS_SURFACE, DS_TEXT } from '../../lib/ds'
import { FIT_OUT_LABELS } from '../../lib/constants'
import { resolveUnitFacts } from '../../lib/unitFacts'
import { floorLabel } from './PropertyDetailHelpers'
import { UnitFieldsEditor } from './UnitFieldsEditor'

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>
  )
}

function LeaseField({ label, value }: { label: string; value?: string }) {
  if (!value) return null
  return (
    <Box>
      <Typography sx={{ fontSize: '0.59rem', color: DS_TEXT.muted, textTransform: 'uppercase', letterSpacing: 0.3 }}>
        {label}
      </Typography>
      <Typography sx={{ fontSize: '0.72rem', fontWeight: 600, color: '#1e293b' }}>
        {value}
      </Typography>
    </Box>
  )
}

function formatLeaseDate(iso?: string): string | undefined {
  if (!iso) return undefined
  return new Date(iso).toLocaleDateString('de-CH', { day: 'numeric', month: 'short', year: 'numeric' })
}

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 [editingFlexUnit, setEditingFlexUnit] = useState<string | null>(null)
  const [flexDraft, setFlexDraft] = useState<Record<string, number | undefined>>({})
  const [editingUnit, setEditingUnit] = useState<string | null>(null)
  const updateUnit = useUpdateUnit(p.id)

  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)

  // Group units by floor level (consecutive same-floor units form a group)
  const floorGroups = useMemo(() => {
    const groups: { floorLevel: number; units: PropertyUnit[] }[] = []
    for (const u of p.units ?? []) {
      const last = groups[groups.length - 1]
      if (last && last.floorLevel === u.floorLevel) {
        last.units.push(u)
      } else {
        groups.push({ floorLevel: u.floorLevel, units: [u] })
      }
    }
    return groups
  }, [p.units])

  // Flat list of all units for index tracking
  const allUnits = p.units ?? []

  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

  const renderUnitRow = (u: PropertyUnit, isFirstInGroup: boolean, isLastUnit: boolean) => {
    const matches = u.available ? (unitMatches[u.id] ?? []) : []
    const topMatch = matches[0]
    const isExpanded = expandedUnit === u.id
    const isSelected = selectedIds.has(u.id)
    const unitIndex = allUnits.indexOf(u)
    const isLastRow = unitIndex === allUnits.length - 1 && !isExpanded

    const activeLease: Lease | undefined = u.leases?.find(l => l.status === 'ACTIVE')
    const tenantName = activeLease?.tenant.companyName ?? u.currentTenant
    const leaseEnd = activeLease?.endDate ?? u.leaseEndDate
    const hasLeaseDetail = !u.available && !!activeLease

    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 when multiple free units exist */}
          <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 — only on first unit of group */}
          <Typography variant="caption" sx={{ fontWeight: 600, color: '#0f172a' }}>
            {isFirstInGroup ? 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}` }} />

                {/* Teilbar toggle */}
                <Tooltip title={u.isFlexible ? 'Teilbar — Mindesteinheit bearbeiten' : 'Als teilbar markieren'}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.25 }}>
                    <Switch
                      size="small"
                      checked={u.isFlexible ?? false}
                      onChange={e => {
                        const flexible = e.target.checked
                        if (flexible) {
                          setEditingFlexUnit(u.id)
                          setFlexDraft(d => ({ ...d, [u.id]: u.minLettableSqm }))
                        } else {
                          updateUnit.mutate({ unitId: u.id, data: { isFlexible: false, minLettableSqm: undefined } })
                          setEditingFlexUnit(null)
                        }
                      }}
                      sx={{ '& .MuiSwitch-thumb': { width: 10, height: 10 }, '& .MuiSwitch-switchBase': { p: '4px' }, '& .Mui-checked + .MuiSwitch-track': { bgcolor: '#1d4ed8' } }}
                    />
                    <Typography sx={{ fontSize: '0.58rem', color: u.isFlexible ? '#1d4ed8' : DS_TEXT.disabled, fontWeight: u.isFlexible ? 700 : 400 }}>
                      Teilbar
                    </Typography>
                  </Box>
                </Tooltip>

                {/* Inline min-unit editor */}
                {(editingFlexUnit === u.id || (u.isFlexible && !u.minLettableSqm)) && (
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                    <TextField
                      size="small"
                      type="number"
                      autoFocus={!u.minLettableSqm}
                      placeholder="Min m² *"
                      value={flexDraft[u.id] ?? ''}
                      onChange={e => setFlexDraft(d => ({ ...d, [u.id]: parseInt(e.target.value) || undefined }))}
                      error={!flexDraft[u.id] && u.isFlexible && !u.minLettableSqm}
                      sx={{
                        width: 80,
                        '& .MuiInputBase-input': { fontSize: '0.68rem', py: 0.375, px: 0.75 },
                        '& .MuiOutlinedInput-root': {
                          '& fieldset': { borderColor: (!flexDraft[u.id] && u.isFlexible && !u.minLettableSqm) ? '#ef4444' : undefined },
                        },
                      }}
                      slotProps={{ htmlInput: { min: 10, max: u.areaSqm, step: 10 } }}
                    />
                    <Button
                      size="small"
                      variant="contained"
                      disabled={!flexDraft[u.id]}
                      sx={{ fontSize: '0.58rem', py: 0.25, px: 0.75, minWidth: 0, bgcolor: '#1d4ed8', '&:hover': { bgcolor: '#1e40af' } }}
                      onClick={() => {
                        updateUnit.mutate({ unitId: u.id, data: { isFlexible: true, minLettableSqm: flexDraft[u.id] } })
                        setEditingFlexUnit(null)
                      }}
                    >
                      ✓
                    </Button>
                    {editingFlexUnit === u.id && u.minLettableSqm && (
                      <Button
                        size="small"
                        variant="text"
                        sx={{ fontSize: '0.58rem', py: 0.25, px: 0.5, minWidth: 0, color: DS_TEXT.muted }}
                        onClick={() => setEditingFlexUnit(null)}
                      >
                        ✕
                      </Button>
                    )}
                  </Box>
                )}

                <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,
                        floor: floorLabel(u),
                        fitOut: p.hardFacts?.fitOut,
                        fitOutByLandlord: p.hardFacts?.fitOutByLandlord,
                        parking: p.hardFacts?.parking,
                        ceilingHeight: p.hardFacts?.ceilingHeightM,
                        mieterausbaubeitragPerSqm: p.hardFacts?.mieterausbaubeitragPerSqm,
                        isFlexible: u.isFlexible,
                        minLettableSqm: u.minLettableSqm,
                        availableFrom: p.availabilityDate,
                      },
                    },
                  })}
                >
                  + Inserat
                </Button>
              </>
            ) : (
              <Box>
                <Typography variant="caption" sx={{ fontWeight: 600, color: '#374151' }} noWrap>
                  {tenantName ?? 'Vermietet'}
                </Typography>
                {leaseEnd && (
                  <Typography sx={{ fontSize: '0.6rem', color: DS_TEXT.muted, display: 'block' }}>
                    bis {new Date(leaseEnd).toLocaleDateString('de-CH', { month: 'short', year: '2-digit' })}
                  </Typography>
                )}
              </Box>
            )}
          </Box>

          {/* Matches column + expand */}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            {topMatch && <MatchPill m={topMatch} />}
            {/* Expand for free units with multiple matches */}
            {u.available && 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>
            )}
            {/* Expand for occupied units with lease detail */}
            {hasLeaseDetail && (
              <IconButton
                size="small"
                onClick={() => setExpandedUnit(isExpanded ? null : u.id)}
                sx={{
                  p: 0.5,
                  color: isExpanded ? '#2563eb' : '#64748b',
                  borderRadius: 1,
                  '&:hover': { bgcolor: '#f1f5f9', color: '#2563eb' },
                  transition: 'color 0.15s, background 0.15s',
                }}
              >
                {isExpanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
              </IconButton>
            )}
            {/* Edit price / availability per unit */}
            <Tooltip title="Preis & Verfügbarkeit bearbeiten">
              <IconButton
                size="small"
                onClick={() => setEditingUnit(editingUnit === u.id ? null : u.id)}
                sx={{ p: 0.25, color: editingUnit === u.id ? '#2563eb' : DS_TEXT.disabled }}
              >
                <Pencil size={11} />
              </IconButton>
            </Tooltip>
          </Box>

          {/* Area + Preis + Verfügbarkeit pro Einheit */}
          <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>
            )}
            <Typography variant="caption" sx={{ color: DS_TEXT.muted, fontSize: '0.6rem', display: 'block' }}>
              CHF {(u.rentPricePerSqm ?? p.rentPricePerSqm).toLocaleString('de-CH')}/m²
            </Typography>
            {u.available && (() => {
              const av = u.availableFrom ?? u.schattenmarktRelease?.availableFrom
              return (
                <Typography variant="caption" sx={{ color: DS_TEXT.disabled, fontSize: '0.6rem', display: 'block' }}>
                  {av ? `ab ${new Date(av).toLocaleDateString('de-CH', { month: 'short', year: '2-digit' })}` : 'sofort'}
                </Typography>
              )
            })()}
          </Box>
        </Box>

        {/* Always-visible per-unit details (read) */}
        {(() => {
          const f = resolveUnitFacts(p, u)
          const fitLabel = f.fitOut ? (FIT_OUT_LABELS[f.fitOut] ?? f.fitOut) : null
          const needsBuild = f.fitOut === 'SHELL' || f.fitOut === 'BASIC'
          const parts: string[] = []
          if (fitLabel) parts.push(`Ausbau: ${fitLabel}`)
          if (needsBuild) parts.push(`Träger: ${f.fitOutByLandlord ? 'Vermieter' : 'Mieter'}`)
          if (needsBuild && !f.fitOutByLandlord && f.mabPerSqm > 0) parts.push(`MAB CHF ${f.mabPerSqm}/m²`)
          if (f.parkingSpots != null) parts.push(`${f.parkingSpots} PP`)
          if (u.expectedRentPerSqm) parts.push(`erwartet CHF ${u.expectedRentPerSqm}/m²`)
          if (parts.length === 0) return null
          return (
            <Box sx={{ px: 1.5, pb: 0.625, mt: -0.25, borderBottom: isLastRow ? 'none' : `1px solid ${DS_BORDER.muted}` }}>
              <Typography variant="caption" sx={{ color: DS_TEXT.muted, fontSize: '0.63rem' }}>
                {parts.join(' · ')}
              </Typography>
            </Box>
          )
        })()}

        {/* Inline editor: full per-unit fields */}
        <Collapse in={editingUnit === u.id}>
          <UnitFieldsEditor property={p} unit={u} onClose={() => setEditingUnit(null)} />
        </Collapse>

        {/* Expanded: matches for free units */}
        <Collapse in={isExpanded && u.available}>
          <Box sx={{ px: 2, py: 1, bgcolor: DS_SURFACE.neutral.bg, borderBottom: !isLastUnit ? `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>

        {/* Expanded: lease detail for occupied units */}
        <Collapse in={isExpanded && !u.available && !!activeLease}>
          {activeLease && (
            <Box sx={{ px: 2, py: 1.25, bgcolor: '#f8fafc', borderBottom: !isLastUnit ? `1px solid ${DS_BORDER.default}` : 'none' }}>
              <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1.25, mb: activeLease.contractDocumentUrl ? 1.25 : 0 }}>
                <LeaseField label="Mietbeginn" value={formatLeaseDate(activeLease.startDate)} />
                <LeaseField label="Mietende" value={formatLeaseDate(activeLease.endDate)} />
                <LeaseField label="Laufzeit" value={activeLease.contractDurationYears ? `${activeLease.contractDurationYears} Jahre` : undefined} />
                <LeaseField label="Breakout-Option" value={activeLease.breakoutOption
                  ? `Ja${activeLease.breakoutOptionDate ? ` · ${formatLeaseDate(activeLease.breakoutOptionDate)}` : ''}`
                  : 'Nein'
                } />
                <LeaseField label="Importiert aus" value={activeLease.sourceSystem} />
                <LeaseField label="Zuletzt aktualisiert" value={formatLeaseDate(activeLease.lastUpdatedAt)} />
              </Box>
              {activeLease.contractDocumentUrl && (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, pt: 0.75, borderTop: `1px solid ${DS_BORDER.muted}` }}>
                  <FileText size={11} color="#152642" />
                  <Typography variant="caption" sx={{ fontWeight: 500, color: '#475569', flex: 1 }} noWrap>
                    {activeLease.contractDocumentName ?? 'Mietvertrag'}
                  </Typography>
                  <Button
                    size="small"
                    variant="outlined"
                    endIcon={<ExternalLink size={10} />}
                    href={activeLease.contractDocumentUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    sx={{ textTransform: 'none', fontSize: '0.68rem', py: 0.2, px: 0.875, borderColor: '#cbd5e1', color: '#152642', flexShrink: 0 }}
                  >
                    Öffnen
                  </Button>
                </Box>
              )}
            </Box>
          )}
        </Collapse>
      </Box>
    )
  }

  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' }}>
          Einheiten & Mietverträge
        </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', '', 'Fläche'].map((h, i) => (
            <Typography key={i} variant="caption" sx={{ fontWeight: 600, color: DS_TEXT.muted, fontSize: '0.63rem', textTransform: 'uppercase' }}>{h}</Typography>
          ))}
        </Box>

        {/* Floor groups */}
        {floorGroups.map((group, groupIdx) => (
          <Box
            key={group.floorLevel}
            sx={{ borderTop: groupIdx > 0 ? `2px solid ${DS_BORDER.default}` : 'none' }}
          >
            {group.units.map((u, unitIdxInGroup) => {
              const isFirstInGroup = unitIdxInGroup === 0
              const globalIdx = allUnits.indexOf(u)
              const isLastUnit = globalIdx === allUnits.length - 1
              return renderUnitRow(u, isFirstInGroup, isLastUnit)
            })}
          </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>
      )}
    </>
  )
}
