'use client'
import { useState, useEffect, useCallback, lazy, Suspense } from 'react'
const WorkflowBuilderView = lazy(() => import('./WorkflowBuilderView'))
import MatterTimelineView from '@/views/matter-deadlines/MatterTimelineView'
import { useT } from '@/contexts/LangContext'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardHeader from '@mui/material/CardHeader'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import CircularProgress from '@mui/material/CircularProgress'
import Alert from '@mui/material/Alert'
import MenuItem from '@mui/material/MenuItem'
import TextField from '@mui/material/TextField'
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 Snackbar from '@mui/material/Snackbar'
import Divider from '@mui/material/Divider'
import Accordion from '@mui/material/Accordion'
import AccordionSummary from '@mui/material/AccordionSummary'
import AccordionDetails from '@mui/material/AccordionDetails'
import LinearProgress from '@mui/material/LinearProgress'
import Tooltip from '@mui/material/Tooltip'
import IconButton from '@mui/material/IconButton'
import Grid from '@mui/material/Grid'
import Tab from '@mui/material/Tab'
import Tabs from '@mui/material/Tabs'

const API = '/api'

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

type PracticeArea =
  | 'immigration' | 'corporate' | 'civil_litigation' | 'property'
  | 'family' | 'employment' | 'criminal' | 'other' | 'universal'

type WorkflowStepStatus = 'pending' | 'in_progress' | 'completed' | 'skipped'

interface WorkflowStepDef {
  stepId: string
  order: number
  title: string
  description?: string
  mandatory: boolean
  linkedFormTemplateId?: string
  deadlineDays?: number
}

interface WorkflowTemplate {
  _id: string
  name: string
  description?: string
  practiceArea: PracticeArea
  steps: WorkflowStepDef[]
  isActive: boolean
  isSystem: boolean
  createdAt: string
}

interface MatterWorkflowStep {
  stepId: string
  order: number
  title: string
  description?: string
  mandatory: boolean
  linkedFormTemplateId?: string
  status: WorkflowStepStatus
  dueDate?: string
  completedAt?: string
  completedBy?: string
  notes?: string
}

interface MatterWorkflow {
  _id: string
  matterId: string
  clientFolderId: string
  templateId: string
  templateName: string
  steps: MatterWorkflowStep[]
  status: 'active' | 'completed' | 'archived'
  createdAt: string
}

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

const PA_LABELS: Record<string, string> = {
  immigration:      'Immigration',
  corporate:        'Corporate',
  civil_litigation: 'Civil Litigation',
  property:         'Property',
  family:           'Family',
  employment:       'Employment',
  criminal:         'Criminal',
  other:            'Other',
  universal:        'Universal',
}

const PA_COLORS: Record<string, string> = {
  immigration:      '#16B1FF',
  corporate:        '#9C6FDE',
  civil_litigation: '#FF4C51',
  property:         '#56CA00',
  family:           '#FFB400',
  employment:       '#0D9394',
  criminal:         '#FF6B00',
  other:            '#8A8D93',
  universal:        '#2F3349',
}

const STEP_STATUS_COLORS: Record<WorkflowStepStatus, string> = {
  pending:     '#8A8D93',
  in_progress: '#FFB400',
  completed:   '#56CA00',
  skipped:     '#c0c0c0',
}

const STEP_STATUS_ICONS: Record<WorkflowStepStatus, string> = {
  pending:     'ri-circle-line',
  in_progress: 'ri-refresh-line',
  completed:   'ri-checkbox-circle-fill',
  skipped:     'ri-skip-forward-line',
}

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

function progressPct(steps: MatterWorkflowStep[]) {
  if (!steps.length) return 0
  const done = steps.filter(s => s.status === 'completed' || s.status === 'skipped').length
  return Math.round((done / steps.length) * 100)
}

// ─── Apply Workflow Dialog ─────────────────────────────────────────────────────

