'use client'
import { useState, useEffect, useCallback } from 'react'
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import Chip from '@mui/material/Chip'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Divider from '@mui/material/Divider'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import TextField from '@mui/material/TextField'
import Alert from '@mui/material/Alert'
import CircularProgress from '@mui/material/CircularProgress'
import Tooltip from '@mui/material/Tooltip'
import Snackbar from '@mui/material/Snackbar'
import Collapse from '@mui/material/Collapse'
import Tabs from '@mui/material/Tabs'
import Tab from '@mui/material/Tab'

const API = '/api'

// ─── Types ─────────────────────────────────────────────────────────────────────

type DeadlineStatus = 'proposed' | 'confirmed' | 'rejected' | 'reminder_sent' | 'completed' | 'overdue'

interface MatterDeadline {
  _id: string
  matterId: string
  clientFolderId: string
  obligationKey: string
  name: string
  description?: string
  dueDate: string
  reminderDate: string
  anchorDate?: string
  anchorField?: string
  intervalDays?: number
  recurrenceIndex: number
  linkedFormIds: string[]
  status: DeadlineStatus
  proposedBy: string
  confirmedBy?: string
  confirmedAt?: string
  rejectionReason?: string
  editDelta?: Record<string, { from: any; to: any }>
  notes?: string
  createdAt: string
}

// ─── Helpers ───────────────────────────────────────────────────────────────────

function fmtDate(d?: string) {
  if (!d) return '—'
  return new Date(d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })
}

function daysFromNow(d: string) {
  const diff = Math.ceil((new Date(d).getTime() - Date.now()) / 86400000)
  if (diff < 0)  return { label: `${Math.abs(diff)}d overdue`, color: '#FF4C51' }
  if (diff === 0) return { label: 'Today',                       color: '#FF6B00' }
  if (diff <= 7)  return { label: `${diff}d`,                    color: '#FF6B00' }
  if (diff <= 30) return { label: `${diff}d`,                    color: '#FFB400' }
  return              { label: `${diff}d`,                        color: '#56CA00' }
}

const STATUS_CONFIG: Record<DeadlineStatus, { label: string; color: string; icon: string }> = {
  proposed:      { label: 'Proposed',      color: '#16B1FF', icon: 'ri-time-line' },
  confirmed:     { label: 'Confirmed',     color: '#56CA00', icon: 'ri-checkbox-circle-line' },
  rejected:      { label: 'Rejected',      color: '#8A8D93', icon: 'ri-close-circle-line' },
  reminder_sent: { label: 'Reminder Sent', color: '#9C6FDE', icon: 'ri-notification-line' },
  completed:     { label: 'Completed',     color: '#0D9394', icon: 'ri-check-double-line' },
  overdue:       { label: 'Overdue',       color: '#FF4C51', icon: 'ri-error-warning-line' },
}

// ─── Confirm dialog ─────────────────────────────────────────────────────────────

