import { useEffect, useState } from 'react'
import { Box, IconButton, Tooltip, Typography, useMediaQuery, useTheme } from '@mui/material'
import { ArrowLeft, LayoutGrid, List as ListIcon, Inbox } from 'lucide-react'
import { useActiveInquiries } from '../../hooks/useInquiries'
import type { InquiryFilters } from '../../provider/IInquiryProvider'
import { EmptyState } from '../ui'
import { InquiryList } from './InquiryList'
import { InquiryCardGrid } from './InquiryCardGrid'
import { InquiryDetailPanel } from './InquiryDetailPanel'

type ViewMode = 'list' | 'grid'

const VIEW_STORAGE_KEY = 'view-inquiries'

function loadViewMode(): ViewMode {
  if (typeof window === 'undefined') return 'list'
  const stored = window.localStorage.getItem(VIEW_STORAGE_KEY)
  return stored === 'grid' ? 'grid' : 'list'
}

interface Props {
  filters?: InquiryFilters
  emptyTitle?: string
  emptyDescription?: string
}

export function ActiveInquiriesTab({ filters, emptyTitle, emptyDescription }: Props = {}) {
  const { data: inquiries = [], isLoading } = useActiveInquiries(filters)
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [view, setView] = useState<ViewMode>(loadViewMode())
  const theme = useTheme()
  const isMobile = useMediaQuery(theme.breakpoints.down('md'))

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(VIEW_STORAGE_KEY, view)
    }
  }, [view])

  // Auto-select first inquiry on desktop only
  useEffect(() => {
    if (!isMobile && !selectedId && inquiries.length > 0) {
      setSelectedId(inquiries[0].id)
    }
  }, [inquiries, selectedId, isMobile])

  if (!isLoading && inquiries.length === 0) {
    return (
      <EmptyState
        icon={<Inbox size={40} />}
        title={emptyTitle ?? 'Keine aktiven Anfragen'}
        description={emptyDescription ?? 'Sobald Interessenten Anfragen zu Ihren Objekten stellen, erscheinen diese hier.'}
      />
    )
  }

  // Mobile: show detail panel when an inquiry is selected
  if (isMobile && selectedId) {
    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 }}>
          <IconButton size="small" onClick={() => setSelectedId(null)}>
            <ArrowLeft size={18} />
          </IconButton>
        </Box>
        <Box sx={{ flex: 1, overflow: 'hidden' }}>
          <InquiryDetailPanel inquiryId={selectedId} />
        </Box>
      </Box>
    )
  }

  return (
    <Box sx={{ display: 'flex', height: '100%', overflow: 'hidden' }}>
      {/* Left column: list/grid */}
      <Box
        sx={{
          width: isMobile ? '100%' : (view === 'list' ? 380 : 720),
          minWidth: isMobile ? 'unset' : (view === 'list' ? 380 : 480),
          flexShrink: 0,
          borderRight: isMobile ? 'none' : '1px solid #e2e8f0',
          bgcolor: 'white',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
        }}
      >
        <Box
          sx={{
            px: 2,
            py: 1.25,
            borderBottom: '1px solid #e2e8f0',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            flexShrink: 0,
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Typography variant="body2" sx={{ fontWeight: 600, color: '#0f172a' }}>
              Anfragen
            </Typography>
            <Box sx={{ px: 1, py: 0.125, borderRadius: 1, bgcolor: '#152642', color: 'white', fontWeight: 600, fontSize: '0.7rem' }}>
              {inquiries.length}
            </Box>
          </Box>
          <Box sx={{ display: 'flex', gap: 0.5 }}>
            <Tooltip title="Listenansicht">
              <IconButton size="small" onClick={() => setView('list')} sx={{ bgcolor: view === 'list' ? '#e0e7ff' : 'transparent', color: view === 'list' ? '#152642' : '#64748b' }}>
                <ListIcon size={16} />
              </IconButton>
            </Tooltip>
            <Tooltip title="Kartenansicht">
              <IconButton size="small" onClick={() => setView('grid')} sx={{ bgcolor: view === 'grid' ? '#e0e7ff' : 'transparent', color: view === 'grid' ? '#152642' : '#64748b' }}>
                <LayoutGrid size={16} />
              </IconButton>
            </Tooltip>
          </Box>
        </Box>

        {view === 'list' ? (
          <InquiryList inquiries={inquiries} selectedId={selectedId} onSelect={setSelectedId} />
        ) : (
          <InquiryCardGrid inquiries={inquiries} selectedId={selectedId} onSelect={setSelectedId} />
        )}
      </Box>

      {/* Right column: detail (desktop only) */}
      {!isMobile && (
        <Box sx={{ flex: 1, overflow: 'hidden', bgcolor: '#f8fafc' }}>
          {selectedId ? (
            <InquiryDetailPanel inquiryId={selectedId} />
          ) : (
            <EmptyState
              icon={<Inbox size={40} />}
              title="Anfrage auswählen"
              description="Wählen Sie eine Anfrage aus der Liste, um Details anzuzeigen und zu antworten."
            />
          )}
        </Box>
      )}
    </Box>
  )
}