function ApplyWorkflowDialog({
  matterId,
  templates,
  onClose,
}: {
  matterId: string
  templates: WorkflowTemplate[]
  onClose: (applied?: MatterWorkflow) => void
}) {
  const t = useT()
  const [selected, setSelected] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleApply = async () => {
    if (!selected) return
    setBusy(true)
    setError(null)
    try {
      const res = await fetch(`${API}/workflows/instantiate`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ templateId: selected, matterId }),
      })
      if (!res.ok) {
        const body = await res.json().catch(() => ({}))
        throw new Error(body.message ?? res.statusText)
      }
      const workflow: MatterWorkflow = await res.json()
      onClose(workflow)
    } catch (e: any) {
      setError(e.message ?? t.workflows.applyError)
    } finally {
      setBusy(false)
    }
  }

  const selectedTemplate = templates.find(tpl => tpl._id === selected)

  return (
    <Dialog open onClose={() => onClose()} maxWidth='sm' fullWidth>
      <DialogTitle>{t.workflows.applyTitle}</DialogTitle>
      <DialogContent sx={{ pt: 2 }}>
        {error && <Alert severity='error' sx={{ mb: 2 }}>{error}</Alert>}
        <Typography variant='body2' color='text.secondary' sx={{ mb: 2 }}>{t.workflows.applySubtitle}</Typography>
        <TextField
          select
          fullWidth
          size='small'
          label={t.workflows.applySelectLabel}
          value={selected}
          onChange={e => setSelected(e.target.value)}
        >
          {templates.map(tpl => (
            <MenuItem key={tpl._id} value={tpl._id}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <span>{tpl.name}</span>
                <Chip
                  label={PA_LABELS[tpl.practiceArea] ?? tpl.practiceArea}
                  size='small'
                  sx={{ fontSize: '0.6rem', height: 16, bgcolor: (PA_COLORS[tpl.practiceArea] ?? '#888') + '22', color: PA_COLORS[tpl.practiceArea] ?? '#888' }}
                />
              </Box>
            </MenuItem>
          ))}
        </TextField>

        {selectedTemplate && (
          <Box sx={{ mt: 2, p: 1.5, bgcolor: 'action.hover', borderRadius: 1 }}>
            <Typography variant='caption' sx={{ fontWeight: 600, display: 'block', mb: 0.5 }}>
              {t.workflows.steps(selectedTemplate.steps.length)}
            </Typography>
            {selectedTemplate.steps.slice(0, 5).map((step, i) => (
              <Typography key={step.stepId} variant='caption' color='text.secondary' sx={{ display: 'block', lineHeight: 1.6 }}>
                {i + 1}. {step.title}{step.mandatory ? ' *' : ''}
              </Typography>
            ))}
            {selectedTemplate.steps.length > 5 && (
              <Typography variant='caption' color='text.disabled'>…+{selectedTemplate.steps.length - 5} more</Typography>
            )}
          </Box>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={() => onClose()} disabled={busy}>{t.common.cancel}</Button>
        <Button
          variant='contained'
          onClick={handleApply}
          disabled={!selected || busy}
          startIcon={busy ? <CircularProgress size={14} color='inherit' /> : <i className='ri-play-circle-line' />}
        >
          {t.workflows.applyConfirm}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

// ─── Workflow Checklist ────────────────────────────────────────────────────────

function WorkflowChecklist({
  workflow,
  onStepUpdate,
}: {
  workflow: MatterWorkflow
  onStepUpdate: (workflowId: string, stepId: string, status: WorkflowStepStatus) => void
}) {
  const t = useT()
  const pct = progressPct(workflow.steps)

  const statusLabel: Record<WorkflowStepStatus, string> = {
    pending:     t.workflows.statusPending,
    in_progress: t.workflows.statusInProgress,
    completed:   t.workflows.statusCompleted,
    skipped:     t.workflows.statusSkipped,
  }

  return (
    <Card variant='outlined' sx={{ mb: 2 }}>
      <CardHeader
        title={
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Typography variant='subtitle2' sx={{ fontWeight: 700 }}>{workflow.templateName}</Typography>
            <Chip
              size='small'
              label={workflow.status === 'completed' ? t.workflows.workflowCompleted : t.workflows.workflowActive}
              color={workflow.status === 'completed' ? 'success' : 'primary'}
              sx={{ fontSize: '0.6rem', height: 16 }}
            />
          </Box>
        }
        subheader={
          <Box sx={{ mt: 0.75 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
              <LinearProgress variant='determinate' value={pct} sx={{ flex: 1, height: 4, borderRadius: 2 }} />
              <Typography variant='caption' color='text.secondary'>{pct}%</Typography>
            </Box>
            <Typography variant='caption' color='text.disabled'>
              {workflow.steps.filter(s => s.status === 'completed').length} / {workflow.steps.length} steps done
            </Typography>
          </Box>
        }
        sx={{ pb: 0 }}
      />
      <CardContent sx={{ pt: 1 }}>
        {workflow.steps
          .slice()
          .sort((a, b) => a.order - b.order)
          .map((step, idx) => {
            const color = STEP_STATUS_COLORS[step.status]
            const icon  = STEP_STATUS_ICONS[step.status]
            const isOverdue = step.status === 'pending' && step.dueDate && new Date(step.dueDate) < new Date()

            return (
              <Box key={step.stepId}>
                {idx > 0 && <Divider sx={{ my: 0.75 }} />}
                <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1.5, py: 0.5 }}>
                  {/* Status icon */}
                  <Box sx={{ mt: 0.2, flexShrink: 0 }}>
                    <i className={icon} style={{ fontSize: '1.1rem', color }} />
                  </Box>

                  {/* Content */}
                  <Box sx={{ flex: 1, minWidth: 0 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, flexWrap: 'wrap' }}>
                      <Typography
                        variant='body2'
                        sx={{
                          fontWeight: step.status === 'completed' ? 400 : 600,
                          textDecoration: step.status === 'skipped' ? 'line-through' : 'none',
                          color: step.status === 'skipped' ? 'text.disabled' : 'text.primary',
                        }}
                      >
                        {step.title}
                      </Typography>
                      {step.mandatory && (
                        <Chip label={t.workflows.mandatoryBadge} size='small' sx={{ fontSize: '0.55rem', height: 14 }} />
                      )}
                      {isOverdue && (
                        <Chip label={t.common.overdue} size='small' color='error' sx={{ fontSize: '0.55rem', height: 14 }} />
                      )}
                    </Box>

                    {step.description && (
                      <Typography variant='caption' color='text.secondary' sx={{ display: 'block', mt: 0.2, lineHeight: 1.4 }}>
                        {step.description}
                      </Typography>
                    )}

                    <Box sx={{ display: 'flex', gap: 2, mt: 0.5, flexWrap: 'wrap' }}>
                      {step.dueDate && (
                        <Typography variant='caption' color={isOverdue ? 'error' : 'text.disabled'}>
                          <i className='ri-calendar-line' style={{ fontSize: '0.7rem', marginRight: 2 }} />
                          {t.workflows.stepDue}: {fmtDate(step.dueDate)}
                        </Typography>
                      )}
                      {step.completedAt && (
                        <Typography variant='caption' color='text.disabled'>
                          <i className='ri-check-line' style={{ fontSize: '0.7rem', marginRight: 2 }} />
                          {fmtDate(step.completedAt)}{step.completedBy ? ` · ${step.completedBy}` : ''}
                        </Typography>
                      )}
                    </Box>
                  </Box>

                  {/* Step actions */}
                  <Box sx={{ display: 'flex', gap: 0.5, flexShrink: 0 }}>
                    {step.status !== 'completed' && (
                      <Tooltip title={t.workflows.markComplete}>
                        <IconButton
                          size='small'
                          onClick={() => onStepUpdate(workflow._id, step.stepId, 'completed')}
                          sx={{ color: '#56CA00' }}
                        >
                          <i className='ri-checkbox-circle-line' style={{ fontSize: '1rem' }} />
                        </IconButton>
                      </Tooltip>
                    )}
                    {step.status === 'pending' && (
                      <Tooltip title={t.workflows.markInProgress}>
                        <IconButton
                          size='small'
                          onClick={() => onStepUpdate(workflow._id, step.stepId, 'in_progress')}
                          sx={{ color: '#FFB400' }}
                        >
                          <i className='ri-refresh-line' style={{ fontSize: '1rem' }} />
                        </IconButton>
                      </Tooltip>
                    )}
                    {step.status !== 'skipped' && step.status !== 'completed' && !step.mandatory && (
                      <Tooltip title={t.workflows.skipStep}>
                        <IconButton
                          size='small'
                          onClick={() => onStepUpdate(workflow._id, step.stepId, 'skipped')}
                          sx={{ color: 'text.disabled' }}
                        >
                          <i className='ri-skip-forward-line' style={{ fontSize: '1rem' }} />
                        </IconButton>
                      </Tooltip>
                    )}
                    {step.status === 'completed' && (
                      <Tooltip title='Reopen step'>
                        <IconButton
                          size='small'
                          onClick={() => onStepUpdate(workflow._id, step.stepId, 'pending')}
                          sx={{ color: 'text.disabled' }}
                        >
                          <i className='ri-arrow-go-back-line' style={{ fontSize: '0.9rem' }} />
                        </IconButton>
                      </Tooltip>
                    )}
                  </Box>
                </Box>
              </Box>
            )
          })}
      </CardContent>
    </Card>
  )
}

// ─── Template browser tab ──────────────────────────────────────────────────────

function TemplatesBrowser({
  templates,
  loading,
  areaFilter,
  onAreaFilter,
  onEdit,
  onToggle,
}: {
  templates: WorkflowTemplate[]
  loading: boolean
  areaFilter: string
  onAreaFilter: (v: string) => void
  onEdit: (id: string) => void
  onToggle: (id: string, isActive: boolean) => void
}) {
  const t = useT()

  const AREAS = [
    { value: 'all', label: t.workflows.allAreas },
    ...Object.entries(PA_LABELS).map(([v, label]) => ({ value: v, label })),
  ]

  const visible = areaFilter === 'all'
    ? templates
    : templates.filter(tpl => tpl.practiceArea === areaFilter || tpl.practiceArea === 'universal')

  return (
    <Box>
      <Box sx={{ display: 'flex', gap: 2, mb: 3, flexWrap: 'wrap', alignItems: 'center' }}>
        <TextField
          select size='small' value={areaFilter}
          label={t.workflows.allAreas}
          onChange={e => onAreaFilter(e.target.value)}
          sx={{ minWidth: 200 }}
        >
          {AREAS.map(a => <MenuItem key={a.value} value={a.value}>{a.label}</MenuItem>)}
        </TextField>
      </Box>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}><CircularProgress /></Box>
      ) : visible.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 8 }}>
          <i className='ri-list-check-3' style={{ fontSize: '3rem', color: '#ccc' }} />
          <Typography variant='body1' sx={{ mt: 1 }}>{t.workflows.noTemplates}</Typography>
        </Box>
      ) : (
        <Grid container spacing={2}>
          {visible.map(tpl => {
            const color = PA_COLORS[tpl.practiceArea] ?? '#888'
            return (
              <Grid size={{ xs: 12, sm: 6, md: 4 }} key={tpl._id}>
                <Card variant='outlined' sx={{
                  borderColor: color + '44',
                  opacity: tpl.isActive ? 1 : 0.55,
                  transition: 'opacity 0.2s',
                }}>
                  <CardContent>
                    <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 1 }}>
                      <Box sx={{
                        width: 32, height: 32, borderRadius: 1, flexShrink: 0,
                        bgcolor: color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        <i className='ri-list-check-3' style={{ fontSize: '1rem', color }} />
                      </Box>
                      <Box sx={{ flex: 1, minWidth: 0 }}>
                        <Typography variant='subtitle2' noWrap sx={{ fontWeight: 600 }}>{tpl.name}</Typography>
                        <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
                          <Chip label={PA_LABELS[tpl.practiceArea] ?? tpl.practiceArea} size='small'
                            sx={{ fontSize: '0.6rem', height: 14, bgcolor: color + '18', color }} />
                          {tpl.isSystem && (
                            <Chip label='System' size='small' sx={{ fontSize: '0.6rem', height: 14 }} />
                          )}
                          <Chip
                            label={tpl.isActive ? 'Enabled' : 'Disabled'}
                            size='small'
                            sx={{ fontSize: '0.6rem', height: 14,
                              bgcolor: tpl.isActive ? '#56CA0018' : '#8A8D9318',
                              color: tpl.isActive ? '#56CA00' : '#8A8D93' }}
                          />
                        </Box>
                      </Box>
                      <Tooltip title={tpl.isActive ? 'Disable this workflow' : 'Enable this workflow'}>
                        <IconButton size='small' onClick={() => onToggle(tpl._id, !tpl.isActive)}>
                          <i className={tpl.isActive ? 'ri-toggle-fill' : 'ri-toggle-line'}
                            style={{ fontSize: '1.2rem', color: tpl.isActive ? '#56CA00' : '#8A8D93' }} />
                        </IconButton>
                      </Tooltip>
                    </Box>
                    {tpl.description && (
                      <Typography variant='caption' color='text.secondary' sx={{ display: 'block', mb: 1, lineHeight: 1.4 }}>
                        {tpl.description}
                      </Typography>
                    )}
                    <Typography variant='caption' color='text.disabled'>
                      {t.workflows.steps(tpl.steps.length)}
                      {' · '}
                      {tpl.steps.filter(s => s.mandatory).length} mandatory
                    </Typography>
                  </CardContent>
                  <Box sx={{ px: 2, pb: 1.5, display: 'flex', gap: 1 }}>
                    <Button
                      size='small'
                      variant='outlined'
                      startIcon={<i className='ri-edit-line' style={{ fontSize: '0.75rem' }} />}
                      onClick={() => onEdit(tpl._id)}
                      sx={{ fontSize: '0.7rem' }}
                    >
                      Edit in Builder
                    </Button>
                  </Box>
                </Card>
              </Grid>
            )
          })}
        </Grid>
      )}
    </Box>
  )
}