function ConfirmDialog({
  deadline,
  onClose,
}: {
  deadline: MatterDeadline
  onClose: (confirmed?: { dueDate?: string; reminderDate?: string; notes?: string }) => void
}) {
  const [dueDate,      setDueDate]      = useState(deadline.dueDate.split('T')[0])
  const [reminderDate, setReminderDate] = useState(deadline.reminderDate.split('T')[0])
  const [notes,        setNotes]        = useState(deadline.notes ?? '')

  const hasEdits = dueDate !== deadline.dueDate.split('T')[0]
    || reminderDate !== deadline.reminderDate.split('T')[0]
    || notes !== (deadline.notes ?? '')

  return (
    <Dialog open onClose={() => onClose()} maxWidth='xs' fullWidth>
      <DialogTitle sx={{ fontWeight: 700 }}>Confirm Deadline</DialogTitle>
      <DialogContent sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
        <Typography variant='body2' sx={{ fontWeight: 600 }}>{deadline.name}</Typography>
        {deadline.description && (
          <Typography variant='caption' color='text.secondary'>{deadline.description}</Typography>
        )}
        <TextField
          label='Due date'
          type='date'
          size='small'
          fullWidth
          value={dueDate}
          onChange={e => setDueDate(e.target.value)}
          InputLabelProps={{ shrink: true }}
        />
        <TextField
          label='Send reminder on'
          type='date'
          size='small'
          fullWidth
          value={reminderDate}
          onChange={e => setReminderDate(e.target.value)}
          InputLabelProps={{ shrink: true }}
        />
        <TextField
          label='Notes (optional)'
          size='small'
          fullWidth
          multiline
          rows={2}
          value={notes}
          onChange={e => setNotes(e.target.value)}
          placeholder='Any specific instructions…'
        />
        {hasEdits && (
          <Alert severity='info' sx={{ fontSize: '0.72rem' }}>
            Your edits will be saved as training data to improve future forecasts.
          </Alert>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={() => onClose()}>Cancel</Button>
        <Button
          variant='contained'
          color='success'
          onClick={() => onClose({ dueDate, reminderDate, notes })}
          startIcon={<i className='ri-checkbox-circle-line' />}
        >
          Confirm
        </Button>
      </DialogActions>
    </Dialog>
  )
}

// ─── Reject dialog ──────────────────────────────────────────────────────────────

function RejectDialog({
  deadline,
  onClose,
}: {
  deadline: MatterDeadline
  onClose: (reason?: string) => void
}) {
  const [reason, setReason] = useState('')

  return (
    <Dialog open onClose={() => onClose()} maxWidth='xs' fullWidth>
      <DialogTitle sx={{ fontWeight: 700 }}>Reject Proposal</DialogTitle>
      <DialogContent sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
        <Typography variant='body2'>{deadline.name}</Typography>
        <TextField
          label='Reason (optional but helpful)'
          size='small'
          fullWidth
          multiline
          rows={3}
          value={reason}
          onChange={e => setReason(e.target.value)}
          placeholder='e.g. Not applicable for this client / handled differently / wrong dates'
          helperText='Your reason trains the system to make better proposals in future.'
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={() => onClose()}>Cancel</Button>
        <Button
          variant='outlined'
          color='error'
          onClick={() => onClose(reason || undefined)}
        >
          Reject
        </Button>
      </DialogActions>
    </Dialog>
  )
}

// ─── Add manual deadline dialog ─────────────────────────────────────────────────

function AddDeadlineDialog({
  matterId,
  onClose,
}: {
  matterId: string
  onClose: (created?: MatterDeadline) => void
}) {
  const [name,        setName]        = useState('')
  const [description, setDescription] = useState('')
  const [dueDate,     setDueDate]     = useState('')
  const [leadDays,    setLeadDays]    = useState('7')
  const [notes,       setNotes]       = useState('')
  const [busy,        setBusy]        = useState(false)
  const [error,       setError]       = useState<string | null>(null)

  const handleSave = async () => {
    if (!name.trim() || !dueDate) { setError('Name and due date are required'); return }
    setBusy(true)
    setError(null)
    try {
      const res = await fetch(`${API}/matter-deadlines`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          matterId, name: name.trim(), description: description.trim() || undefined,
          dueDate, reminderLeadDays: Number(leadDays) || 7,
          notes: notes.trim() || undefined,
        }),
      })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message ?? res.statusText)
      onClose(await res.json())
    } catch (e: any) {
      setError(e.message)
    } finally {
      setBusy(false)
    }
  }

  return (
    <Dialog open onClose={() => onClose()} maxWidth='xs' fullWidth>
      <DialogTitle sx={{ fontWeight: 700 }}>Add Deadline</DialogTitle>
      <DialogContent sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
        {error && <Alert severity='error'>{error}</Alert>}
        <TextField label='Name' size='small' fullWidth value={name} onChange={e => setName(e.target.value)} />
        <TextField label='Description' size='small' fullWidth multiline rows={2} value={description} onChange={e => setDescription(e.target.value)} />
        <TextField label='Due date' type='date' size='small' fullWidth value={dueDate} onChange={e => setDueDate(e.target.value)} InputLabelProps={{ shrink: true }} />
        <TextField label='Reminder lead (days before)' type='number' size='small' fullWidth value={leadDays} onChange={e => setLeadDays(e.target.value)} />
        <TextField label='Notes' size='small' fullWidth multiline rows={2} value={notes} onChange={e => setNotes(e.target.value)} />
      </DialogContent>
      <DialogActions>
        <Button onClick={() => onClose()} disabled={busy}>Cancel</Button>
        <Button variant='contained' onClick={handleSave} disabled={busy || !name.trim() || !dueDate}
          startIcon={busy ? <CircularProgress size={14} color='inherit' /> : <i className='ri-add-line' />}>
          Add
        </Button>
      </DialogActions>
    </Dialog>
  )
}

