import { Box, Paper, Typography } from '@mui/material'
import { useShortlists } from '../../hooks/useShortlists'
import { useShortlistStore } from '../../stores/shortlistStore'
import {
  ShortlistList,
  ShortlistDetail,
  DecisionBriefDraftPanel,
  AddToShortlistDialog,
} from '../../components/shortlist'

const PANEL_HEADER_SX = {
  px: 2,
  py: 1.5,
  borderBottom: '1px solid #e2e8f0',
  bgcolor: 'white',
  position: 'sticky' as const,
  top: 0,
  zIndex: 1,
  flexShrink: 0,
}

export default function Shortlists() {
  const { data: shortlists = [], isLoading } = useShortlists()
  const { selectedShortlistId } = useShortlistStore()

  const selectedShortlist = shortlists.find(s => s.id === selectedShortlistId) ?? null

  return (
    <Box sx={{ display: 'flex', height: 'calc(100vh - 64px)', overflow: 'hidden' }}>

      {/* Left: shortlist list */}
      <Paper elevation={0} sx={{
        width: 260,
        flexShrink: 0,
        display: 'flex',
        flexDirection: 'column',
        borderRadius: 0,
        borderRight: '1px solid #e2e8f0',
        overflow: 'hidden',
      }}>
        <Box sx={PANEL_HEADER_SX}>
          <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>Shortlists</Typography>
          <Typography variant="caption" color="text.secondary">{shortlists.length} gespeichert</Typography>
        </Box>
        <ShortlistList shortlists={shortlists} isLoading={isLoading} />
      </Paper>

      {/* Center: detail */}
      <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', bgcolor: '#f8fafc' }}>
        {selectedShortlist ? (
          <ShortlistDetail shortlist={selectedShortlist} />
        ) : (
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 1 }}>
            <Typography variant="body2" color="text.secondary">
              Shortlist aus der Liste wählen
            </Typography>
          </Box>
        )}
      </Box>

      {/* Right: decision brief — only when a shortlist is selected */}
      {selectedShortlist && (
        <Paper elevation={0} sx={{
          width: 280,
          flexShrink: 0,
          display: 'flex',
          flexDirection: 'column',
          borderRadius: 0,
          borderLeft: '1px solid #e2e8f0',
          overflow: 'hidden',
        }}>
          <DecisionBriefDraftPanel shortlistId={selectedShortlist.id} />
        </Paper>
      )}

      <AddToShortlistDialog />
    </Box>
  )
}
