import { useMemo, useState } from 'react';

import { MarkdownViewer } from '@renderer/components/chat/viewers/MarkdownViewer';
import { AttachmentDisplay } from '@renderer/components/team/attachments/AttachmentDisplay';
import { MemberBadge } from '@renderer/components/team/MemberBadge';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/components/ui/tooltip';
import {
  CARD_BG,
  CARD_BORDER_STYLE,
  CARD_ICON_MUTED,
  CARD_TEXT_LIGHT,
} from '@renderer/constants/cssVariables';
import { getTeamColorSet } from '@renderer/constants/teamColors';
import {
  getMessageTypeLabel,
  getStructuredMessageSummary,
  parseMessageReply,
  parseStructuredAgentMessage,
} from '@renderer/utils/agentMessageFormatting';
import { formatAgentRole } from '@renderer/utils/formatAgentRole';
import { stripAgentBlocks } from '@shared/constants/agentBlocks';
import { extractMarkdownPlainText } from '@shared/utils/markdownTextSearch';
import { isRateLimitMessage } from '@shared/utils/rateLimitDetector';
import { AlertTriangle, ChevronRight, ListPlus, Reply } from 'lucide-react';

import { ReplyQuoteBlock } from './ReplyQuoteBlock';

import type { TeamColorSet } from '@renderer/constants/teamColors';
import type { InboxMessage } from '@shared/types';

type StructuredMessage = Record<string, unknown>;

interface ActivityItemProps {
  message: InboxMessage;
  teamName: string;
  memberRole?: string;
  memberColor?: string;
  recipientColor?: string;
  /** When true, show a blue unread dot. */
  isUnread?: boolean;
  onMemberNameClick?: (memberName: string) => void;
  onCreateTask?: (subject: string, description: string) => void;
  onReply?: (message: InboxMessage) => void;
  /** Called when a task ID link (e.g. #10) is clicked in message text. */
  onTaskIdClick?: (taskId: string) => void;
}

function getStringField(obj: StructuredMessage, key: string): string | null {
  const value = obj[key];
  return typeof value === 'string' && value.trim() !== '' ? value : null;
}

function getNoiseLabel(parsed: StructuredMessage): string | null {
  const type = getStringField(parsed, 'type');

  if (type === 'idle_notification') {
    const reason = getStringField(parsed, 'idleReason');
    return reason ? `Idle (${reason})` : 'Idle';
  }

  if (type === 'shutdown_response') {
    return parsed.approve === true ? 'Shut down' : 'Rejected shutdown';
  }

  if (type === 'shutdown_request') {
    return 'Shutdown requested';
  }

  if (type === 'shutdown_approved' || type === 'teammate_terminated') {
    return type === 'shutdown_approved' ? 'Shutdown confirmed' : 'Terminated';
  }

  if (type === 'task_completed') {
    const rawTaskId = parsed.taskId;
    const taskId =
      typeof rawTaskId === 'string' || typeof rawTaskId === 'number' ? rawTaskId : null;
    return taskId !== null ? `Completed task #${taskId}` : 'Completed a task';
  }

  return null;
}

// ---------------------------------------------------------------------------
// Compact noise row (idle, shutdown, terminated) — minimal dot + name + label
// ---------------------------------------------------------------------------

const NoiseRow = ({
  name,
  label,
  colors,
}: {
  name: string;
  label: string;
  colors: TeamColorSet;
}): React.JSX.Element => (
  <div className="flex items-center gap-2 px-3 py-1" style={{ opacity: 0.45 }}>
    <span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: colors.border }} />
    <span className="text-[11px]" style={{ color: CARD_ICON_MUTED }}>
      {name}
    </span>
    <span className="text-[11px]" style={{ color: CARD_ICON_MUTED }}>
      {label}
    </span>
  </div>
);

// ---------------------------------------------------------------------------
// Detect system/automated messages that should be collapsed by default.
// These are generated by teamctl.js and contain tool instructions, not
// human-written content, so showing them expanded adds visual noise.
// ---------------------------------------------------------------------------

