import { useState } from 'react'
import {
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from '@mui/material'
import { Plus } from 'lucide-react'
import { ShortlistStatusBadge } from './ShortlistStatusBadge'
import { useShortlists, useCreateShortlist, useAddToShortlist } from '../../hooks/useShortlists'
import { useShortlistStore } from '../../stores/shortlistStore'
import { useToastStore } from '../../stores/toastStore'
import { ShortlistStatus } from '../../domain/enums'

export function AddToShortlistDialog() {
  const { dialogOpen, pendingItem, closeAddDialog } = useShortlistStore()
  const { data: shortlists = [], isLoading } = useShortlists()
  const createShortlist = useCreateShortlist()
  const addToShortlist = useAddToShortlist()

  const showToast = useToastStore((s) => s.showToast)
  const [selectedId, setSelectedId] = useState<string>('')
  const [creatingNew, setCreatingNew] = useState(false)
  const [newTitle, setNewTitle] = useState('')
  const [note, setNote] = useState('')

  function handleClose() {
    closeAddDialog()
    setSelectedId('')
    setCreatingNew(false)
    setNewTitle('')
    setNote('')
  }

  async function handleConfirm() {
    if (!pendingItem) return
    const itemWithNote = { ...pendingItem, note: note.trim() || undefined }

    let targetId = selectedId

    if (creatingNew) {
      if (!newTitle.trim()) return
      const created = await createShortlist.mutateAsync({
        title: newTitle.trim(),
        items: [],
        status: ShortlistStatus.DRAFT,
        createdBy: 'admin@ideal-sharing.ch',
        organizationId: 'org-wincasa',
      })
      targetId = created.data.id
    }

    if (!targetId) return

    const prevShortlist = shortlists.find(s => s.id === targetId)
    const alreadyExists = prevShortlist?.items.some(i => i.resultId === pendingItem.resultId)

    await addToShortlist.mutateAsync({ shortlistId: targetId, item: itemWithNote })

    handleClose()
    if (alreadyExists) {
      showToast('Bereits in dieser Shortlist vorhanden.', 'warning')
    } else {
      showToast('Zur Shortlist hinzugefügt.')
    }
  }

  const isBusy = createShortlist.isPending || addToShortlist.isPending
  const canConfirm = !isBusy && ((creatingNew && !!newTitle.trim()) || (!creatingNew && !!selectedId))

  return (
    <>
      <Dialog open={dialogOpen} onClose={handleClose} maxWidth="xs" fullWidth>
        <DialogTitle sx={{ fontWeight: 700, pb: 1 }}>Zur Shortlist hinzufügen</DialogTitle>
        <DialogContent sx={{ pt: 0 }}>
          {pendingItem && (
            <Box sx={{ bgcolor: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: 1, p: 1.5, mb: 2 }}>
              <Typography variant="body2" sx={{ fontWeight: 600 }}>{pendingItem.title}</Typography>
              <Typography variant="caption" color="text.secondary">
                Score {pendingItem.matchScore} · {pendingItem.resultType}
              </Typography>
            </Box>
          )}

          {isLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 2 }}>
              <CircularProgress size={20} />
            </Box>
          ) : (
            <RadioGroup value={creatingNew ? '__new__' : selectedId} onChange={e => {
              if (e.target.value === '__new__') { setCreatingNew(true); setSelectedId('') }
              else { setCreatingNew(false); setSelectedId(e.target.value) }
            }}>
              {shortlists.map(sl => (
                <FormControlLabel
                  key={sl.id}
                  value={sl.id}
                  control={<Radio size="small" />}
                  label={
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Typography variant="body2">{sl.title}</Typography>
                      <ShortlistStatusBadge status={sl.status} />
                    </Box>
                  }
                />
              ))}
              <FormControlLabel
                value="__new__"
                control={<Radio size="small" />}
                label={
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                    <Plus size={14} />
                    <Typography variant="body2">Neue Shortlist erstellen</Typography>
                  </Box>
                }
              />
            </RadioGroup>
          )}

          {creatingNew && (
            <TextField
              size="small"
              fullWidth
              autoFocus
              label="Titel der neuen Shortlist"
              value={newTitle}
              onChange={e => setNewTitle(e.target.value)}
              sx={{ mt: 1.5 }}
            />
          )}

          <TextField
            size="small"
            fullWidth
            multiline
            rows={2}
            label="Notiz (optional)"
            value={note}
            onChange={e => setNote(e.target.value)}
            sx={{ mt: 2 }}
          />
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button onClick={handleClose} disabled={isBusy}>Abbrechen</Button>
          <Button
            variant="contained"
            onClick={handleConfirm}
            disabled={!canConfirm}
            endIcon={isBusy ? <CircularProgress size={14} color="inherit" /> : undefined}
            sx={{ bgcolor: '#1e3a5f', '&:hover': { bgcolor: '#162d4a' } }}
          >
            Hinzufügen
          </Button>
        </DialogActions>
      </Dialog>
    </>
  )
}
