import { useState } from 'react'
import { Box, Button, Chip, CircularProgress, Divider, MenuItem, TextField, ToggleButton, ToggleButtonGroup, Typography } from '@mui/material'
import { Sparkles } from 'lucide-react'
import type { Property, PropertyUnit } from '../../domain/property'
import { usePreMarketRentRecommendation } from '../../hooks/useAI'
import { useUpdateUnit } from '../../hooks/useProperties'
import { resolveUnitFacts } from '../../lib/unitFacts'
import { FIT_OUT_LABELS } from '../../lib/constants'
import { DS_BORDER, DS_PRE_MARKET, DS_SURFACE, DS_TEXT } from '../../lib/ds'

const NEEDS_BUILD = new Set(['SHELL', 'BASIC'])
const VERDICT_META: Record<string, { label: string; bg: string; fg: string }> = {
  UNDERPRICED: { label: 'zu günstig', bg: '#fef3c7', fg: '#92400e' },
  FAIR:        { label: 'marktgerecht', bg: '#dcfce7', fg: '#166534' },
  AMBITIOUS:   { label: 'ambitioniert', bg: '#fee2e2', fg: '#991b1b' },
}

interface Draft {
  fitOut?: string
  fitOutByLandlord?: boolean
  mieterausbaubeitragPerSqm?: number
  parkingSpots?: number
  expectedRentPerSqm?: number
}

interface Props {
  property: Property
  unit: PropertyUnit
}