const SYSTEM_MESSAGE_PATTERNS: { pattern: RegExp; label: string }[] = [
  { pattern: /^New task assigned to you:/, label: 'Task assignment' },
  { pattern: /^Task #\d+\s+approved/, label: 'Task approved' },
  { pattern: /^Task #\d+\s+needs fixes/, label: 'Review changes requested' },
];

function getSystemMessageLabel(text: string): string | null {
  for (const { pattern, label } of SYSTEM_MESSAGE_PATTERNS) {
    if (pattern.test(text)) return label;
  }
  return null;
}

// ---------------------------------------------------------------------------
// Full message card — left colored border, name badge, collapsible content
// ---------------------------------------------------------------------------

/** Convert `#<digits>` in plain text to markdown links with task:// protocol. */
function linkifyTaskIdsInMarkdown(text: string): string {
  return text.replace(/#(\d+)/g, '[#$1](task://$1)');
}

/** Render `#<digits>` in plain text as clickable inline elements. */
function linkifyTaskIds(text: string, onClick: (taskId: string) => void): React.ReactNode[] {
  return text.split(/(#\d+)/g).map((part, i) => {
    const match = /^#(\d+)$/.exec(part);
    if (!match) return <span key={i}>{part}</span>;
    const taskId = match[1];
    return (
      <button
        key={i}
        type="button"
        className="cursor-pointer font-medium text-blue-400 hover:underline"
        onClick={(e) => {
          e.stopPropagation();
          onClick(taskId);
        }}
      >
        {part}
      </button>
    );
  });
}

export const ActivityItem = ({
  message,
  teamName,
  memberRole,
  memberColor,
  recipientColor,
  isUnread,
  onMemberNameClick,
  onCreateTask,
  onReply,
  onTaskIdClick,
}: ActivityItemProps): React.JSX.Element => {
  const colors = getTeamColorSet(memberColor ?? message.color ?? '');
  const formattedRole = formatAgentRole(memberRole);

  const timestamp = Number.isNaN(Date.parse(message.timestamp))
    ? message.timestamp
    : new Date(message.timestamp).toLocaleString();

  const structured = parseStructuredAgentMessage(message.text);
  // Only flag agent messages as rate-limited, not user's own quotes
  const rateLimited = message.from !== 'user' && isRateLimitMessage(message.text);
  // Never collapse rate limit messages as noise — they must be visible
  const noiseLabel = structured && !rateLimited ? getNoiseLabel(structured) : null;

  // System/automated messages start collapsed (but not rate limits)
  const systemLabel = !structured && !rateLimited ? getSystemMessageLabel(message.text) : null;
  const [isExpanded, setIsExpanded] = useState(!systemLabel);

  // Strip agent-only blocks from displayed text + linkify task IDs
  const displayText = useMemo(() => {
    if (structured) return null;
    const stripped = stripAgentBlocks(message.text).trim();
    if (!stripped) return null; // All content was agent-only blocks → show summary instead
    return onTaskIdClick ? linkifyTaskIdsInMarkdown(stripped) : stripped;
  }, [structured, message.text, onTaskIdClick]);

  // Check if this is a reply message
  const parsedReply = useMemo(
    () => (displayText ? parseMessageReply(displayText) : null),
    [displayText]
  );

  const rawSummary =
    message.summary || (structured ? getStructuredMessageSummary(structured) : '') || '';
  const summaryText = useMemo(() => extractMarkdownPlainText(rawSummary), [rawSummary]);

  // Noise messages: minimal inline row
  if (noiseLabel) {
    return <NoiseRow name={message.from} label={noiseLabel} colors={colors} />;
  }

  const messageType =
    structured && typeof structured.type === 'string' ? getMessageTypeLabel(structured.type) : null;
  const autoSummary = structured ? getStructuredMessageSummary(structured) : null;

  const handleCreateTask = (): void => {
    const subject = message.summary || autoSummary || `Task from ${message.from}`;
    const plainText = structured
      ? JSON.stringify(structured, null, 2)
      : stripAgentBlocks(message.text);
    const description = `From: ${message.from}\nAt: ${timestamp}\n\n${plainText}`.slice(0, 2000);
    onCreateTask?.(subject, description);
  };

  const isHeaderClickable = Boolean(systemLabel);

  return (
    <article
      className="group overflow-hidden rounded-md"
      style={{
        backgroundColor: rateLimited ? 'var(--tool-result-error-bg)' : CARD_BG,
        border: rateLimited ? '1px solid var(--tool-result-error-border)' : CARD_BORDER_STYLE,
        borderLeft: rateLimited
          ? '3px solid var(--tool-result-error-text)'
          : `3px solid ${colors.border}`,
      }}
    >
      {/* Header — div with role=button (cannot use <button> due to nested buttons inside) */}
      {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions -- role=button, tabIndex, onKeyDown below; nested buttons prevent using native button */}
      <div
        role={isHeaderClickable ? 'button' : undefined}
        tabIndex={isHeaderClickable ? 0 : undefined}
        className={[
          'flex items-center gap-2 px-3 py-2',
          isHeaderClickable ? 'cursor-pointer select-none' : '',
        ].join(' ')}
        onClick={isHeaderClickable ? () => setIsExpanded((v) => !v) : undefined}
        onKeyDown={
          isHeaderClickable
            ? (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  setIsExpanded((v) => !v);
                }
              }
            : undefined
        }
      >
        {isUnread ? (
          <span className="size-2 shrink-0 rounded-full bg-blue-500" title="Unread" aria-hidden />
        ) : null}
        {/* Chevron for collapsible system messages */}
        {systemLabel ? (
          <ChevronRight
            className="size-3 shrink-0 transition-transform duration-150"
            style={{
              color: CARD_ICON_MUTED,
              transform: isExpanded ? 'rotate(90deg)' : undefined,
            }}
          />
        ) : null}

        {/* Sender avatar + name badge */}
        <MemberBadge
          name={message.from}
          color={memberColor ?? message.color}
          onClick={onMemberNameClick}
        />

        {/* Role */}
        {formattedRole ? (
          <span className="text-[10px]" style={{ color: CARD_ICON_MUTED }}>
            {formattedRole}
          </span>
        ) : null}

        {/* Message type label or system label */}
        {systemLabel ? (
          <span className="text-[10px] uppercase tracking-wide" style={{ color: CARD_ICON_MUTED }}>
            {systemLabel}
          </span>
        ) : messageType ? (
          <span className="text-[10px] uppercase tracking-wide" style={{ color: CARD_ICON_MUTED }}>
            {messageType}
          </span>
        ) : null}

        {/* Lead session marker */}
        {message.source === 'lead_session' ? (
          <span className="text-[10px] uppercase tracking-wide" style={{ color: CARD_ICON_MUTED }}>
            session
          </span>
        ) : message.source === 'lead_process' ? (
          <span className="text-[10px] uppercase tracking-wide" style={{ color: CARD_ICON_MUTED }}>
            live
          </span>
        ) : null}

        {/* Rate limit warning badge */}
        {rateLimited ? (
          <span className="inline-flex items-center gap-1 rounded-full bg-red-500/20 px-1.5 py-0.5 text-[10px] font-medium text-red-400">
            <AlertTriangle size={10} />
            Rate Limited
          </span>
        ) : null}

        {/* Recipient — arrow + avatar + badge */}
        {message.to && message.to !== message.from ? (
          <>
            <span style={{ color: CARD_ICON_MUTED }} className="text-[10px]">
              &rarr;
            </span>
            <MemberBadge
              name={message.to}
              color={recipientColor}
              hideAvatar={message.to === 'user'}
              onClick={onMemberNameClick}
            />
          </>
        ) : null}

        {/* Summary */}
        <span className="flex-1 truncate text-xs" style={{ color: CARD_TEXT_LIGHT }}>
          {onTaskIdClick ? linkifyTaskIds(summaryText, onTaskIdClick) : summaryText}
        </span>

        {/* Timestamp + reply + create task */}
        <div className="flex shrink-0 items-center gap-1.5">
          {onReply && (
            <Tooltip>
              <TooltipTrigger asChild>
                <button
                  type="button"
                  className="rounded p-0.5 opacity-0 transition-opacity hover:bg-[var(--color-surface-raised)] group-hover:opacity-100"
                  style={{ color: CARD_ICON_MUTED }}
                  onClick={(e) => {
                    e.stopPropagation();
                    onReply(message);
                  }}
                >
                  <Reply size={14} />
                </button>
              </TooltipTrigger>
              <TooltipContent side="bottom">Reply to message</TooltipContent>
            </Tooltip>
          )}
          {onCreateTask && (
            <Tooltip>
              <TooltipTrigger asChild>
                <button
                  type="button"
                  className="rounded p-0.5 opacity-0 transition-opacity hover:bg-[var(--color-surface-raised)] group-hover:opacity-100"
                  style={{ color: CARD_ICON_MUTED }}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleCreateTask();
                  }}
                >
                  <ListPlus size={14} />
                </button>
              </TooltipTrigger>
              <TooltipContent side="bottom">Create task from message</TooltipContent>
            </Tooltip>
          )}
          <span className="text-[10px]" style={{ color: CARD_ICON_MUTED }}>
            {timestamp}
          </span>
        </div>
      </div>

      {/* Content — collapsed for system messages, expanded for others */}
      {isExpanded ? (
        <div className="px-3 pb-3">
          {structured ? (
            <div className="space-y-2">
              {autoSummary && autoSummary !== messageType ? (
                <p className="text-xs text-[var(--color-text-secondary)]">{autoSummary}</p>
              ) : null}
              <details className="rounded border border-[var(--color-border)] bg-[var(--color-surface)]">
                <summary className="cursor-pointer px-2 py-1 text-[11px] text-[var(--color-text-muted)]">
                  Raw JSON
                </summary>
                <pre className="overflow-auto px-2 pb-2 text-[11px] leading-relaxed text-[var(--color-text-muted)]">
                  {JSON.stringify(structured, null, 2)}
                </pre>
              </details>
            </div>
          ) : parsedReply ? (
            <ReplyQuoteBlock reply={parsedReply} />
          ) : displayText ? (
            <span
              onClickCapture={
                onTaskIdClick
                  ? (e) => {
                      const link = (e.target as HTMLElement).closest<HTMLAnchorElement>(
                        'a[href^="task://"]'
                      );
                      if (link) {
                        e.preventDefault();
                        e.stopPropagation();
                        const taskId = link.getAttribute('href')?.replace('task://', '');
                        if (taskId) onTaskIdClick(taskId);
                      }
                    }
                  : undefined
              }
            >
              <MarkdownViewer content={displayText} maxHeight="max-h-56" copyable bare />
            </span>
          ) : summaryText ? (
            <p className="text-xs italic" style={{ color: CARD_TEXT_LIGHT }}>
              {summaryText}
            </p>
          ) : null}
          {message.attachments?.length && message.messageId ? (
            <AttachmentDisplay
              teamName={teamName}
              messageId={message.messageId}
              attachments={message.attachments}
            />
          ) : null}
        </div>
      ) : null}
    </article>
  );
};
