import { useState } from 'react'
import { Box, Button, CircularProgress, Skeleton, TextField } from '@mui/material'
import { Plus } from 'lucide-react'
import { ShortlistCard } from './ShortlistCard'
import { ShortlistEmptyState } from './ShortlistEmptyState'
import { useCreateShortlist } from '../../hooks/useShortlists'
import { useShortlistStore } from '../../stores/shortlistStore'
import { ShortlistStatus } from '../../domain/enums'
import type { Shortlist } from '../../domain/shortlist'

interface Props {
  shortlists: Shortlist[]
  isLoading: boolean
}

export function ShortlistList({ shortlists, isLoading }: Props) {
  const [creating, setCreating] = useState(false)
  const [newTitle, setNewTitle] = useState('')
  const createShortlist = useCreateShortlist()
  const { setSelectedShortlist } = useShortlistStore()

  async function handleCreate() {
    if (!newTitle.trim()) return
    const result = await createShortlist.mutateAsync({
      title: newTitle.trim(),
      items: [],
      status: ShortlistStatus.DRAFT,
      createdBy: 'admin@ideal-sharing.ch',
      organizationId: 'org-wincasa',
    })
    setNewTitle('')
    setCreating(false)
    setSelectedShortlist(result.data.id)
  }

  if (isLoading) {
    return (
      <Box sx={{ p: 1.5 }}>
        {[0, 1, 2].map(i => (
          <Box key={i} sx={{ mb: 1.5 }}>
            <Skeleton variant="text" width="70%" sx={{ fontSize: '0.875rem' }} />
            <Skeleton variant="text" width="40%" sx={{ fontSize: '0.75rem' }} />
          </Box>
        ))}
      </Box>
    )
  }

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden' }}>
      <Box sx={{ flex: 1, overflowY: 'auto' }}>
        {shortlists.length === 0 && !creating
          ? <ShortlistEmptyState context="no-shortlists" />
          : shortlists.map(sl => <ShortlistCard key={sl.id} shortlist={sl} />)
        }
      </Box>

      <Box sx={{ p: 1.5, borderTop: '1px solid #f1f5f9', flexShrink: 0 }}>
        {creating ? (
          <Box sx={{ display: 'flex', gap: 0.5 }}>
            <TextField
              size="small"
              autoFocus
              placeholder="Titel der Shortlist"
              value={newTitle}
              onChange={e => setNewTitle(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') handleCreate(); if (e.key === 'Escape') { setCreating(false); setNewTitle('') } }}
              sx={{ flex: 1, '& .MuiInputBase-input': { fontSize: 13 } }}
            />
            {createShortlist.isPending
              ? <CircularProgress size={20} sx={{ alignSelf: 'center', ml: 0.5 }} />
              : (
                <Button size="small" variant="contained" onClick={handleCreate} disabled={!newTitle.trim()} sx={{ bgcolor: '#152642', minWidth: 0, px: 1 }}>
                  OK
                </Button>
              )
            }
          </Box>
        ) : (
          <Button
            fullWidth
            size="small"
            startIcon={<Plus size={14} />}
            onClick={() => setCreating(true)}
            sx={{ color: '#152642', justifyContent: 'flex-start' }}
          >
            Neue Shortlist
          </Button>
        )}
      </Box>
    </Box>
  )
}
