'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 Chip from '@mui/material/Chip'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardHeader from '@mui/material/CardHeader'
import LinearProgress from '@mui/material/LinearProgress'
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 MenuItem from '@mui/material/MenuItem'
import Alert from '@mui/material/Alert'
import CircularProgress from '@mui/material/CircularProgress'
import Tooltip from '@mui/material/Tooltip'
import IconButton from '@mui/material/IconButton'
import Snackbar from '@mui/material/Snackbar'
import MatterTimelineView from '@/views/matter-deadlines/MatterTimelineView'

const API = '/api'

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

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

interface WorkflowTemplate {
  _id: string
  name: string
  description?: string
  practiceArea: string
  steps: { stepId: string; title: string; mandatory: boolean }[]
  isActive: boolean
}

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

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

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

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 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 ApplyDialog({
  matterId,
  templates,
  onClose,
}: {
  matterId: string
  templates: WorkflowTemplate[]
  onClose: (applied?: MatterWorkflow) => void
}) {
  const [selected, setSelected] = useState('')
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const selectedTpl = templates.find(t => t._id === selected)

  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) 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='sm' fullWidth>
      <DialogTitle sx={{ fontWeight: 700 }}>Apply Workflow</DialogTitle>
      <DialogContent sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
        {error && <Alert severity='error'>{error}</Alert>}
        <TextField
          select fullWidth size='small'
          label='Select workflow template'
          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 }}>
                <Box sx={{ width: 8, height: 8, borderRadius: '50%', bgcolor: PA_COLORS[tpl.practiceArea] ?? '#888', flexShrink: 0 }} />
                {tpl.name}
              </Box>
            </MenuItem>
          ))}
        </TextField>
        {selectedTpl && (
          <Box sx={{ p: 1.5, bgcolor: 'action.hover', borderRadius: 1 }}>
            <Typography variant='caption' sx={{ fontWeight: 600, display: 'block', mb: 0.5 }}>
              {selectedTpl.steps.length} steps
            </Typography>
            {selectedTpl.steps.slice(0, 5).map((s, i) => (
              <Typography key={s.stepId} variant='caption' color='text.secondary' sx={{ display: 'block', lineHeight: 1.6 }}>
                {i + 1}. {s.title}{s.mandatory ? ' *' : ''}
              </Typography>
            ))}
            {selectedTpl.steps.length > 5 && (
              <Typography variant='caption' color='text.disabled'>…+{selectedTpl.steps.length - 5} more</Typography>
            )}
          </Box>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={() => onClose()} disabled={busy}>Cancel</Button>
        <Button
          variant='contained'
          onClick={handleApply}
          disabled={!selected || busy}
          startIcon={busy ? <CircularProgress size={14} color='inherit' /> : <i className='ri-play-circle-line' />}
        >
          Apply
        </Button>
      </DialogActions>
    </Dialog>
  )
}

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

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

  return (
    <Card variant='outlined' sx={{ mb: 1.5 }}>
      <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' ? 'Completed' : 'Active'}
              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]
            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 }}>
                  <Box sx={{ mt: 0.2, flexShrink: 0 }}>
                    <i className={icon} style={{ fontSize: '1.1rem', color }} />
                  </Box>
                  <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='Required' size='small' 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>
                  <Box sx={{ display: 'flex', gap: 0.5, flexShrink: 0 }}>
                    {step.status !== 'completed' && (
                      <Tooltip title='Mark complete'>
                        <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='Mark in progress'>
                        <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='Skip'>
                        <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'>
                        <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>
  )
}

// ─── Main Panel ─────────────────────────────────────────────────────────────────

export default function MatterWorkflowsPanel({
  matterId,
  practiceArea,
}: {
  matterId: string
  practiceArea: string
}) {
  const [workflows,  setWorkflows]  = useState<MatterWorkflow[]>([])
  const [templates,  setTemplates]  = useState<WorkflowTemplate[]>([])
  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 toast = (msg: string, severity: 'success' | 'error' = 'success') =>
    setSnack({ open: true, msg, severity })

  const accentColor = PA_COLORS[practiceArea] ?? '#2F3349'

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const [wRes, tRes] = await Promise.all([
        fetch(`${API}/workflows/matter/${matterId}`),
        fetch(`${API}/workflow-templates?practiceArea=${practiceArea}`),
      ])
      if (wRes.ok) setWorkflows(await wRes.json())
      if (tRes.ok) {
        const all = await tRes.json()
        setTemplates((all as WorkflowTemplate[]).filter(t => t.isActive))
      }
    } finally {
      setLoading(false)
    }
  }, [matterId, practiceArea])

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

  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 {
      toast('Failed to update step', 'error')
    }
  }

  return (
    <Box>
      {/* Section header */}
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box sx={{ width: 8, height: 8, borderRadius: '50%', bgcolor: accentColor }} />
          <Typography variant='subtitle2' sx={{ fontWeight: 700 }}>Workflows & Obligations</Typography>
          {workflows.length > 0 && (
            <Chip label={`${workflows.length} active`} size='small' sx={{ fontSize: '0.6rem', height: 16 }} />
          )}
        </Box>
        <Button
          size='small'
          variant='contained'
          disabled={templates.length === 0}
          onClick={() => setApplying(true)}
          startIcon={<i className='ri-play-circle-line' style={{ fontSize: '0.85rem' }} />}
          sx={{ bgcolor: accentColor, '&:hover': { bgcolor: accentColor + 'cc' } }}
        >
          Apply Workflow
        </Button>
      </Box>

      {/* Workflow checklists */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}><CircularProgress size={24} /></Box>
      ) : workflows.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 4, border: '1px dashed', borderColor: 'divider', borderRadius: 2, mb: 2 }}>
          <i className='ri-list-check-3' style={{ fontSize: '2rem', color: '#ccc' }} />
          <Typography variant='body2' color='text.secondary' sx={{ mt: 1 }}>
            No workflows applied yet
          </Typography>
          <Typography variant='caption' color='text.disabled'>
            Click "Apply Workflow" to attach a process checklist to this matter
          </Typography>
        </Box>
      ) : (
        workflows.map(wf => (
          <WorkflowCard key={wf._id} workflow={wf} onStepUpdate={handleStepUpdate} />
        ))
      )}

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

      {/* Obligation timeline */}
      <MatterTimelineView matterId={matterId} />

      {/* Apply dialog */}
      {applying && (
        <ApplyDialog
          matterId={matterId}
          templates={templates}
          onClose={applied => {
            setApplying(false)
            if (applied) {
              setWorkflows(prev => [applied, ...prev])
              toast(`"${applied.templateName}" applied`)
            }
          }}
        />
      )}

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