import { useState } from 'react'
import { Box, CircularProgress, Collapse, IconButton, Switch, TextField, Tooltip, Typography } from '@mui/material'
import { EyeOff, Pencil } from 'lucide-react'
import type { Property } from '../../domain/property'
import { DS_BORDER, DS_PRE_MARKET, 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'
import { PreMarketPriceAdvisor } from './PreMarketPriceAdvisor'

type PropertyUnit = NonNullable<Property['units']>[number]

export interface UnitReleaseState {
  enabled: boolean
  availableFrom: string
  anonymous: boolean
}

interface Props {
  property: Property
  units: PropertyUnit[]
  unitStates: Record<string, UnitReleaseState>
  unitSaving: Record<string, boolean>
  setUnitStates: React.Dispatch<React.SetStateAction<Record<string, UnitReleaseState>>>
  saveUnit: (unitId: string, enabled: boolean, availableFrom: string, anonymous: boolean) => Promise<void>
}

export function PreMarketUnitGrid({ property, units, unitStates, unitSaving, setUnitStates, saveUnit }: Props) {
  const [editing, setEditing] = useState<string | null>(null)

  return (
    <Box sx={{ mt: 1.25, pt: 1.25, borderTop: `1px solid ${DS_PRE_MARKET.border}` }}>
      <Typography variant="caption" sx={{ fontWeight: 700, color: '#4c1d95', textTransform: 'uppercase', letterSpacing: 0.5, fontSize: '0.63rem', display: 'block', mb: 0.875 }}>
        Einheiten freigeben
      </Typography>
      {units.map(u => {
        const us = unitStates[u.id] ?? { enabled: false, availableFrom: '', anonymous: false }
        const f = resolveUnitFacts(property, u)
        const fitLabel = f.fitOut ? (FIT_OUT_LABELS[f.fitOut] ?? f.fitOut) : null
        const needsBuild = f.fitOut === 'SHELL' || f.fitOut === 'BASIC'
        const detailParts: string[] = []
        if (fitLabel) detailParts.push(fitLabel)
        if (needsBuild) detailParts.push(`Träger: ${f.fitOutByLandlord ? 'Vermieter' : 'Mieter'}`)
        if (f.parkingSpots != null) detailParts.push(`${f.parkingSpots} PP`)
        detailParts.push(u.expectedRentPerSqm ? `erwartet CHF ${u.expectedRentPerSqm}/m²` : `CHF ${f.rentPricePerSqm}/m²`)

        return (
          <Box key={u.id} sx={{ borderBottom: '1px solid #f3e8ff', '&:last-child': { borderBottom: 'none' }, py: 0.875 }}>
            <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 140px auto', gap: 1, alignItems: 'start' }}>
              {/* Unit info + anonym toggle (shown when enabled) */}
              <Box>
                <Typography sx={{ fontSize: '0.72rem', fontWeight: 600, color: DS_TEXT.primary }}>
                  {floorLabel(u)}{u.unitLabel ? ` · ${u.unitLabel}` : ''}
                </Typography>
                <Typography sx={{ fontSize: '0.65rem', color: DS_TEXT.muted }}>
                  {u.areaSqm.toLocaleString('de-CH')} m²
                </Typography>
                {us.enabled && (
                  <Tooltip title="Adresse und Objektname werden im Matching-Feed ausgeblendet — Interessenten sehen nur Fläche, Typ und Standortregion">
                    <Box
                      sx={{
                        display: 'inline-flex', alignItems: 'center', gap: 0.5, mt: 0.625,
                        px: 0.75, py: 0.25, borderRadius: 1,
                        border: '1px solid',
                        borderColor: us.anonymous ? '#ddd6fe' : '#e2e8f0',
                        bgcolor: us.anonymous ? '#f5f3ff' : 'transparent',
                        cursor: 'pointer',
                        transition: 'background 0.15s, border-color 0.15s',
                      }}
                      onClick={() => {
                        const next = { ...us, anonymous: !us.anonymous }
                        setUnitStates(prev => ({ ...prev, [u.id]: next }))
                        saveUnit(u.id, us.enabled, us.availableFrom, !us.anonymous)
                      }}
                    >
                      <EyeOff size={11} color={us.anonymous ? DS_PRE_MARKET.accent : '#94a3b8'} />
                      <Typography sx={{ fontSize: '0.62rem', fontWeight: us.anonymous ? 700 : 400, color: us.anonymous ? DS_PRE_MARKET.accent : '#94a3b8', lineHeight: 1 }}>
                        Anonym
                      </Typography>
                      <Switch
                        size="small"
                        checked={us.anonymous}
                        onChange={(_, checked) => {
                          const next = { ...us, anonymous: checked }
                          setUnitStates(prev => ({ ...prev, [u.id]: next }))
                          saveUnit(u.id, us.enabled, us.availableFrom, checked)
                        }}
                        onClick={e => e.stopPropagation()}
                        sx={{
                          width: 28, height: 16, p: 0,
                          '& .MuiSwitch-switchBase': { p: '2px', '&.Mui-checked': { transform: 'translateX(12px)', color: '#fff' } },
                          '& .MuiSwitch-thumb': { width: 12, height: 12 },
                          '& .MuiSwitch-track': { borderRadius: 8, bgcolor: '#cbd5e1' },
                          '& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': { bgcolor: '#8b5cf6' },
                        }}
                      />
                    </Box>
                  </Tooltip>
                )}
              </Box>

              {/* Available-from date */}
              <TextField
                type="date"
                size="small"
                value={us.availableFrom}
                disabled={!us.enabled}
                slotProps={{ inputLabel: { shrink: true } }}
                sx={{ '& .MuiInputBase-input': { fontSize: '0.72rem', py: 0.5 }, mt: 0.125 }}
                onChange={e => {
                  const next = { ...us, availableFrom: e.target.value }
                  setUnitStates(prev => ({ ...prev, [u.id]: next }))
                  if (us.enabled) saveUnit(u.id, true, e.target.value, us.anonymous)
                }}
              />

              {/* Edit (nur vor Freigabe — danach inline) + enabled toggle */}
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.25, mt: 0.25 }}>
                {unitSaving[u.id] && <CircularProgress size={10} sx={{ color: DS_PRE_MARKET.accent }} />}
                {!us.enabled && (
                  <Tooltip title="Ausbau, Preis & Parkplätze dieser Einheit bearbeiten">
                    <IconButton size="small" onClick={() => setEditing(editing === u.id ? null : u.id)} sx={{ p: 0.25, color: editing === u.id ? DS_PRE_MARKET.accent : DS_TEXT.disabled }}>
                      <Pencil size={12} />
                    </IconButton>
                  </Tooltip>
                )}
                <Switch
                  size="small"
                  checked={us.enabled}
                  onChange={(_, checked) => {
                    const next = { ...us, enabled: checked }
                    setUnitStates(prev => ({ ...prev, [u.id]: next }))
                    saveUnit(u.id, checked, us.availableFrom, us.anonymous)
                  }}
                  sx={{
                    '& .MuiSwitch-switchBase.Mui-checked': { color: DS_PRE_MARKET.accent },
                    '& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': { bgcolor: '#8b5cf6' },
                  }}
                />
              </Box>
            </Box>

            {/* Vor Freigabe: Lese-Details + Stift-Editor. Nach Freigabe: volle Inline-Konfiguration. */}
            {us.enabled ? (
              <PreMarketPriceAdvisor property={property} unit={u} />
            ) : (
              <>
                <Typography variant="caption" sx={{ color: DS_TEXT.muted, fontSize: '0.62rem', display: 'block', mt: 0.25 }}>
                  {detailParts.join(' · ')}
                </Typography>
                <Collapse in={editing === u.id}>
                  <Box sx={{ border: `1px solid ${DS_BORDER.default}`, borderRadius: 1, mt: 0.75, overflow: 'hidden' }}>
                    <UnitFieldsEditor property={property} unit={u} onClose={() => setEditing(null)} />
                  </Box>
                </Collapse>
              </>
            )}
          </Box>
        )
      })}
    </Box>
  )
}
