'use client'

import { useState, useEffect, useCallback } from 'react'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Tabs from '@mui/material/Tabs'
import Tab from '@mui/material/Tab'
import Chip from '@mui/material/Chip'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import TextField from '@mui/material/TextField'
import Divider from '@mui/material/Divider'
import CircularProgress from '@mui/material/CircularProgress'
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 MenuItem from '@mui/material/MenuItem'
import Alert from '@mui/material/Alert'
import Tooltip from '@mui/material/Tooltip'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'
import type { Email, AssociationCandidate } from '../clients/types'

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

function formatDate(iso: string) {
  const d = new Date(iso)
  const now = new Date()
  const isToday = d.toDateString() === now.toDateString()
  if (isToday) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  return d.toLocaleDateString([], { month: 'short', day: 'numeric', year: d.getFullYear() !== now.getFullYear() ? 'numeric' : undefined })
}

function addrLabel(a: { address: string; name?: string }) {
  return a.name ? a.name : a.address
}

const ASSOC_COLORS: Record<string, { bg: string; color: string; label: string }> = {
  auto_matched:   { bg: '#EEFBE5', color: '#52B630', label: 'Auto-matched' },
  confirmed:      { bg: '#E8F7F7', color: '#0D9394', label: 'Confirmed' },
  ai_suggested:   { bg: '#EEF2FF', color: '#7C6AF7', label: 'AI suggested' },
  pending_review: { bg: '#FFF4CC', color: '#CC8800', label: 'Needs review' },
  unassociated:   { bg: '#FFE9E9', color: '#CC2200', label: 'Unassociated' },
}

// ─── Thread list item ─────────────────────────────────────────────────────────

