import React, { useEffect, useRef, useState } from 'react';
import {
  LuCheck,
  LuChevronDown,
  LuChevronRight,
  LuLoader2,
} from 'react-icons/lu';

import type { ICopilotStep } from '../../service/copilot/copilot.interface';

import { cn } from './cn';

/**
 * Collapsible tool/thinking tree for one assistant turn. Each step shows live
 * state: a spinning loader with a pulsing label while running, then a green
 * check once done. The tree stays open while Reco works and folds itself to a
 * one-line summary when the turn completes (the merchant can re-expand it).
 *
 * @param props - Component props.
 * @param props.steps - Steps for this turn, in order.
 * @return The tree, or null when there are no steps.
 */
export function CopilotSteps({
  steps,
}: {
  steps: ICopilotStep[];
}): React.ReactElement | null {
  const isWorking: boolean = steps.some(step => step.state === 'running');
  const [isExpanded, setIsExpanded] = useState<boolean>(isWorking);
  // Tracks the working state across renders so we only auto-collapse on the
  // moment the turn finishes, never against a manual re-expand afterwards.
  const wasWorkingRef = useRef<boolean>(isWorking);

  useEffect(() => {
    if (wasWorkingRef.current && !isWorking) setIsExpanded(false);
    if (!wasWorkingRef.current && isWorking) setIsExpanded(true);
    wasWorkingRef.current = isWorking;
  }, [isWorking]);

  if (steps.length === 0) return null;

  return (
    <div className="mb-2">
      <button
        type="button"
        onClick={() => setIsExpanded(value => !value)}
        className="group flex items-center gap-1.5 text-xs font-medium text-gray-500 transition hover:text-gray-700"
      >
        {isWorking ? (
          <LuLoader2 className="h-3.5 w-3.5 animate-spin text-[#b7007c]" />
        ) : (
          <span className="flex h-3.5 w-3.5 items-center justify-center rounded-full bg-emerald-100">
            <LuCheck className="h-2.5 w-2.5 text-emerald-600" />
          </span>
        )}
        <span className={cn(isWorking && 'animate-pulse text-gray-700')}>
          {isWorking ? 'Thinking...' : 'Thought it through'}
        </span>
        {!isWorking && (
          <span className="text-[10px] text-gray-400 transition group-hover:text-gray-600">
            {steps.length} step{steps.length > 1 ? 's' : ''}
          </span>
        )}
        {isExpanded ? (
          <LuChevronDown className="h-3.5 w-3.5" />
        ) : (
          <LuChevronRight className="h-3.5 w-3.5" />
        )}
      </button>

      {isExpanded && (
        <div className="relative mt-2 ml-[6px] flex flex-col gap-2.5 pl-4">
          {/* Connector line with a soft brand fade, instead of a flat border. */}
          <span
            aria-hidden
            className="absolute bottom-1 left-0 top-1 w-px bg-gradient-to-b from-[#e85bbd] via-[#b7007c]/30 to-transparent"
          />
          {steps.map(step => (
            <div
              key={step.id}
              className="flex items-start gap-2.5 text-xs duration-300 animate-in fade-in slide-in-from-left-1"
            >
              {step.state === 'running' ? (
                <span className="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center">
                  <LuLoader2 className="h-3.5 w-3.5 animate-spin text-[#b7007c]" />
                </span>
              ) : (
                <span className="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-emerald-100 duration-300 animate-in zoom-in">
                  <LuCheck className="h-2.5 w-2.5 text-emerald-600" />
                </span>
              )}
              <div className="flex min-w-0 flex-col gap-0.5">
                <span
                  className={cn(
                    'font-medium',
                    step.state === 'running'
                      ? 'animate-pulse text-gray-900'
                      : 'text-gray-700'
                  )}
                >
                  {step.label}
                </span>
                {step.detail && (
                  <span className="leading-snug text-gray-400">
                    {step.detail}
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