// ─── Deadline card ──────────────────────────────────────────────────────────────

function DeadlineCard({
  deadline,
  onConfirm,
  onReject,
  onComplete,
  onDelete,
}: {
  deadline: MatterDeadline
  onConfirm: (d: MatterDeadline) => void
  onReject:  (d: MatterDeadline) => void
  onComplete:(d: MatterDeadline) => void
  onDelete:  (d: MatterDeadline) => void
}) {
  const [expanded, setExpanded] = useState(false)
  const s  = STATUS_CONFIG[deadline.status]
  const dt = daysFromNow(deadline.dueDate)
  const isProposed   = deadline.status === 'proposed'
  const isConfirmed  = deadline.status === 'confirmed'
  const isRecurring  = !!deadline.intervalDays
  const isManual     = deadline.proposedBy === 'manual'

  return (
    <Card variant='outlined' sx={{
      mb: 1.5,
      borderLeft: `3px solid ${s.color}`,
      opacity: ['rejected', 'completed'].includes(deadline.status) ? 0.6 : 1,
    }}>
      <CardContent sx={{ py: 1.5, '&:last-child': { pb: 1.5 } }}>
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
          {/* Status icon */}
          <Box sx={{ mt: 0.2, flexShrink: 0 }}>
            <i className={s.icon} style={{ fontSize: '1rem', color: s.color }} />
          </Box>

          {/* Content */}
          <Box sx={{ flex: 1, minWidth: 0 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, flexWrap: 'wrap', mb: 0.25 }}>
              <Typography variant='body2' sx={{ fontWeight: 600 }}>{deadline.name}</Typography>
              <Chip label={s.label} size='small' sx={{ fontSize: '0.58rem', height: 16, bgcolor: s.color + '18', color: s.color }} />
              {isRecurring && (
                <Chip label={`Every ${deadline.intervalDays}d`} size='small' sx={{ fontSize: '0.58rem', height: 16 }} />
              )}
              {isManual && (
                <Chip label='Manual' size='small' sx={{ fontSize: '0.58rem', height: 16 }} />
              )}
              {deadline.recurrenceIndex > 0 && (
                <Chip label={`#${deadline.recurrenceIndex + 1}`} size='small' sx={{ fontSize: '0.58rem', height: 16 }} />
              )}
            </Box>

            <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', mt: 0.5 }}>
              <Typography variant='caption' color='text.secondary'>
                <i className='ri-calendar-event-line' style={{ fontSize: '0.7rem', marginRight: 3 }} />
                Due: <strong>{fmtDate(deadline.dueDate)}</strong>
              </Typography>
              {!['completed', 'rejected'].includes(deadline.status) && (
                <Typography variant='caption' sx={{ color: dt.color, fontWeight: 600 }}>
                  {dt.label}
                </Typography>
              )}
              <Typography variant='caption' color='text.disabled'>
                <i className='ri-notification-line' style={{ fontSize: '0.7rem', marginRight: 3 }} />
                Remind: {fmtDate(deadline.reminderDate)}
              </Typography>
              {deadline.anchorField && (
                <Typography variant='caption' color='text.disabled'>
                  anchor: {deadline.anchorField} ({fmtDate(deadline.anchorDate)})
                </Typography>
              )}
            </Box>

            {deadline.confirmedBy && (
              <Typography variant='caption' color='text.disabled' sx={{ mt: 0.25, display: 'block' }}>
                Confirmed by {deadline.confirmedBy} · {fmtDate(deadline.confirmedAt)}
                {deadline.editDelta && Object.keys(deadline.editDelta).length > 0 && ' · edited before confirming'}
              </Typography>
            )}
            {deadline.rejectionReason && (
              <Typography variant='caption' color='text.disabled' sx={{ mt: 0.25, display: 'block', fontStyle: 'italic' }}>
                Rejected: "{deadline.rejectionReason}"
              </Typography>
            )}
          </Box>

          {/* Actions */}
          <Box sx={{ display: 'flex', gap: 0.5, flexShrink: 0, alignItems: 'center' }}>
            {isProposed && (
              <>
                <Tooltip title='Confirm (with optional edits)'>
                  <IconButton size='small' onClick={() => onConfirm(deadline)} sx={{ color: '#56CA00' }}>
                    <i className='ri-checkbox-circle-line' style={{ fontSize: '1.1rem' }} />
                  </IconButton>
                </Tooltip>
                <Tooltip title='Reject proposal'>
                  <IconButton size='small' onClick={() => onReject(deadline)} sx={{ color: '#8A8D93' }}>
                    <i className='ri-close-circle-line' style={{ fontSize: '1.1rem' }} />
                  </IconButton>
                </Tooltip>
              </>
            )}
            {isConfirmed && (
              <Tooltip title='Mark completed'>
                <IconButton size='small' onClick={() => onComplete(deadline)} sx={{ color: '#0D9394' }}>
                  <i className='ri-check-double-line' style={{ fontSize: '1.1rem' }} />
                </IconButton>
              </Tooltip>
            )}
            <Tooltip title={expanded ? 'Hide details' : 'Show details'}>
              <IconButton size='small' onClick={() => setExpanded(v => !v)} sx={{ color: 'text.disabled' }}>
                <i className={expanded ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} style={{ fontSize: '1rem' }} />
              </IconButton>
            </Tooltip>
            <Tooltip title='Delete'>
              <IconButton size='small' onClick={() => onDelete(deadline)} sx={{ color: 'text.disabled' }}>
                <i className='ri-delete-bin-line' style={{ fontSize: '0.9rem' }} />
              </IconButton>
            </Tooltip>
          </Box>
        </Box>

        {/* Expanded detail */}
        <Collapse in={expanded}>
          <Divider sx={{ my: 1 }} />
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
            {deadline.description && (
              <Typography variant='caption' color='text.secondary' sx={{ lineHeight: 1.5 }}>
                {deadline.description}
              </Typography>
            )}
            {deadline.notes && (
              <Typography variant='caption' color='text.secondary'>
                <strong>Notes:</strong> {deadline.notes}
              </Typography>
            )}
            {deadline.editDelta && Object.keys(deadline.editDelta).length > 0 && (
              <Box sx={{ bgcolor: 'action.hover', borderRadius: 1, p: 1, mt: 0.5 }}>
                <Typography variant='caption' sx={{ fontWeight: 600, display: 'block', mb: 0.5 }}>
                  Attorney edits (training signal):
                </Typography>
                {Object.entries(deadline.editDelta).map(([field, { from, to }]) => (
                  <Typography key={field} variant='caption' color='text.secondary' sx={{ display: 'block' }}>
                    {field}: {String(from)} → {String(to)}
                  </Typography>
                ))}
              </Box>
            )}
            <Typography variant='caption' color='text.disabled'>
              ID: {deadline._id} · Created: {fmtDate(deadline.createdAt)}
            </Typography>
          </Box>
        </Collapse>
      </CardContent>
    </Card>
  )
}