// ─── Matter Workflows tab ─────────────────────────────────────────────────────

function MatterWorkflowsTab({
  matterId,
  templates,
}: {
  matterId: string
  templates: WorkflowTemplate[]
}) {
  const t = useT()
  const [workflows, setWorkflows] = useState<MatterWorkflow[]>([])
  const [loading, setLoading] = useState(true)
  const [applying, setApplying] = useState(false)
  const [snack, setSnack] = useState<{ open: boolean; msg: string; severity: 'success' | 'error' }>({
    open: false, msg: '', severity: 'success',
  })

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

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

  const handleApplyClose = (applied?: MatterWorkflow) => {
    setApplying(false)
    if (applied) {
      setWorkflows(prev => [applied, ...prev])
      const tplName = templates.find(t => t._id === applied.templateId)?.name ?? applied.templateName
      setSnack({ open: true, msg: t.workflows.applySuccess(tplName), severity: 'success' })
    }
  }

  const handleStepUpdate = async (workflowId: string, stepId: string, status: WorkflowStepStatus) => {
    try {
      const res = await fetch(`${API}/workflows/${workflowId}/steps/${stepId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      })
      if (!res.ok) throw new Error(res.statusText)
      const updated: MatterWorkflow = await res.json()
      setWorkflows(prev => prev.map(wf => wf._id === workflowId ? updated : wf))
    } catch {
      setSnack({ open: true, msg: 'Failed to update step', severity: 'error' })
    }
  }

  if (!matterId) {
    return (
      <Box sx={{ textAlign: 'center', py: 8 }}>
        <Typography variant='body2' color='text.secondary'>Enter a Matter ID above to view its active workflows</Typography>
      </Box>
    )
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 2 }}>
        <Button
          variant='contained'
          startIcon={<i className='ri-play-circle-line' style={{ fontSize: '0.9rem' }} />}
          onClick={() => setApplying(true)}
          size='small'
          disabled={templates.length === 0}
        >
          {t.workflows.applyBtn}
        </Button>
      </Box>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}><CircularProgress /></Box>
      ) : workflows.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 8 }}>
          <i className='ri-list-check-3' style={{ fontSize: '3rem', color: '#ccc' }} />
          <Typography variant='body1' sx={{ mt: 1 }}>{t.workflows.noWorkflows}</Typography>
          <Typography variant='caption' color='text.secondary'>{t.workflows.noWorkflowsHint}</Typography>
        </Box>
      ) : (
        workflows.map(wf => (
          <WorkflowChecklist key={wf._id} workflow={wf} onStepUpdate={handleStepUpdate} />
        ))
      )}

      {applying && (
        <ApplyWorkflowDialog
          matterId={matterId}
          templates={templates}
          onClose={handleApplyClose}
        />
      )}

      <Divider sx={{ my: 3 }} />

      {/* Obligation timeline — deadlines and compliance events for this matter */}
      <MatterTimelineView matterId={matterId} />

      <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>
  )
}

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

export default function WorkflowsView() {
  const t = useT()
  const [templates, setTemplates] = useState<WorkflowTemplate[]>([])
  const [templatesLoading, setTemplatesLoading] = useState(true)
  const [areaFilter, setAreaFilter] = useState('all')
  const [building, setBuilding] = useState(false)
  const [editId, setEditId] = useState<string | undefined>()

  const loadTemplates = useCallback(async () => {
    setTemplatesLoading(true)
    try {
      const res = await fetch(`${API}/workflow-templates`)
      if (res.ok) setTemplates(await res.json())
    } finally {
      setTemplatesLoading(false)
    }
  }, [])

  const handleToggle = useCallback(async (id: string, isActive: boolean) => {
    try {
      const res = await fetch(`${API}/workflow-templates/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isActive }),
      })
      if (res.ok) {
        const updated = await res.json()
        setTemplates(prev => prev.map(t => t._id === id ? { ...t, isActive: updated.isActive } : t))
      }
    } catch { /* silent */ }
  }, [])

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

  if (building) {
    return (
      <Box sx={{ height: 'calc(100vh - 120px)', display: 'flex', flexDirection: 'column' }}>
        <Suspense fallback={<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}><CircularProgress /></Box>}>
          <WorkflowBuilderView
            editId={editId}
            onSaved={() => { setBuilding(false); setEditId(undefined); loadTemplates() }}
            onCancel={() => { setBuilding(false); setEditId(undefined) }}
          />
        </Suspense>
      </Box>
    )
  }

  return (
    <Box>
      {/* Page header */}
      <Box sx={{ mb: 3, display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 2, flexWrap: 'wrap' }}>
        <Box>
          <Typography variant='h5' sx={{ fontWeight: 700, mb: 0.5 }}>{t.workflows.title}</Typography>
          <Typography variant='body2' color='text.secondary'>
            Manage workflow templates. Assign workflows to matters from inside the client record.
          </Typography>
        </Box>
        <Button
          variant='contained'
          startIcon={<i className='ri-node-tree' style={{ fontSize: '0.9rem' }} />}
          onClick={() => { setEditId(undefined); setBuilding(true) }}
          size='small'
        >
          Build Workflow
        </Button>
      </Box>

      <TemplatesBrowser
        templates={templates}
        loading={templatesLoading}
        areaFilter={areaFilter}
        onAreaFilter={setAreaFilter}
        onEdit={id => { setEditId(id); setBuilding(true) }}
        onToggle={handleToggle}
      />
    </Box>
  )
}
