'use client'

import { useState, useEffect, useCallback } from 'react'
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'
import Chip from '@mui/material/Chip'
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
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 Alert from '@mui/material/Alert'
import Tooltip from '@mui/material/Tooltip'
import type { ClientFolder, Matter, Email, UserEmailAccount } from './types'

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

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

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

const DIR_COLOR = {
  inbound:  { bg: '#E8F7F7', color: '#0D5E5F', icon: 'ri-mail-download-line' },
  outbound: { bg: '#F0EEFF', color: '#5947B5', icon: 'ri-mail-send-line' },
}

// ─── Compose dialog ───────────────────────────────────────────────────────────

function ComposeDialog({
  folder,
  matters,
  accounts,
  onSend,
  onClose,
  replyTo,
}: {
  folder: ClientFolder
  matters: Matter[]
  accounts: UserEmailAccount[]
  onSend: () => void
  onClose: () => void
  replyTo?: Email
}) {
  const [to,       setTo]       = useState(replyTo ? addrLabel(replyTo.from) + ' <' + replyTo.from.address + '>' : folder.email ?? '')
  const [from,     setFrom]     = useState(accounts[0]?.emailAddress ?? '')
  const [matterId, setMatterId] = useState(replyTo?.matterId ?? '')
  const [subject,  setSubject]  = useState(replyTo ? `Re: ${replyTo.subject.replace(/^Re: /i, '')}` : '')
  const [body,     setBody]     = useState('')
  const [sending,  setSending]  = useState(false)
  const [err,      setErr]      = useState<string | null>(null)

  // Auto-prefix subject with matter ref
  const matter = matters.find(m => m._id === matterId)
  const subjectRef  = matter ? `[ref: ${matter.matterNumber}]` : `[ref: ${folder.folderNumber}]`
  const fullSubject = subject.startsWith('[ref:') ? subject : `${subjectRef} ${subject}`

  async function send() {
    if (!to || !subject || !from) return
    setSending(true); setErr(null)
    try {
      const res = await fetch('/api/email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          clientFolderId: folder._id,
          matterId:       matterId || undefined,
          to:             [{ address: to.match(/<(.+)>/)?.[1] ?? to, name: to.match(/^(.+)\s*<.+>/)?.[1]?.trim() }],
          from,
          subject:        fullSubject,
          bodyText:       body,
          inReplyTo:      replyTo?.messageId,
        }),
      })
      if (!res.ok) throw new Error((await res.json()).message ?? 'Send failed')
      onSend()
    } catch (e: any) { setErr(e.message) }
    finally { setSending(false) }
  }

  return (
    <Dialog open onClose={onClose} maxWidth='md' fullWidth>
      <DialogTitle>
        {replyTo ? 'Reply' : 'New Email'} — {folder.displayName}
      </DialogTitle>
      <DialogContent>
        {err && <Alert severity='error' sx={{ mb: 2 }}>{err}</Alert>}

        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <TextField
              select label='From (your address)' size='small' value={from}
              onChange={e => setFrom(e.target.value)} sx={{ flex: 1 }}
            >
              {accounts.map(a => (
                <MenuItem key={a._id} value={a.emailAddress}>{a.displayName} &lt;{a.emailAddress}&gt;</MenuItem>
              ))}
            </TextField>
            <TextField
              select label='Matter (optional)' size='small' value={matterId}
              onChange={e => setMatterId(e.target.value)} sx={{ flex: 1 }}
            >
              <MenuItem value=''>— No specific matter —</MenuItem>
              {matters.map(m => (
                <MenuItem key={m._id} value={m._id}>{m.matterNumber} — {m.title}</MenuItem>
              ))}
            </TextField>
          </Box>

          <TextField label='To' size='small' value={to} onChange={e => setTo(e.target.value)} fullWidth />

          <Box>
            <TextField label='Subject' size='small' value={subject} onChange={e => setSubject(e.target.value)} fullWidth />
            <Typography variant='caption' color='text.secondary' sx={{ mt: 0.5, display: 'block' }}>
              Will be sent as: <strong>{fullSubject}</strong>
            </Typography>
          </Box>

          <TextField
            label='Message' multiline rows={8} size='small' fullWidth
            value={body} onChange={e => setBody(e.target.value)}
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button
          variant='contained' onClick={send} disabled={sending || !to || !subject || !from}
          startIcon={<i className={sending ? 'ri-loader-4-line' : 'ri-send-plane-line'} />}
          sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
        >
          {sending ? 'Sending…' : 'Send'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

// ─── Thread row ───────────────────────────────────────────────────────────────

function ThreadRow({
  email,
  selected,
  onClick,
}: {
  email: Email
  selected: boolean
  onClick: () => void
}) {
  const d = DIR_COLOR[email.direction]
  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.selected' },
        display: 'flex', gap: 1.5, alignItems: 'flex-start',
      }}
    >
      <Box sx={{ mt: 0.25, flexShrink: 0, width: 28, height: 28, borderRadius: 1, bgcolor: d.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <i className={d.icon} style={{ fontSize: '0.95rem', color: d.color }} />
      </Box>
      <Box sx={{ flex: 1, minWidth: 0 }}>
        <Box sx={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <Typography variant='body2' sx={{ fontWeight: email.isRead ? 500 : 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {email.direction === 'inbound' ? addrLabel(email.from) : 'You → ' + email.to.map(addrLabel).join(', ')}
          </Typography>
          <Typography variant='caption' color='text.disabled' sx={{ flexShrink: 0, ml: 1 }}>
            {formatDate(email.receivedAt)}
          </Typography>
        </Box>
        <Typography variant='body2' color='text.secondary' sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', mt: 0.25 }}>
          {email.subject}
        </Typography>
        {email.bodyText && (
          <Typography variant='caption' color='text.disabled' sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'block' }}>
            {email.bodyText.slice(0, 100)}
          </Typography>
        )}
      </Box>
    </Box>
  )
}

// ─── Thread detail ────────────────────────────────────────────────────────────

function ThreadDetail({
  threadId,
  onReply,
}: {
  threadId: string
  onReply: (email: Email) => void
}) {
  const [thread, setThread] = useState<Email[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setLoading(true)
    fetch(`/api/email/thread/${encodeURIComponent(threadId)}`)
      .then(r => r.json())
      .then(data => setThread(Array.isArray(data) ? data : []))
      .finally(() => setLoading(false))
  }, [threadId])

  if (loading) return <Box sx={{ display: 'flex', justifyContent: 'center', pt: 4 }}><CircularProgress size={24} sx={{ color: '#0D9394' }} /></Box>

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'auto' }}>
      {thread.map((email, i) => {
        const d = DIR_COLOR[email.direction]
        return (
          <Box key={email._id} sx={{ borderBottom: i < thread.length - 1 ? '1px solid' : 'none', borderColor: 'divider', p: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Chip
                  label={email.direction === 'inbound' ? 'Inbound' : 'Outbound'}
                  size='small'
                  sx={{ bgcolor: d.bg, color: d.color, fontWeight: 600, height: 20 }}
                  icon={<i className={d.icon} style={{ fontSize: '0.75rem', color: d.color }} />}
                />
                <Typography variant='body2' sx={{ fontWeight: 600 }}>
                  {addrLabel(email.from)}
                </Typography>
                <Typography variant='caption' color='text.disabled'>
                  → {email.to.map(addrLabel).join(', ')}
                </Typography>
              </Box>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Typography variant='caption' color='text.disabled'>
                  {new Date(email.receivedAt).toLocaleString()}
                </Typography>
                <Tooltip title='Reply'>
                  <Button
                    size='small' variant='text'
                    onClick={() => onReply(email)}
                    startIcon={<i className='ri-reply-line' />}
                    sx={{ fontSize: '0.75rem', minWidth: 0 }}
                  >
                    Reply
                  </Button>
                </Tooltip>
              </Box>
            </Box>

            {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>
        )
      })}
    </Box>
  )
}

// ─── Main tab ─────────────────────────────────────────────────────────────────

export default function CommunicationsTab({ folder }: { folder: ClientFolder }) {
  const [emails,    setEmails]    = useState<Email[]>([])
  const [matters,   setMatters]   = useState<Matter[]>([])
  const [accounts,  setAccounts]  = useState<UserEmailAccount[]>([])
  const [loading,   setLoading]   = useState(true)
  const [selected,  setSelected]  = useState<Email | null>(null)
  const [filter,    setFilter]    = useState<'all' | 'inbound' | 'outbound'>('all')
  const [matterFilter, setMatterFilter] = useState('')
  const [composing, setComposing] = useState(false)
  const [replyTo,   setReplyTo]   = useState<Email | undefined>()

  const load = useCallback(async () => {
    setLoading(true)
    const qs = new URLSearchParams({ clientFolderId: folder._id })
    if (filter !== 'all') qs.set('direction', filter)
    if (matterFilter) qs.set('matterId', matterFilter)
    try {
      const [emailRes, matterRes, accountRes] = await Promise.all([
        fetch(`/api/email?${qs}`).then(r => r.json()),
        fetch(`/api/matters?clientFolderId=${folder._id}`).then(r => r.json()),
        fetch('/api/email/accounts').then(r => r.json()),
      ])
      setEmails(emailRes.items ?? [])
      setMatters(Array.isArray(matterRes) ? matterRes : (matterRes.items ?? []))
      setAccounts(Array.isArray(accountRes) ? accountRes : [])
    } finally {
      setLoading(false)
    }
  }, [folder._id, filter, matterFilter])

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

  function openReply(email: Email) {
    setReplyTo(email)
    setComposing(true)
  }

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: 640, border: '1px solid', borderColor: 'divider', borderRadius: 2, overflow: 'hidden' }}>
      {/* Toolbar */}
      <Box sx={{ px: 2, py: 1.5, borderBottom: '1px solid', borderColor: 'divider', display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap', bgcolor: 'background.paper' }}>
        <Typography variant='subtitle1' sx={{ fontWeight: 700, mr: 1 }}>Communications</Typography>

        <TextField
          select size='small' value={filter} onChange={e => setFilter(e.target.value as any)}
          sx={{ width: 130 }}
        >
          <MenuItem value='all'>All</MenuItem>
          <MenuItem value='inbound'>Inbound</MenuItem>
          <MenuItem value='outbound'>Outbound</MenuItem>
        </TextField>

        {matters.length > 0 && (
          <TextField
            select size='small' value={matterFilter} onChange={e => setMatterFilter(e.target.value)}
            sx={{ width: 220 }}
            label='Matter'
          >
            <MenuItem value=''>All Matters</MenuItem>
            {matters.map(m => (
              <MenuItem key={m._id} value={m._id}>{m.matterNumber} — {m.title}</MenuItem>
            ))}
          </TextField>
        )}

        <Box sx={{ ml: 'auto' }}>
          <Button
            variant='contained' size='small'
            startIcon={<i className='ri-pencil-line' />}
            onClick={() => { setReplyTo(undefined); setComposing(true) }}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
          >
            Compose
          </Button>
        </Box>
      </Box>

      {/* Split pane */}
      <Box sx={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* List */}
        <Box sx={{ width: 320, flexShrink: 0, borderRight: '1px solid', borderColor: 'divider', overflow: 'auto' }}>
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', pt: 4 }}>
              <CircularProgress size={24} sx={{ color: '#0D9394' }} />
            </Box>
          ) : emails.length === 0 ? (
            <Box sx={{ p: 3, textAlign: 'center' }}>
              <i className='ri-mail-line' style={{ fontSize: '2rem', color: '#ccc', display: 'block' }} />
              <Typography variant='body2' color='text.disabled' sx={{ mt: 1 }}>
                No emails yet for this client
              </Typography>
            </Box>
          ) : (
            emails.map(e => (
              <ThreadRow key={e._id} email={e} selected={selected?._id === e._id} onClick={() => setSelected(e)} />
            ))
          )}
        </Box>

        {/* Thread detail */}
        <Box sx={{ flex: 1, overflow: 'hidden' }}>
          {selected ? (
            <ThreadDetail
              threadId={selected.threadId}
              onReply={openReply}
            />
          ) : (
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
              <Box sx={{ textAlign: 'center', color: 'text.disabled' }}>
                <i className='ri-chat-1-line' style={{ fontSize: '2.5rem', display: 'block', marginBottom: 8 }} />
                <Typography variant='body2'>Select an email to read the thread</Typography>
              </Box>
            </Box>
          )}
        </Box>
      </Box>

      {composing && (
        <ComposeDialog
          folder={folder}
          matters={matters}
          accounts={accounts}
          replyTo={replyTo}
          onSend={() => { setComposing(false); load() }}
          onClose={() => setComposing(false)}
        />
      )}
    </Box>
  )
}
