import { useEffect, useState } from 'react'
import { Box, IconButton, Typography, useMediaQuery, useTheme } from '@mui/material'
import { ArrowLeft, Sparkles } from 'lucide-react'
import { usePublicNeeds, useLatentNeedById } from '../../hooks/useLatentNeeds'
import { EmptyState } from '../ui'
import { PublicNeedList } from './PublicNeedList'
import { PublicNeedDetail } from './PublicNeedDetail'
import { OwnPropertyMatchList } from './OwnPropertyMatchList'

type MobileView = 'list' | 'detail' | 'properties'

export function LatentInquiriesTab() {
  const { data: needs = [] } = usePublicNeeds()
  const [selectedNeedId, setSelectedNeedId] = useState<string | null>(null)
  const { data: selectedNeed } = useLatentNeedById(selectedNeedId)
  const theme = useTheme()
  const isMobile = useMediaQuery(theme.breakpoints.down('md'))
  const isTablet = useMediaQuery(theme.breakpoints.between('md', 'lg'))
  const [mobileView, setMobileView] = useState<MobileView>('list')

  useEffect(() => {
    if (!isMobile && !selectedNeedId && needs.length > 0) {
      setSelectedNeedId(needs[0].id)
    }
  }, [needs, selectedNeedId, isMobile])

  const handleSelectNeed = (id: string) => {
    setSelectedNeedId(id)
    if (isMobile) setMobileView('detail')
  }

  // Mobile: sequential single-panel navigation
  if (isMobile) {
    if (mobileView === 'detail' && selectedNeed) {
      return (
        <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
          <Box sx={{ px: 1.5, py: 1, borderBottom: '1px solid #e2e8f0', bgcolor: 'white', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 1 }}>
            <IconButton size="small" onClick={() => setMobileView('list')}>
              <ArrowLeft size={18} />
            </IconButton>
            <Typography variant="body2" sx={{ fontWeight: 600, fontSize: '0.85rem' }} noWrap>
              {selectedNeed.title}
            </Typography>
          </Box>
          <Box sx={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
            <PublicNeedDetail need={selectedNeed} />
            <Box sx={{ px: 2, py: 1.5, borderTop: '1px solid #e2e8f0', flexShrink: 0 }}>
              <Box
                onClick={() => setMobileView('properties')}
                sx={{ p: 1.25, bgcolor: '#152642', color: 'white', borderRadius: 1, textAlign: 'center', cursor: 'pointer', fontSize: '0.85rem', fontWeight: 600 }}
              >
                Eigene Objekte anzeigen →
              </Box>
            </Box>
          </Box>
        </Box>
      )
    }
    if (mobileView === 'properties' && selectedNeed) {
      return (
        <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
          <Box sx={{ px: 1.5, py: 1, borderBottom: '1px solid #e2e8f0', bgcolor: 'white', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 1 }}>
            <IconButton size="small" onClick={() => setMobileView('detail')}>
              <ArrowLeft size={18} />
            </IconButton>
            <Typography variant="body2" sx={{ fontWeight: 600, fontSize: '0.85rem' }}>
              Eigene Objekte
            </Typography>
          </Box>
          <Box sx={{ flex: 1, overflow: 'hidden' }}>
            <OwnPropertyMatchList need={selectedNeed} />
          </Box>
        </Box>
      )
    }
    // list view
    return (
      <Box sx={{ height: '100%', overflow: 'hidden' }}>
        <PublicNeedList selectedNeedId={selectedNeedId} onSelect={handleSelectNeed} fullWidth />
      </Box>
    )
  }

  // Tablet: hide own-property column, show it as button in detail
  if (isTablet) {
    return (
      <Box sx={{ display: 'flex', height: '100%', overflow: 'hidden' }}>
        <PublicNeedList selectedNeedId={selectedNeedId} onSelect={setSelectedNeedId} />
        <Box sx={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
          {selectedNeed ? (
            <PublicNeedDetail need={selectedNeed} />
          ) : (
            <Box sx={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <EmptyState icon={<Sparkles size={40} />} title="Bedarf auswählen" description="Wählen Sie einen latenten Bedarf, um Details zu sehen." />
            </Box>
          )}
        </Box>
      </Box>
    )
  }

  // Desktop: full 3-column layout
  return (
    <Box sx={{ display: 'flex', height: '100%', overflow: 'hidden' }}>
      <PublicNeedList selectedNeedId={selectedNeedId} onSelect={setSelectedNeedId} />
      <Box sx={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {selectedNeed ? (
          <PublicNeedDetail need={selectedNeed} />
        ) : (
          <Box sx={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <EmptyState icon={<Sparkles size={40} />} title="Bedarf auswählen" description="Wählen Sie einen latenten Bedarf, um Details und passende Objekte zu sehen." />
          </Box>
        )}
      </Box>
      {selectedNeed && <OwnPropertyMatchList need={selectedNeed} />}
    </Box>
  )
}
