import { useState } from 'react'
import {
  Box, Button, CircularProgress, Dialog, DialogActions,
  DialogContent, DialogTitle, TextField, Typography,
} from '@mui/material'
import { Bookmark } from 'lucide-react'
import { usePipelineStore } from '../../stores/pipelineStore'
import { useAddToPipeline } from '../../hooks/usePipeline'

export function AddToPipelineDialog() {
  const { dialogOpen, pendingItem, closeSavedDialog } = usePipelineStore()
  const { mutate: addToPipeline, isPending } = useAddToPipeline()
  const [note, setNote] = useState('')

  function handleClose() {
    closeSavedDialog()
    setNote('')
  }

  function handleConfirm() {
    if (!pendingItem) return
    addToPipeline({ pending: pendingItem, notes: note.trim() || undefined })
    setNote('')
  }

  return (
    <Dialog open={dialogOpen} onClose={handleClose} maxWidth="xs" fullWidth>
      <DialogTitle sx={{ fontWeight: 700, pb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
        <Bookmark size={16} />
        Merken
      </DialogTitle>
      <DialogContent sx={{ pt: 0 }}>
        {pendingItem && (
          <Box sx={{ bgcolor: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: 1.5, p: 1.5, mb: 2 }}>
            <Typography variant="body2" sx={{ fontWeight: 600 }}>{pendingItem.title}</Typography>
            <Typography variant="caption" color="text.secondary">
              Match {pendingItem.matchScore}% · {pendingItem.resultType}
            </Typography>
          </Box>
        )}
        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1.5 }}>
          Das Objekt wird in Ihrer Pipeline unter <strong>Gemerkt</strong> gespeichert. Von dort können Sie es qualifizieren und weiterverfolgen.
        </Typography>
        <TextField
          size="small"
          fullWidth
          multiline
          rows={2}
          label="Notiz (optional)"
          value={note}
          onChange={e => setNote(e.target.value)}
        />
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button onClick={handleClose} disabled={isPending}>Abbrechen</Button>
        <Button
          variant="contained"
          onClick={handleConfirm}
          disabled={isPending}
          endIcon={isPending ? <CircularProgress size={14} color="inherit" /> : undefined}
          sx={{ bgcolor: '#152642', '&:hover': { bgcolor: '#162d4a' } }}
        >
          Merken
        </Button>
      </DialogActions>
    </Dialog>
  )
}
