import { Box, CircularProgress, Switch, TextField, Typography } from '@mui/material'
import type { Property } from '../../domain/property'
import { DS_PRE_MARKET, DS_TEXT } from '../../lib/ds'
import { floorLabel } from './PropertyDetailHelpers'

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

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

export function PreMarketUnitGrid({ units, unitStates, unitSaving, setUnitStates, saveUnit }: Props) {
  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: '' }
        return (
          <Box
            key={u.id}
            sx={{
              display: 'grid', gridTemplateColumns: '1fr 140px auto',
              gap: 1, alignItems: 'center', py: 0.75,
              borderBottom: '1px solid #f3e8ff',
              '&:last-child': { borderBottom: 'none' },
            }}
          >
            <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²
                {u.currentTenant ? ` · ${u.currentTenant}` : ''}
              </Typography>
            </Box>
            <TextField
              type="date"
              size="small"
              value={us.availableFrom}
              disabled={!us.enabled}
              slotProps={{ inputLabel: { shrink: true } }}
              sx={{ '& .MuiInputBase-input': { fontSize: '0.72rem', py: 0.5 } }}
              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)
              }}
            />
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              {unitSaving[u.id] && <CircularProgress size={10} sx={{ color: DS_PRE_MARKET.accent }} />}
              <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)
                }}
                sx={{
                  '& .MuiSwitch-switchBase.Mui-checked': { color: DS_PRE_MARKET.accent },
                  '& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': { bgcolor: '#8b5cf6' },
                }}
              />
            </Box>
          </Box>
        )
      })}
    </Box>
  )
}