// ─── Main view ──────────────────────────────────────────────────────────────────

export default function MatterTimelineView({ matterId }: { matterId: string }) {
  const [deadlines,     setDeadlines]     = useState<MatterDeadline[]>([])
  const [loading,       setLoading]       = useState(true)
  const [generating,    setGenerating]    = useState(false)
  const [tab,           setTab]           = useState(0)
  const [confirmTarget, setConfirmTarget] = useState<MatterDeadline | null>(null)
  const [rejectTarget,  setRejectTarget]  = useState<MatterDeadline | null>(null)
  const [addOpen,       setAddOpen]       = useState(false)
  const [snack,         setSnack]         = useState<{ open: boolean; msg: string; severity: 'success' | 'error' }>({ open: false, msg: '', severity: 'success' })
  const [genResult,     setGenResult]     = useState<{ created: number; missingAnchors: string[] } | null>(null)

  const toast = (msg: string, severity: 'success' | 'error' = 'success') =>
    setSnack({ open: true, msg, severity })

  const load = useCallback(async () => {
    if (!matterId) return
    setLoading(true)
    try {
      const res = await fetch(`${API}/matter-deadlines/matter/${matterId}`)
      if (res.ok) setDeadlines(await res.json())
    } finally {
      setLoading(false)
    }
  }, [matterId])

  useEffect(() => { load() }, [load])

  const handleGenerate = async () => {
    setGenerating(true)
    try {
      const res = await fetch(`${API}/matter-deadlines/matter/${matterId}/generate`, { method: 'POST' })
      const data = await res.json()
      if (!res.ok) throw new Error(data.message ?? res.statusText)
      setGenResult({ created: data.created?.length ?? 0, missingAnchors: data.missingAnchors ?? [] })
      await load()
      toast(`${data.created?.length ?? 0} deadline(s) proposed`)
    } catch (e: any) {
      toast(e.message, 'error')
    } finally {
      setGenerating(false)
    }
  }

  const handleConfirm = async (deadline: MatterDeadline, edits?: any) => {
    setConfirmTarget(null)
    try {
      const res = await fetch(`${API}/matter-deadlines/${deadline._id}/confirm`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ confirmedBy: 'attorney', ...edits }),
      })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message)
      const updated = await res.json()
      setDeadlines(prev => prev.map(d => d._id === updated._id ? updated : d))
      toast('Deadline confirmed')
    } catch (e: any) {
      toast(e.message, 'error')
    }
  }

  const handleReject = async (deadline: MatterDeadline, reason?: string) => {
    setRejectTarget(null)
    try {
      const res = await fetch(`${API}/matter-deadlines/${deadline._id}/reject`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason }),
      })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message)
      const updated = await res.json()
      setDeadlines(prev => prev.map(d => d._id === updated._id ? updated : d))
      toast('Proposal rejected')
    } catch (e: any) {
      toast(e.message, 'error')
    }
  }

  const handleComplete = async (deadline: MatterDeadline) => {
    try {
      const res = await fetch(`${API}/matter-deadlines/${deadline._id}/complete`, { method: 'PATCH' })
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).message)
      await load()
      toast('Marked complete — next occurrence queued if recurring')
    } catch (e: any) {
      toast(e.message, 'error')
    }
  }

  const handleDelete = async (deadline: MatterDeadline) => {
    try {
      await fetch(`${API}/matter-deadlines/${deadline._id}`, { method: 'DELETE' })
      setDeadlines(prev => prev.filter(d => d._id !== deadline._id))
      toast('Deleted')
    } catch {
      toast('Delete failed', 'error')
    }
  }

  // ── Split by tab ────────────────────────────────────────────────────────────

  const proposed   = deadlines.filter(d => d.status === 'proposed')
  const confirmed  = deadlines.filter(d => d.status === 'confirmed' || d.status === 'reminder_sent')
  const history    = deadlines.filter(d => ['completed', 'rejected', 'overdue'].includes(d.status))

  const tabCounts  = [proposed.length, confirmed.length, history.length]
  const tabItems   = [proposed, confirmed, history]

  if (!matterId) return null

  return (
    <Box>
      {/* Header */}
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2, flexWrap: 'wrap', gap: 1 }}>
        <Box>
          <Typography variant='h6' sx={{ fontWeight: 700 }}>Obligation Timeline</Typography>
          <Typography variant='caption' color='text.secondary'>
            AI-proposed deadlines for attorney review · every confirmation improves future forecasts
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button
            size='small'
            variant='outlined'
            onClick={() => setAddOpen(true)}
            startIcon={<i className='ri-add-line' />}
          >
            Add Manual
          </Button>
          <Button
            size='small'
            variant='contained'
            onClick={handleGenerate}
            disabled={generating}
            startIcon={generating
              ? <CircularProgress size={14} color='inherit' />
              : <i className='ri-magic-line' />}
          >
            Generate Proposals
          </Button>
        </Box>
      </Box>

      {/* Gen result banner */}
      {genResult && (
        <Alert
          severity={genResult.missingAnchors.length > 0 ? 'warning' : 'success'}
          onClose={() => setGenResult(null)}
          sx={{ mb: 2, fontSize: '0.75rem' }}
        >
          {genResult.created} new proposal(s) generated.
          {genResult.missingAnchors.length > 0 && (
            <> {genResult.missingAnchors.length} skipped — missing date fields: {genResult.missingAnchors.join(', ')}. Update the client profile to enable these.</>
          )}
        </Alert>
      )}

      {/* Tabs */}
      <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}>
        <Tab label={
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
            Proposed
            {proposed.length > 0 && (
              <Chip label={proposed.length} size='small' color='primary' sx={{ fontSize: '0.6rem', height: 16 }} />
            )}
          </Box>
        } />
        <Tab label={`Confirmed (${confirmed.length})`} />
        <Tab label={`History (${history.length})`} />
      </Tabs>

      {/* Content */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
          <CircularProgress />
        </Box>
      ) : tabItems[tab].length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 6 }}>
          <i className='ri-calendar-check-line' style={{ fontSize: '2.5rem', color: '#ccc' }} />
          <Typography variant='body2' color='text.secondary' sx={{ mt: 1 }}>
            {tab === 0
              ? 'No pending proposals. Click "Generate Proposals" to forecast obligations from the knowledge base.'
              : tab === 1
              ? 'No confirmed deadlines. Confirm proposals above to schedule them.'
              : 'No completed or rejected items yet.'}
          </Typography>
        </Box>
      ) : (
        tabItems[tab].map(d => (
          <DeadlineCard
            key={d._id}
            deadline={d}
            onConfirm={setConfirmTarget}
            onReject={setRejectTarget}
            onComplete={handleComplete}
            onDelete={handleDelete}
          />
        ))
      )}

      {/* Dialogs */}
      {confirmTarget && (
        <ConfirmDialog
          deadline={confirmTarget}
          onClose={edits => edits !== undefined ? handleConfirm(confirmTarget, edits) : setConfirmTarget(null)}
        />
      )}
      {rejectTarget && (
        <RejectDialog
          deadline={rejectTarget}
          onClose={reason => reason !== undefined ? handleReject(rejectTarget, reason) : setRejectTarget(null)}
        />
      )}
      {addOpen && (
        <AddDeadlineDialog
          matterId={matterId}
          onClose={created => {
            setAddOpen(false)
            if (created) { setDeadlines(prev => [created, ...prev]); toast('Deadline added') }
          }}
        />
      )}

      <Snackbar
        open={snack.open}
        autoHideDuration={4000}
        onClose={() => setSnack(s => ({ ...s, open: false }))}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert severity={snack.severity} onClose={() => setSnack(s => ({ ...s, open: false }))}>
          {snack.msg}
        </Alert>
      </Snackbar>
    </Box>
  )
}
