import { useState, useEffect } from 'react'
import {
  Box, Button, Dialog, DialogActions, DialogContent, DialogTitle,
  TextField, Typography,
} from '@mui/material'
import { Send } from 'lucide-react'
import { useToastStore } from '../../stores/toastStore'
import { useInquiryStore } from '../../stores/inquiryStore'
import { useSessionStore } from '../../stores/sessionStore'
import { useMoveStage } from '../../hooks/usePipeline'
import { useCreateInquiry } from '../../hooks/useInquiries'
import { DS_BG, DS_BORDER, DS_TEXT } from '../../lib/ds'

function buildTemplate(propertyTitle: string, location: string, areaLabel?: string): string {
  const areaLine = areaLabel ? `\nDie Fläche von ${areaLabel} entspricht unserem Bedarf.` : ''
  return `Guten Tag\n\nWir interessieren uns für Ihre Fläche «${propertyTitle}» in ${location}.${areaLine} Gerne würden wir einen Besichtigungstermin vereinbaren und offene Fragen klären.\n\nFür Rückfragen stehen wir jederzeit zur Verfügung.\n\nFreundliche Grüsse`
}

export function InquiryQuickDialog() {
  const showToast = useToastStore(s => s.showToast)
  const dialogOpen = useInquiryStore(s => s.dialogOpen)
  const pendingInquiry = useInquiryStore(s => s.pendingInquiry)
  const closeInquiryDialog = useInquiryStore(s => s.closeInquiryDialog)
  const currentUser = useSessionStore(s => s.currentUser)
  const createInquiry = useCreateInquiry()
  const { mutate: moveStage } = useMoveStage()

  const [message, setMessage] = useState('')

  useEffect(() => {
    if (dialogOpen && pendingInquiry) {
      setMessage(buildTemplate(pendingInquiry.propertyTitle, pendingInquiry.location, pendingInquiry.areaLabel))
    }
  }, [dialogOpen, pendingInquiry])

  function handleSend() {
    if (!pendingInquiry) return
    createInquiry.mutate({
      organizationId: 'org-wincasa',   // Supply-Org des Objekts (Mock: Wincasa)
      tenantOrgId: currentUser?.organizationId ?? 'org-mobimo',
      propertyId: pendingInquiry.propertyId ?? 'unknown',
      tenantName: currentUser?.name ?? 'Demand User',
      tenantCompany: currentUser?.organizationName,
      tenantEmail: currentUser?.email,
      propertyAddress: pendingInquiry.propertyTitle,
      subject: `Anfrage: ${pendingInquiry.propertyTitle}`,
      message,
      matchScore: pendingInquiry.matchScore,
    })
    if (pendingInquiry.pipelineItemId) {
      moveStage({ id: pendingInquiry.pipelineItemId, stage: 'CONTACTED' })
    }
    showToast('Anfrage gesendet — Sie erhalten eine Antwort per E-Mail.', 'success')
    closeInquiryDialog()
  }

  if (!pendingInquiry) return null

  return (
    <Dialog open={dialogOpen} onClose={closeInquiryDialog} maxWidth="sm" fullWidth>
      <DialogTitle sx={{ fontWeight: 700, pb: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
        <Send size={16} />
        Anfrage senden
      </DialogTitle>

      <DialogContent sx={{ pt: 0 }}>
        <Box sx={{ bgcolor: DS_BG.subtle, border: `1px solid ${DS_BORDER.default}`, borderRadius: 1.5, p: 1.5, mb: 2 }}>
          <Typography variant="body2" sx={{ fontWeight: 600 }}>{pendingInquiry.propertyTitle}</Typography>
          <Typography variant="caption" sx={{ color: DS_TEXT.secondary }}>
            {pendingInquiry.location}
            {pendingInquiry.areaLabel && ` · ${pendingInquiry.areaLabel}`}
            {pendingInquiry.rentLabel && ` · ${pendingInquiry.rentLabel}`}
            {' · '}Match {pendingInquiry.matchScore}%
          </Typography>
        </Box>

        <TextField
          fullWidth
          multiline
          rows={8}
          value={message}
          onChange={e => setMessage(e.target.value)}
          sx={{ '& .MuiInputBase-root': { fontSize: '0.875rem' } }}
        />

        <Typography variant="caption" sx={{ color: DS_TEXT.muted, display: 'block', mt: 1 }}>
          Der Text kann vor dem Absenden angepasst werden.
        </Typography>
      </DialogContent>

      <DialogActions sx={{ px: 3, pb: 2, gap: 1 }}>
        <Button onClick={closeInquiryDialog} size="small" sx={{ color: DS_TEXT.muted }}>Abbrechen</Button>
        <Button
          onClick={handleSend}
          variant="contained"
          size="small"
          disabled={!message.trim()}
          startIcon={<Send size={14} />}
          sx={{ bgcolor: '#152642', '&:hover': { bgcolor: '#162d4a' } }}
        >
          Anfrage senden
        </Button>
      </DialogActions>
    </Dialog>
  )
}
