import React, { useEffect, useMemo, useState } from "react";
import { motion } from "framer-motion";
import type { ThinkingTimelineEntry } from "../../../types/chatStream";

interface AssistantThinkingSummaryProps {
  label: string;
  timeline?: ThinkingTimelineEntry[];
  isActive?: boolean;
  defaultExpanded?: boolean;
}

const AssistantThinkingSummary: React.FC<AssistantThinkingSummaryProps> = ({
  label,
  timeline = [],
  isActive = false,
  defaultExpanded = false,
}) => {
  const [isExpandedState, setIsExpanded] = useState(defaultExpanded);
  const [dots, setDots] = useState(0);

  useEffect(() => {
    if (!isActive) {
      setDots(0);
      return;
    }
    const id = setInterval(() => setDots((d) => (d + 1) % 4), 400);
    return () => clearInterval(id);
  }, [isActive, label]);

  const visibleTimeline = useMemo(
    () => timeline.filter((entry) => entry.kind !== 'reasoning' || entry.text.trim()),
    [timeline]
  );

  const groupedTimeline = useMemo(() => {
    const groups: Array<
      | { kind: 'tool_group'; id: string; entries: Extract<ThinkingTimelineEntry, { kind: 'tool' }>[] }
      | Exclude<ThinkingTimelineEntry, { kind: 'tool' }>
    > = [];

    for (const entry of visibleTimeline) {
      if (entry.kind === 'tool') {
        const lastGroup = groups[groups.length - 1];
        if (lastGroup && lastGroup.kind === 'tool_group') {
          lastGroup.entries.push(entry);
        } else {
          groups.push({
            kind: 'tool_group',
            id: `tool-group-${entry.id}`,
            entries: [entry],
          });
        }
        continue;
      }
      groups.push(entry);
    }

    return groups;
  }, [visibleTimeline]);

  const renderReasoningBlocks = (text: string) => {
    const blocks = text
      .split(/\n{2,}/)
      .map((block) => block.trim())
      .filter(Boolean);

    return blocks.map((block, index) => {
      const boldHeadingMatch = block.match(/^\*\*(.+?)\*\*$/s);
      const markdownHeadingMatch = block.match(/^#{1,6}\s+(.+)$/);
      if (boldHeadingMatch || markdownHeadingMatch) {
        const headingText = (boldHeadingMatch?.[1] || markdownHeadingMatch?.[1] || '').trim();
        return (
          <div
            key={`${headingText}-${index}`}
            className="text-sm font-semibold leading-6 text-gray-600 dark:text-gray-300"
          >
            {headingText}
          </div>
        );
      }

      return (
        <div
          key={`${block.slice(0, 24)}-${index}`}
          className="whitespace-pre-wrap text-sm leading-6 text-gray-500 dark:text-gray-400"
        >
          {block}
        </div>
      );
    });
  };

  const isCollapsible = !isActive;
  const isExpanded = isActive || isExpandedState;

  return (
    <div className="pb-3">
      <button
        type="button"
        className="flex w-full items-center gap-2 text-left"
        onClick={() => {
          if (!isCollapsible) return;
          setIsExpanded((prev) => !prev);
        }}
      >
        {isActive ? (
          <span className="h-2 w-2 shrink-0 rounded-full bg-gray-500 animate-pulse" aria-hidden="true" />
        ) : (
          <svg
            viewBox="0 0 20 20"
            fill="none"
            aria-hidden="true"
            className={`h-4 w-4 shrink-0 text-gray-400 transition-transform duration-150 ${isExpanded ? 'rotate-90' : ''}`}
          >
            <path d="M7 5l6 5-6 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        )}
        <span
          className={
            isActive
              ? "text-sm sm:text-[0.95rem] font-medium text-gradient-gray"
              : "text-sm sm:text-[0.95rem] font-medium text-gray-500 dark:text-gray-400"
          }
          style={isActive ? undefined : { animation: 'none' }}
        >
          {label}
          {isActive ? '.'.repeat(dots) : ''}
        </span>
      </button>

      {isExpanded && groupedTimeline.length > 0 && (
        <div className="space-y-4 pt-6 pl-6">
          {groupedTimeline.map((entry) => {
            if (entry.kind === 'reasoning') {
              return (
                <motion.div
                  key={entry.id}
                  initial={{ opacity: 0, y: 2 }}
                  animate={{ opacity: 0.82, y: 0 }}
                  transition={{ duration: 0.18, ease: "easeOut" }}
                  className="space-y-2"
                >
                  {renderReasoningBlocks(entry.text)}
                </motion.div>
              );
            }
            if (entry.kind === 'approval') {
              return (
                <motion.div
                  key={entry.id}
                  initial={{ opacity: 0, y: 2 }}
                  animate={{ opacity: 0.9, y: 0 }}
                  transition={{ duration: 0.18, ease: "easeOut" }}
                  className="text-xs rounded-2xl px-3 py-2 bg-amber-100/70 text-amber-900 dark:bg-amber-500/10 dark:text-amber-100"
                >
                  {entry.label}
                </motion.div>
              );
            }
            if (entry.kind === 'tool_group') {
              return (
                <motion.div
                  key={entry.id}
                  initial={{ opacity: 0, y: 2 }}
                  animate={{ opacity: 0.88, y: 0 }}
                  transition={{ duration: 0.18, ease: "easeOut" }}
                  className="flex flex-wrap gap-x-1.5 gap-y-2 pb-1"
                >
                  {entry.entries.map((toolEntry) => (
                    <div
                      key={toolEntry.id}
                      className={`inline-flex rounded-full px-3 py-1.5 text-xs ${
                        toolEntry.state === 'error'
                          ? 'bg-red-100/80 text-red-700 dark:bg-red-500/10 dark:text-red-200'
                          : 'bg-gray-100/75 text-gray-500 dark:bg-gray-700/45 dark:text-gray-400'
                      }`}
                    >
                      {toolEntry.label}
                    </div>
                  ))}
                </motion.div>
              );
            }
            return null;
          })}
        </div>
      )}
    </div>
  );
};

export default React.memo(AssistantThinkingSummary);