/** Pre-Market-Konfiguration einer Einheit: erst Ausbau/Parkplätze, dann KI-Preisempfehlung. */
export function PreMarketPriceAdvisor({ property, unit }: Props) {
  const updateUnit = useUpdateUnit(property.id)
  const [d, setD] = useState<Draft>(() => ({
    fitOut: unit.fitOut ?? '',
    fitOutByLandlord: unit.fitOutByLandlord,
    mieterausbaubeitragPerSqm: unit.mieterausbaubeitragPerSqm,
    parkingSpots: unit.parkingSpots,
    expectedRentPerSqm: unit.expectedRentPerSqm,
  }))

  const facts = resolveUnitFacts(property, unit)
  const current = facts.rentPricePerSqm
  const effFit = d.fitOut || property.hardFacts?.fitOut
  const needsBuild = NEEDS_BUILD.has(effFit ?? '')

  const { data, isLoading, isError } = usePreMarketRentRecommendation({
    city: property.location?.city ?? '',
    assetType: property.assetType,
    areaSqm: unit.areaSqm,
    currentRentPerSqm: current,
    availableFrom: unit.schattenmarktRelease?.availableFrom,
  })
  const rec = data?.data
  const verdict = rec ? VERDICT_META[rec.verdict] : null

  const save = (patch: Partial<PropertyUnit>) => updateUnit.mutate({ unitId: unit.id, data: patch })

  return (
    <Box sx={{ mt: 0.75, p: 1.25, borderRadius: 1, bgcolor: 'white', border: `1px solid ${DS_SURFACE.purple.border}` }}>
      {/* 1) Ausbau & Ausstattung */}
      <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 130px', gap: 1 }}>
        <TextField
          select size="small" label="Ausbaustandard"
          value={d.fitOut ?? ''}
          onChange={e => {
            const v = e.target.value
            const nb = v === 'SHELL' || v === 'BASIC'
            setD(p => ({ ...p, fitOut: v }))
            save({ fitOut: (v || undefined) as PropertyUnit['fitOut'], ...(nb ? {} : { fitOutByLandlord: undefined, mieterausbaubeitragPerSqm: undefined }) })
          }}
        >
          <MenuItem value="">Wie Objekt{property.hardFacts?.fitOut ? ` (${FIT_OUT_LABELS[property.hardFacts.fitOut] ?? property.hardFacts.fitOut})` : ''}</MenuItem>
          <MenuItem value="SHELL">{FIT_OUT_LABELS.SHELL}</MenuItem>
          <MenuItem value="BASIC">{FIT_OUT_LABELS.BASIC}</MenuItem>
          <MenuItem value="FULL">{FIT_OUT_LABELS.FULL}</MenuItem>
          <MenuItem value="PREMIUM">{FIT_OUT_LABELS.PREMIUM}</MenuItem>
        </TextField>
        <TextField
          label="Parkplätze" type="number" size="small"
          value={d.parkingSpots ?? ''}
          onChange={e => setD(p => ({ ...p, parkingSpots: parseInt(e.target.value) || undefined }))}
          onBlur={e => save({ parkingSpots: parseInt(e.target.value) || undefined })}
          slotProps={{ htmlInput: { min: 0 } }}
          helperText={property.hardFacts?.parking != null ? `Pool: ${property.hardFacts.parking}` : undefined}
        />
      </Box>

      {needsBuild && (
        <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap', mt: 1 }}>
          <Typography variant="caption" color="text.secondary">Wer baut aus?</Typography>
          <ToggleButtonGroup
            exclusive size="small"
            value={d.fitOutByLandlord === undefined ? null : d.fitOutByLandlord ? 'landlord' : 'tenant'}
            onChange={(_, v) => {
              if (!v) return
              const landlord = v === 'landlord'
              setD(p => ({ ...p, fitOutByLandlord: landlord, ...(landlord ? { mieterausbaubeitragPerSqm: undefined } : {}) }))
              save({ fitOutByLandlord: landlord, ...(landlord ? { mieterausbaubeitragPerSqm: undefined } : {}) })
            }}
          >
            <ToggleButton value="landlord" sx={{ textTransform: 'none' }}>Vermieter</ToggleButton>
            <ToggleButton value="tenant" sx={{ textTransform: 'none' }}>Mieter</ToggleButton>
          </ToggleButtonGroup>
          {d.fitOutByLandlord === false && (
            <TextField
              label="MAB (CHF/m²)" type="number" size="small" sx={{ width: 140 }}
              value={d.mieterausbaubeitragPerSqm ?? ''}
              onChange={e => setD(p => ({ ...p, mieterausbaubeitragPerSqm: parseInt(e.target.value) || undefined }))}
              onBlur={e => save({ mieterausbaubeitragPerSqm: parseInt(e.target.value) || undefined })}
              slotProps={{ htmlInput: { min: 0, max: 1000, step: 25 } }}
            />
          )}
        </Box>
      )}

      <Divider sx={{ my: 1.25 }} />

      {/* 2) KI-Preisempfehlung */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 0.5 }}>
        <Sparkles size={12} color={DS_PRE_MARKET.accent} />
        <Typography sx={{ fontSize: '0.65rem', fontWeight: 700, color: '#5b21b6' }}>KI-Preisempfehlung Pre-Market</Typography>
        {verdict && <Chip label={verdict.label} size="small" sx={{ height: 16, fontSize: '0.6rem', fontWeight: 700, bgcolor: verdict.bg, color: verdict.fg, ml: 'auto' }} />}
      </Box>

      {isLoading ? (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, py: 0.5 }}>
          <CircularProgress size={12} sx={{ color: DS_PRE_MARKET.accent }} />
          <Typography sx={{ fontSize: '0.65rem', color: '#6d28d9' }}>Marktanalyse läuft…</Typography>
        </Box>
      ) : isError || !rec ? (
        <Typography sx={{ fontSize: '0.65rem', color: DS_TEXT.muted }}>Keine Empfehlung verfügbar.</Typography>
      ) : (
        <>
          <Typography sx={{ fontSize: '0.72rem', fontWeight: 700, color: '#5b21b6' }}>
            Empfehlung: CHF {rec.recommendedPerSqm}/m²
            <Box component="span" sx={{ fontWeight: 400, color: '#6d28d9' }}> (CHF {rec.rangeMinPerSqm}–{rec.rangeMaxPerSqm})</Box>
          </Typography>
          <Typography sx={{ fontSize: '0.65rem', color: '#6d28d9', mb: 0.25 }}>
            Heute CHF {current}/m²
            <Box component="span" sx={{ fontWeight: 700, ml: 0.5 }}>
              {rec.deltaVsCurrentPct > 0 ? `+${rec.deltaVsCurrentPct}%` : `${rec.deltaVsCurrentPct}%`} vs. heute
            </Box>
          </Typography>
          <Typography sx={{ fontSize: '0.6rem', color: '#7c3aed', mb: 0.625 }}>
            {rec.drivers.join(' · ')}
          </Typography>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
            <TextField
              type="number" size="small" label="Pre-Market-Preis"
              placeholder={`z.B. ${rec.recommendedPerSqm}`}
              value={d.expectedRentPerSqm ?? ''}
              onChange={e => setD(p => ({ ...p, expectedRentPerSqm: parseInt(e.target.value) || undefined }))}
              onBlur={e => save({ expectedRentPerSqm: parseInt(e.target.value) || undefined })}
              slotProps={{ inputLabel: { shrink: true }, htmlInput: { min: 0, step: 10 } }}
              sx={{ width: 150, '& .MuiInputBase-input': { fontSize: '0.72rem', py: 0.5 } }}
            />
            <Button
              size="small"
              onClick={() => { setD(p => ({ ...p, expectedRentPerSqm: rec.recommendedPerSqm })); save({ expectedRentPerSqm: rec.recommendedPerSqm }) }}
              sx={{ textTransform: 'none', fontSize: '0.68rem', color: DS_PRE_MARKET.accent }}
            >
              Empfehlung übernehmen
            </Button>
          </Box>
        </>
      )}
    </Box>
  )
}