function EmailRow({
  email,
  selected,
  onClick,
}: {
  email: Email
  selected: boolean
  onClick: () => void
}) {
  const assoc = ASSOC_COLORS[email.associationStatus] ?? ASSOC_COLORS.unassociated
  const preview = email.bodyText?.slice(0, 120).replace(/\n/g, ' ') ?? ''

  return (
    <Box
      onClick={onClick}
      sx={{
        px: 2, py: 1.5, cursor: 'pointer', borderBottom: '1px solid', borderColor: 'divider',
        bgcolor: selected ? 'action.selected' : email.isRead ? 'background.paper' : 'action.hover',
        '&:hover': { bgcolor: 'action.hover' },
        display: 'flex', gap: 1.5, alignItems: 'flex-start',
      }}
    >
      {/* Direction indicator */}
      <Box sx={{ mt: 0.5, color: email.direction === 'inbound' ? '#0D9394' : '#7C6AF7', flexShrink: 0 }}>
        <i className={email.direction === 'inbound' ? 'ri-mail-download-line' : 'ri-mail-send-line'} style={{ fontSize: '1.1rem' }} />
      </Box>

      <Box sx={{ flex: 1, minWidth: 0 }}>
        <Box sx={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 1 }}>
          <Typography
            variant='body2'
            sx={{ fontWeight: email.isRead ? 400 : 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
          >
            {email.direction === 'inbound' ? addrLabel(email.from) : email.to.map(addrLabel).join(', ')}
          </Typography>
          <Typography variant='caption' color='text.disabled' sx={{ flexShrink: 0 }}>
            {formatDate(email.receivedAt)}
          </Typography>
        </Box>

        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mt: 0.25 }}>
          <Typography variant='body2' sx={{ fontWeight: email.isRead ? 500 : 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>
            {email.subject}
          </Typography>
          <Chip
            label={assoc.label} size='small'
            sx={{ bgcolor: assoc.bg, color: assoc.color, fontWeight: 600, height: 18, fontSize: '0.7rem', flexShrink: 0 }}
          />
        </Box>

        {preview && (
          <Typography variant='caption' color='text.secondary' sx={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', mt: 0.25 }}>
            {preview}
          </Typography>
        )}
      </Box>
    </Box>
  )
}

// ─── Association dialog ───────────────────────────────────────────────────────

function AssociateDialog({
  email,
  onConfirm,
  onClose,
}: {
  email: Email
  onConfirm: (clientFolderId: string, matterId?: string) => void
  onClose: () => void
}) {
  const [selected, setSelected] = useState<AssociationCandidate | null>(
    email.associationCandidates[0] ?? null,
  )
  const [selectedMatter, setSelectedMatter] = useState(selected?.matterId ?? '')

  return (
    <Dialog open onClose={onClose} maxWidth='sm' fullWidth>
      <DialogTitle>Route Email to Client / Matter</DialogTitle>
      <DialogContent>
        <Typography variant='body2' color='text.secondary' sx={{ mb: 2 }}>
          <strong>From:</strong> {addrLabel(email.from)}<br />
          <strong>Subject:</strong> {email.subject}
        </Typography>

        {email.associationCandidates.length === 0 ? (
          <Alert severity='warning'>
            No candidates found automatically. The Client Manager AI will review this email and suggest an association.
            For now you can manually enter the client folder ID below.
          </Alert>
        ) : (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
            <Typography variant='caption' color='text.secondary' sx={{ mb: 0.5 }}>
              Select the correct client association:
            </Typography>
            {email.associationCandidates.map((c, i) => (
              <Box
                key={i}
                onClick={() => { setSelected(c); setSelectedMatter(c.matterId ?? '') }}
                sx={{
                  p: 1.5, borderRadius: 1.5, cursor: 'pointer', border: '2px solid',
                  borderColor: selected?.clientFolderId === c.clientFolderId && selected?.matterId === c.matterId ? '#0D9394' : 'divider',
                  bgcolor: selected?.clientFolderId === c.clientFolderId && selected?.matterId === c.matterId ? '#E8F7F7' : 'background.paper',
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Typography variant='body2' sx={{ fontWeight: 700 }}>{c.displayName}</Typography>
                  <Chip label={c.folderNumber} size='small' sx={{ height: 18, fontSize: '0.7rem' }} />
                  <Chip
                    label={`${Math.round(c.confidence * 100)}% ${c.reason.replace('_', ' ')}`}
                    size='small'
                    sx={{ height: 18, fontSize: '0.7rem', bgcolor: '#EEF2FF', color: '#7C6AF7' }}
                  />
                </Box>
                {c.matterTitle && (
                  <Typography variant='caption' color='text.secondary'>
                    Matter: {c.matterNumber} — {c.matterTitle}
                  </Typography>
                )}
              </Box>
            ))}
          </Box>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button
          variant='contained'
          disabled={!selected}
          onClick={() => selected && onConfirm(selected.clientFolderId, selectedMatter || selected.matterId)}
          sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
        >
          Confirm Association
        </Button>
      </DialogActions>
    </Dialog>
  )
}

// ─── Email detail panel ───────────────────────────────────────────────────────

function EmailDetail({
  email,
  onAssociate,
  onMarkRead,
}: {
  email: Email
  onAssociate: () => void
  onMarkRead: () => void
}) {
  useEffect(() => {
    if (!email.isRead) onMarkRead()
  }, [email._id])

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Header */}
      <Box sx={{ p: 2, borderBottom: '1px solid', borderColor: 'divider' }}>
        <Typography variant='h6' sx={{ fontWeight: 700, mb: 0.5 }}>{email.subject}</Typography>
        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', alignItems: 'center' }}>
          <Typography variant='body2' color='text.secondary'>
            <strong>From:</strong> {addrLabel(email.from)} &lt;{email.from.address}&gt;
          </Typography>
          <Typography variant='caption' color='text.disabled'>·</Typography>
          <Typography variant='body2' color='text.secondary'>
            {new Date(email.receivedAt).toLocaleString()}
          </Typography>
        </Box>
        <Typography variant='body2' color='text.secondary' sx={{ mt: 0.5 }}>
          <strong>To:</strong> {email.to.map(addrLabel).join(', ')}
          {email.cc?.length > 0 && <> &nbsp;<strong>Cc:</strong> {email.cc.map(addrLabel).join(', ')}</>}
        </Typography>

        {/* Association status */}
        <Box sx={{ display: 'flex', gap: 1, mt: 1.5, alignItems: 'center' }}>
          {email.clientFolderId ? (
            <Chip
              label={`${ASSOC_COLORS[email.associationStatus]?.label} — routed`}
              size='small'
              sx={{ bgcolor: ASSOC_COLORS[email.associationStatus]?.bg, color: ASSOC_COLORS[email.associationStatus]?.color, fontWeight: 600 }}
            />
          ) : (
            <>
              <Chip label='Unrouted' size='small' sx={{ bgcolor: '#FFE9E9', color: '#CC2200', fontWeight: 600 }} />
              <Button
                size='small' variant='outlined'
                onClick={onAssociate}
                startIcon={<i className='ri-link-m' />}
                sx={{ borderColor: '#0D9394', color: '#0D9394' }}
              >
                Route to Client / Matter
              </Button>
            </>
          )}
        </Box>
      </Box>

      {/* Body */}
      <Box sx={{ flex: 1, overflow: 'auto', p: 2 }}>
        {email.bodyHtml ? (
          <Box
            sx={{ '& *': { maxWidth: '100%' } }}
            dangerouslySetInnerHTML={{ __html: email.bodyHtml }}
          />
        ) : (
          <Typography variant='body2' sx={{ whiteSpace: 'pre-wrap', lineHeight: 1.7 }}>
            {email.bodyText ?? '(no body)'}
          </Typography>
        )}
      </Box>

      {/* Attachments */}
      {email.attachments?.length > 0 && (
        <Box sx={{ p: 2, borderTop: '1px solid', borderColor: 'divider' }}>
          <Typography variant='caption' color='text.secondary' sx={{ fontWeight: 600 }}>
            Attachments ({email.attachments.length})
          </Typography>
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.75, mt: 0.75 }}>
            {email.attachments.map((a, i) => (
              <Chip key={i} size='small' icon={<i className='ri-attachment-line' />}
                label={`${a.filename} (${(a.size / 1024).toFixed(0)} KB)`}
                sx={{ height: 22 }}
              />
            ))}
          </Box>
        </Box>
      )}
    </Box>
  )
}

// ─── Server settings panel ────────────────────────────────────────────────────

interface EmailSettings {
  smtpListenPort: number
  smtpListenHost: string
  imapEnabled: boolean
  imapHost?: string
  imapPort: number
  imapSsl: boolean
  imapUser?: string
  imapPassword?: string
  imapFolder: string
  imapPollIntervalSeconds: number
  outboundSmtpHost?: string
  outboundSmtpPort: number
  outboundSmtpSsl: boolean
  outboundSmtpUser?: string
  outboundSmtpPassword?: string
  outboundFromAddress?: string
  outboundFromName?: string
}

const DEFAULT_SETTINGS: EmailSettings = {
  smtpListenPort: 2525,
  smtpListenHost: '0.0.0.0',
  imapEnabled: false,
  imapPort: 993,
  imapSsl: true,
  imapFolder: 'INBOX',
  imapPollIntervalSeconds: 60,
  outboundSmtpPort: 587,
  outboundSmtpSsl: false,
}

interface TestResult {
  tested: boolean
  success: boolean
  message: string
}
interface TestResults {
  imap: TestResult
  smtp: TestResult
}

function ServerSettings() {
  const [s,        setS]       = useState<EmailSettings>(DEFAULT_SETTINGS)
  const [loaded,   setLoaded]  = useState(false)
  const [testing,  setTesting] = useState(false)
  const [testRes,  setTestRes] = useState<TestResults | null>(null)
  const [saving,   setSaving]  = useState(false)
  const [saved,    setSaved]   = useState(false)
  const [err,      setErr]     = useState<string | null>(null)

  useEffect(() => {
    fetch('/api/email/settings').then(r => r.json()).then(d => {
      if (d && !d.error) setS({ ...DEFAULT_SETTINGS, ...d })
      setLoaded(true)
    }).catch(() => setLoaded(true))
  }, [])

  function set<K extends keyof EmailSettings>(key: K, val: EmailSettings[K]) {
    setS(prev => ({ ...prev, [key]: val }))
    setTestRes(null)   // clear test result when config changes
    setSaved(false)
  }

  async function test() {
    setTesting(true); setTestRes(null); setErr(null)
    try {
      const res = await fetch('/api/email/test-settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(s),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.message ?? 'Test failed')
      setTestRes(data)
    } catch (e: any) { setErr(e.message) }
    finally { setTesting(false) }
  }

  async function save() {
    setSaving(true); setErr(null)
    try {
      const res = await fetch('/api/email/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(s),
      })
      if (!res.ok) throw new Error((await res.json()).message ?? 'Save failed')
      setSaved(true)
    } catch (e: any) { setErr(e.message) }
    finally { setSaving(false) }
  }

  // Save is allowed once tests pass (or if nothing was configured to test)
  const testPassed = testRes
    ? (!testRes.imap.tested || testRes.imap.success) && (!testRes.smtp.tested || testRes.smtp.success)
    : false
  const nothingToTest = !s.imapEnabled && !s.outboundSmtpHost

  if (!loaded) return <Box sx={{ p: 3 }}><CircularProgress size={24} sx={{ color: '#0D9394' }} /></Box>

  return (
    <Box sx={{ p: 3, maxWidth: 640, display: 'flex', flexDirection: 'column', gap: 3 }}>

      {err && <Alert severity='error' onClose={() => setErr(null)}>{err}</Alert>}

      {/* ── Inbound: IMAP polling — enable toggle sits above the card ── */}
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box sx={{ width: 32, height: 32, borderRadius: 1.5, bgcolor: '#E8F7F7', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <i className='ri-mail-download-line' style={{ color: '#0D9394' }} />
          </Box>
          <Box>
            <Typography variant='subtitle1' sx={{ fontWeight: 700 }}>Inbound — IMAP</Typography>
            <Typography variant='caption' color='text.secondary'>
              Poll this mailbox and auto-import messages. Starts polling immediately when saved with credentials.
            </Typography>
          </Box>
        </Box>
        <FormControlLabel
          control={<Switch checked={s.imapEnabled} onChange={e => set('imapEnabled', e.target.checked)} />}
          label={<Typography variant='body2' sx={{ fontWeight: 600 }}>{s.imapEnabled ? 'Enabled' : 'Disabled'}</Typography>}
          labelPlacement='start'
        />
      </Box>

      <Card>
        <CardContent>

          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <Box sx={{ display: 'flex', gap: 2 }}>
              <TextField label='IMAP Host' size='small' value={s.imapHost ?? ''} onChange={e => set('imapHost', e.target.value)} sx={{ flex: 3 }} placeholder='mail.example.com' />
              <TextField label='Port' size='small' type='number' value={s.imapPort} onChange={e => set('imapPort', parseInt(e.target.value) || 993)} sx={{ flex: 1 }} />
            </Box>
            <Box sx={{ display: 'flex', gap: 2 }}>
              <TextField label='Username / Email' size='small' value={s.imapUser ?? ''} onChange={e => set('imapUser', e.target.value)} sx={{ flex: 1 }} placeholder='inbox@gpslaw.com' />
              <TextField label='Password / App Password' size='small' type='password' value={s.imapPassword ?? ''} onChange={e => set('imapPassword', e.target.value)} sx={{ flex: 1 }} />
            </Box>
            <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
            <TextField label='Folder to watch' size='small' value={s.imapFolder} onChange={e => set('imapFolder', e.target.value)} sx={{ flex: 1 }} placeholder='INBOX' />
            <TextField label='Poll every (seconds)' size='small' type='number' value={s.imapPollIntervalSeconds} onChange={e => set('imapPollIntervalSeconds', parseInt(e.target.value) || 60)} sx={{ flex: 1 }} />
            <FormControlLabel
              control={<Switch checked={s.imapSsl} onChange={e => set('imapSsl', e.target.checked)} size='small' />}
              label={<Typography variant='body2'>SSL / TLS</Typography>}
              sx={{ flexShrink: 0 }}
            />
          </Box>
        </Box>
        </CardContent>
      </Card>

      {/* ── Outbound SMTP ── */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Box sx={{ width: 32, height: 32, borderRadius: 1.5, bgcolor: '#F0EEFF', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <i className='ri-mail-send-line' style={{ color: '#7C6AF7' }} />
        </Box>
        <Box>
          <Typography variant='subtitle1' sx={{ fontWeight: 700 }}>Outbound — SMTP Relay</Typography>
          <Typography variant='caption' color='text.secondary'>
            Used when the system sends emails. Leave blank to disable outbound sending.
          </Typography>
        </Box>
      </Box>

      <Card>
        <CardContent>

          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <Box sx={{ display: 'flex', gap: 2 }}>
              <TextField label='SMTP Host' size='small' value={s.outboundSmtpHost ?? ''} onChange={e => set('outboundSmtpHost', e.target.value)} sx={{ flex: 3 }} placeholder='smtp.office365.com' />
              <TextField label='Port' size='small' type='number' value={s.outboundSmtpPort} onChange={e => set('outboundSmtpPort', parseInt(e.target.value) || 587)} sx={{ flex: 1 }} />
            </Box>
            <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
              <TextField label='Username' size='small' value={s.outboundSmtpUser ?? ''} onChange={e => set('outboundSmtpUser', e.target.value)} sx={{ flex: 1 }} />
              <TextField label='Password' size='small' type='password' value={s.outboundSmtpPassword ?? ''} onChange={e => set('outboundSmtpPassword', e.target.value)} sx={{ flex: 1 }} />
              <FormControlLabel
                control={<Switch checked={s.outboundSmtpSsl} onChange={e => set('outboundSmtpSsl', e.target.checked)} size='small' />}
                label={<Typography variant='body2'>SSL</Typography>}
                sx={{ flexShrink: 0 }}
              />
            </Box>
          </Box>
        </CardContent>
      </Card>

      {/* ── Sender identity ── */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Box sx={{ width: 32, height: 32, borderRadius: 1.5, bgcolor: '#FFF4CC', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <i className='ri-id-card-line' style={{ color: '#CC8800' }} />
        </Box>
        <Box>
          <Typography variant='subtitle1' sx={{ fontWeight: 700 }}>Sender Identity</Typography>
          <Typography variant='caption' color='text.secondary'>
            Default From address and name for system-generated emails. Attorneys can override per account.
          </Typography>
        </Box>
      </Box>

      <Card>
        <CardContent>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField label='From Address' size='small' value={s.outboundFromAddress ?? ''} onChange={e => set('outboundFromAddress', e.target.value)} sx={{ flex: 2 }} placeholder='legal@gpslaw.com' />
            <TextField label='Display Name' size='small' value={s.outboundFromName ?? ''} onChange={e => set('outboundFromName', e.target.value)} sx={{ flex: 2 }} placeholder='GPS Legal' />
          </Box>
        </CardContent>
      </Card>

      {/* Test results panel */}
      {testRes && (
        <Card sx={{ border: '1px solid', borderColor: testPassed ? '#71DD37' : '#FF3E1D' }}>
          <CardContent sx={{ py: 1.5, '&:last-child': { pb: 1.5 } }}>
            <Typography variant='body2' sx={{ fontWeight: 700, mb: 1 }}>Test Results</Typography>
            {testRes.imap.tested && (
              <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 0.75 }}>
                <i
                  className={testRes.imap.success ? 'ri-checkbox-circle-fill' : 'ri-close-circle-fill'}
                  style={{ color: testRes.imap.success ? '#71DD37' : '#FF3E1D', fontSize: '1.1rem', marginTop: 1, flexShrink: 0 }}
                />
                <Box>
                  <Typography variant='body2' sx={{ fontWeight: 600 }}>IMAP</Typography>
                  <Typography variant='caption' color='text.secondary'>{testRes.imap.message}</Typography>
                </Box>
              </Box>
            )}
            {testRes.smtp.tested && (
              <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
                <i
                  className={testRes.smtp.success ? 'ri-checkbox-circle-fill' : 'ri-close-circle-fill'}
                  style={{ color: testRes.smtp.success ? '#71DD37' : '#FF3E1D', fontSize: '1.1rem', marginTop: 1, flexShrink: 0 }}
                />
                <Box>
                  <Typography variant='body2' sx={{ fontWeight: 600 }}>Outbound SMTP</Typography>
                  <Typography variant='caption' color='text.secondary'>{testRes.smtp.message}</Typography>
                </Box>
              </Box>
            )}
            {!testRes.imap.tested && !testRes.smtp.tested && (
              <Typography variant='body2' color='text.secondary'>
                Nothing to test — enable IMAP or configure outbound SMTP first.
              </Typography>
            )}
          </CardContent>
        </Card>
      )}

      {err && <Alert severity='error' onClose={() => setErr(null)}>{err}</Alert>}

      {/* Actions */}
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 1.5, alignItems: 'center' }}>
        {saved && <Chip label='Saved' size='small' sx={{ bgcolor: '#EEFBE5', color: '#52B630', fontWeight: 600 }} />}
        <Button
          variant='outlined' onClick={test} disabled={testing}
          startIcon={<i className={testing ? 'ri-loader-4-line' : 'ri-wifi-line'} />}
          sx={{ borderColor: '#0D9394', color: '#0D9394' }}
        >
          {testing ? 'Testing…' : 'Test Settings'}
        </Button>
        <Tooltip title={nothingToTest ? '' : testPassed ? '' : 'Run Test Settings first'}>
          <span>
            <Button
              variant='contained' onClick={save}
              disabled={saving || (!nothingToTest && !testPassed)}
              startIcon={<i className={saving ? 'ri-loader-4-line' : 'ri-save-line'} />}
              sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
            >
              {saving ? 'Saving…' : 'Save Settings'}
            </Button>
          </span>
        </Tooltip>
      </Box>
    </Box>
  )
}


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

export default function EmailInboxView() {
  const [tab,       setTab]       = useState(0)   // 0=All, 1=Pending, 2=Inbound, 3=Outbound, 4=Settings
  const [emails,    setEmails]    = useState<Email[]>([])
  const [total,     setTotal]     = useState(0)
  const [pending,   setPending]   = useState(0)
  const [loading,   setLoading]   = useState(true)
  const [selected,  setSelected]  = useState<Email | null>(null)
  const [assocOpen, setAssocOpen] = useState(false)
  const [search,    setSearch]    = useState('')

  const TAB_FILTERS = [
    {},
    { associationStatus: 'pending_review' },
    { direction: 'inbound' },
    { direction: 'outbound' },
  ]

  const load = useCallback(async () => {
    setLoading(true)
    const f = TAB_FILTERS[tab] ?? {}
    const qs = new URLSearchParams(f as any).toString()
    try {
      const [emailRes, countRes] = await Promise.all([
        fetch(`/api/email${qs ? `?${qs}` : ''}`).then(r => r.json()),
        fetch('/api/email/pending-count').then(r => r.json()),
      ])
      setEmails(emailRes.items ?? [])
      setTotal(emailRes.total ?? 0)
      setPending(typeof countRes === 'number' ? countRes : 0)
    } finally {
      setLoading(false)
    }
  }, [tab])

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

  async function handleAssocConfirm(clientFolderId: string, matterId?: string) {
    if (!selected) return
    await fetch(`/api/email/${selected._id}?action=associate`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ clientFolderId, matterId, confirmedBy: 'attorney' }),
    })
    setAssocOpen(false)
    load()
  }

  async function handleMarkRead() {
    if (!selected) return
    await fetch(`/api/email/${selected._id}?action=read`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: '{}' })
    setEmails(e => e.map(x => x._id === selected._id ? { ...x, isRead: true } : x))
  }

  const filtered = search
    ? emails.filter(e =>
        e.subject.toLowerCase().includes(search.toLowerCase()) ||
        e.from.address.toLowerCase().includes(search.toLowerCase()) ||
        (e.from.name ?? '').toLowerCase().includes(search.toLowerCase()),
      )
    : emails

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', gap: 0 }}>
      {/* Page header */}
      <Box sx={{ px: 3, pt: 3, pb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Box>
            <Typography variant='h5' sx={{ fontWeight: 700 }}>Communications</Typography>
            <Typography variant='body2' color='text.secondary'>All inbound and outbound email across all matters</Typography>
          </Box>
          <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
            {pending > 0 && (
              <Chip
                label={`${pending} pending routing`}
                size='small'
                sx={{ bgcolor: '#FFF4CC', color: '#CC8800', fontWeight: 700 }}
                icon={<i className='ri-alert-line' style={{ fontSize: '0.85rem', color: '#CC8800' }} />}
              />
            )}
            <Button
              size='small' variant='outlined' onClick={load}
              startIcon={<i className='ri-refresh-line' />}
              sx={{ borderColor: 'divider' }}
            >
              Refresh
            </Button>
          </Box>
        </Box>
      </Box>

      {/* Tabs */}
      <Box sx={{ px: 3, borderBottom: '1px solid', borderColor: 'divider' }}>
        <Tabs value={tab} onChange={(_, v) => { setTab(v); setSelected(null) }} sx={{ minHeight: 36 }}>
          <Tab label={`All (${total})`} sx={{ minHeight: 36, fontSize: '0.875rem' }} />
          <Tab
            label={
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
                Needs Routing
                {pending > 0 && (
                  <Chip label={pending} size='small'
                    sx={{ bgcolor: '#FFF4CC', color: '#CC8800', height: 18, fontSize: '0.7rem', fontWeight: 700, minWidth: 24 }} />
                )}
              </Box>
            }
            sx={{ minHeight: 36, fontSize: '0.875rem' }}
          />
          <Tab label='Inbound' sx={{ minHeight: 36, fontSize: '0.875rem' }} />
          <Tab label='Outbound' sx={{ minHeight: 36, fontSize: '0.875rem' }} />
          <Tab label='Email Setup' sx={{ minHeight: 36, fontSize: '0.875rem' }} />
        </Tabs>
      </Box>

      {tab === 4 ? (
        <Box sx={{ flex: 1, overflow: 'auto' }}>
          <ServerSettings />
        </Box>
      ) : (
        <Box sx={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
          {/* Email list */}
          <Box sx={{ width: 380, flexShrink: 0, borderRight: '1px solid', borderColor: 'divider', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            <Box sx={{ p: 1.5, borderBottom: '1px solid', borderColor: 'divider' }}>
              <TextField
                size='small' fullWidth placeholder='Search emails…'
                value={search} onChange={e => setSearch(e.target.value)}
                InputProps={{ startAdornment: <i className='ri-search-line' style={{ marginRight: 6, color: '#888' }} /> }}
              />
            </Box>

            <Box sx={{ flex: 1, overflow: 'auto' }}>
              {loading ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', pt: 4 }}>
                  <CircularProgress size={28} sx={{ color: '#0D9394' }} />
                </Box>
              ) : filtered.length === 0 ? (
                <Box sx={{ p: 3, textAlign: 'center' }}>
                  <Typography variant='body2' color='text.disabled'>No emails</Typography>
                </Box>
              ) : (
                filtered.map(e => (
                  <EmailRow
                    key={e._id}
                    email={e}
                    selected={selected?._id === e._id}
                    onClick={() => setSelected(e)}
                  />
                ))
              )}
            </Box>
          </Box>

          {/* Detail panel */}
          <Box sx={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
            {selected ? (
              <EmailDetail
                email={selected}
                onAssociate={() => setAssocOpen(true)}
                onMarkRead={handleMarkRead}
              />
            ) : (
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
                <Box sx={{ textAlign: 'center', color: 'text.disabled' }}>
                  <i className='ri-mail-open-line' style={{ fontSize: '3rem', display: 'block', marginBottom: 8 }} />
                  <Typography variant='body2'>Select an email to read</Typography>
                </Box>
              </Box>
            )}
          </Box>
        </Box>
      )}

      {assocOpen && selected && (
        <AssociateDialog
          email={selected}
          onConfirm={handleAssocConfirm}
          onClose={() => setAssocOpen(false)}
        />
      )}
    </Box>
  )
}
