'use client'

import { useState } from 'react'
import {
  deleteComment,
  postComment,
  reopenComment,
  resolveComment,
} from '@/app/actions/comments'

export type CommentItem = {
  id: string
  body: string
  author_name: string
  author_id: string | null
  created_at: string
  resolved_at: string | null
  resolved_by_name: string | null
}

type Props = {
  unresolvedCount: number
  comments: CommentItem[]
  currentUserId: string | null
}

export function CommentsBell({ unresolvedCount, comments, currentUserId }: Props) {
  const [open, setOpen] = useState(false)
  const [showResolved, setShowResolved] = useState(false)

  const visible = comments.filter((c) =>
    showResolved ? !!c.resolved_at : !c.resolved_at,
  )

  return (
    <div style={{ position: 'relative' }}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="nav-signout"
        title="Comments"
        style={{ position: 'relative', padding: '0.3rem 0.65rem' }}
      >
        💬
        {unresolvedCount > 0 && (
          <span
            style={{
              position: 'absolute',
              top: '-4px',
              right: '-4px',
              background: '#b91c1c',
              color: '#fff',
              borderRadius: '999px',
              fontSize: '0.65rem',
              padding: '0.05rem 0.3rem',
              fontWeight: 600,
              minWidth: '1rem',
              textAlign: 'center',
            }}
          >
            {unresolvedCount}
          </span>
        )}
      </button>

      {open && (
        <div
          style={{
            position: 'absolute',
            top: '100%',
            right: 0,
            marginTop: '0.4rem',
            width: '380px',
            maxHeight: '70vh',
            background: '#fff',
            color: '#1a1a1a',
            border: '1px solid #d0d0d0',
            borderRadius: '8px',
            boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
            zIndex: 30,
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
          }}
        >
          <div
            style={{
              padding: '0.6rem 0.85rem',
              borderBottom: '1px solid #eee',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <strong style={{ fontSize: '0.9rem' }}>Comments</strong>
            <div className="flex-row" style={{ gap: '0.3rem' }}>
              <button
                type="button"
                onClick={() => setShowResolved(false)}
                className={showResolved ? 'secondary' : ''}
                style={{ padding: '0.2rem 0.55rem', fontSize: '0.8rem' }}
              >
                Open
              </button>
              <button
                type="button"
                onClick={() => setShowResolved(true)}
                className={showResolved ? '' : 'secondary'}
                style={{ padding: '0.2rem 0.55rem', fontSize: '0.8rem' }}
              >
                Resolved
              </button>
            </div>
          </div>

          <div
            style={{
              flex: 1,
              overflowY: 'auto',
              padding: '0.5rem 0.85rem',
            }}
          >
            {visible.length === 0 ? (
              <p className="muted" style={{ fontSize: '0.85em', margin: '0.75rem 0' }}>
                {showResolved ? 'No resolved comments.' : 'No open comments.'}
              </p>
            ) : (
              <ul
                style={{
                  listStyle: 'none',
                  padding: 0,
                  margin: 0,
                  display: 'flex',
                  flexDirection: 'column',
                  gap: '0.5rem',
                }}
              >
                {visible.map((c) => (
                  <CommentItemView
                    key={c.id}
                    comment={c}
                    currentUserId={currentUserId}
                  />
                ))}
              </ul>
            )}
          </div>

          <form
            action={postComment}
            style={{
              borderTop: '1px solid #eee',
              padding: '0.6rem 0.85rem',
              display: 'flex',
              flexDirection: 'column',
              gap: '0.4rem',
            }}
          >
            <textarea
              name="body"
              placeholder="Leave a note for the team… (e.g. @Adi please rename the project in Clockify)"
              rows={2}
              required
              style={{
                width: '100%',
                padding: '0.4rem 0.55rem',
                fontSize: '0.85rem',
                fontFamily: 'inherit',
                border: '1px solid #d0d0d0',
                borderRadius: '6px',
                resize: 'vertical',
              }}
            />
            <button type="submit" style={{ alignSelf: 'flex-end', padding: '0.35rem 0.85rem' }}>
              Post
            </button>
          </form>
        </div>
      )}
    </div>
  )
}

function CommentItemView({
  comment,
  currentUserId,
}: {
  comment: CommentItem
  currentUserId: string | null
}) {
  const isResolved = !!comment.resolved_at
  const canDelete = comment.author_id === currentUserId

  return (
    <li
      style={{
        background: isResolved ? '#f7f7f7' : '#fff',
        border: '1px solid #e5e5e5',
        borderRadius: '6px',
        padding: '0.5rem 0.6rem',
        opacity: isResolved ? 0.7 : 1,
      }}
    >
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          gap: '0.5rem',
          fontSize: '0.78rem',
          marginBottom: '0.25rem',
        }}
      >
        <strong>{comment.author_name}</strong>
        <span className="muted" title={new Date(comment.created_at).toLocaleString()}>
          {timeAgo(comment.created_at)}
        </span>
      </div>
      <div
        style={{
          fontSize: '0.9em',
          whiteSpace: 'pre-wrap',
          marginBottom: '0.4rem',
        }}
      >
        {renderWithMentions(comment.body)}
      </div>
      <div
        className="flex-row"
        style={{ gap: '0.5rem', fontSize: '0.75rem' }}
      >
        {isResolved ? (
          <>
            <span className="muted">
              Resolved by {comment.resolved_by_name ?? 'someone'}
            </span>
            <form action={reopenComment} style={{ display: 'inline' }}>
              <input type="hidden" name="id" value={comment.id} />
              <button type="submit" className="link-button">
                Reopen
              </button>
            </form>
          </>
        ) : (
          <form action={resolveComment} style={{ display: 'inline' }}>
            <input type="hidden" name="id" value={comment.id} />
            <button type="submit" className="link-button">
              Resolve
            </button>
          </form>
        )}
        {canDelete && (
          <form
            action={deleteComment}
            style={{ display: 'inline' }}
            onSubmit={(e) => {
              if (!window.confirm('Delete this comment?')) e.preventDefault()
            }}
          >
            <input type="hidden" name="id" value={comment.id} />
            <button
              type="submit"
              className="link-button"
              style={{ color: '#b91c1c' }}
            >
              Delete
            </button>
          </form>
        )}
      </div>
    </li>
  )
}

function timeAgo(iso: string): string {
  const then = new Date(iso).getTime()
  const now = Date.now()
  const s = Math.round((now - then) / 1000)
  if (s < 60) return `${s}s ago`
  if (s < 3600) return `${Math.round(s / 60)}m ago`
  if (s < 86400) return `${Math.round(s / 3600)}h ago`
  return `${Math.round(s / 86400)}d ago`
}

/** Highlight @mentions visually. Doesn't change behaviour. */
function renderWithMentions(body: string): React.ReactNode[] {
  const parts: React.ReactNode[] = []
  const re = /@\w+/g
  let last = 0
  let m: RegExpExecArray | null
  while ((m = re.exec(body)) !== null) {
    if (m.index > last) parts.push(body.slice(last, m.index))
    parts.push(
      <span
        key={`${m.index}-${m[0]}`}
        style={{ background: '#fef3c7', color: '#78350f', padding: '0 2px', borderRadius: '3px' }}
      >
        {m[0]}
      </span>,
    )
    last = m.index + m[0].length
  }
  if (last < body.length) parts.push(body.slice(last))
  return parts
}
