"use client";

/**
 * 状态栏组件
 * 
 * 用于显示执行步骤的进度和状态信息，支持：
 * - 多步骤进度显示
 * - 成功/错误状态处理
 * - 重试功能
 * - 自动隐藏机制
 * - 平滑动画效果
 * 
 * @author Financial Analysis Platform Team
 * @version 1.0.0
 */

import { useState, useEffect } from "react";
import { cn } from "@/lib/utils";

// ============================================================================
// 类型定义
// ============================================================================

/**
 * 执行步骤接口定义
 */
export interface ExecutionStep {
  /** 步骤唯一标识符 */
  id: string;
  /** 步骤显示名称 */
  name: string;
  /** 步骤详细描述 */
  description: string;
}

/**
 * 状态栏组件属性接口
 */
export interface StatusBarProps {
  /** 是否可见 */
  isVisible: boolean;
  /** 当前执行步骤 */
  currentStep: ExecutionStep | null;
  /** 当前步骤索引 */
  stepIndex: number;
  /** 总步骤数 */
  totalSteps: number;
  /** 执行状态 */
  status: 'idle' | 'loading' | 'success' | 'error';
  /** 错误信息 */
  errorMessage?: string;
  /** 关闭回调 */
  onDismiss?: () => void;
  /** 重试回调 */
  onRetry?: () => void;
  /** 是否可重试 */
  retryable?: boolean;
}

/**
 * 状态栏状态接口
 */
export interface StatusBarState {
  /** 是否可见 */
  isVisible: boolean;
  /** 当前执行步骤 */
  currentStep: ExecutionStep | null;
  /** 当前步骤索引 */
  stepIndex: number;
  /** 总步骤数 */
  totalSteps: number;
  /** 执行状态 */
  status: 'idle' | 'loading' | 'success' | 'error';
  /** 错误信息 */
  errorMessage?: string;
  /** 是否可重试 */
  retryable?: boolean;
}

// 预定义的执行步骤已移至 ExecutionStepManager (Deleted)

// ============================================================================
// 主组件
// ============================================================================

/**
 * 状态栏组件
 * 
 * 显示执行步骤的进度和状态，支持多种状态和交互
 * 
 * @param props - 组件属性
 * @returns JSX元素
 */
export function StatusBar({
  isVisible,
  currentStep,
  stepIndex,
  totalSteps,
  status,
  errorMessage,
  onDismiss,
  onRetry,
  retryable = false
}: StatusBarProps) {
  const [shouldRender, setShouldRender] = useState(isVisible);

  // 处理显示/隐藏动画
  useEffect(() => {
    if (isVisible) {
      setShouldRender(true);
    } else {
      // 延迟隐藏以完成动画
      const timer = setTimeout(() => setShouldRender(false), 300);
      return () => clearTimeout(timer);
    }
  }, [isVisible]);

  // 自动隐藏成功状态
  useEffect(() => {
    if (status === 'success' && onDismiss) {
      const timer = setTimeout(() => {
        onDismiss();
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [status, onDismiss]);

  // 错误状态自动超时隐藏（可选）
  useEffect(() => {
    if (status === 'error' && onDismiss) {
      const timer = setTimeout(() => {
        onDismiss();
      }, 10000); // 10秒后自动隐藏错误信息
      return () => clearTimeout(timer);
    }
  }, [status, onDismiss]);

  if (!shouldRender) return null;

  return (
    <div
      className={cn(
        "fixed top-20 left-1/2 transform -translate-x-1/2 z-50 transition-all duration-300 ease-in-out",
        isVisible ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-2"
      )}
    >
      <div className={cn(
        "bg-white border rounded-lg shadow-lg px-4 py-3 min-w-80 max-w-md",
        status === 'error' && "border-red-200 bg-red-50",
        status === 'success' && "border-green-200 bg-green-50",
        status === 'loading' && "border-blue-200 bg-blue-50"
      )}>
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            {/* 状态图标 */}
            <div className="flex-shrink-0">
              {status === 'loading' && (
                <div className="animate-spin rounded-full h-4 w-4 border-2 border-blue-500 border-t-transparent" />
              )}
              {status === 'success' && (
                <div className="rounded-full h-4 w-4 bg-green-500 flex items-center justify-center">
                  <svg className="h-2.5 w-2.5 text-white" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                  </svg>
                </div>
              )}
              {status === 'error' && (
                <div className="rounded-full h-4 w-4 bg-red-500 flex items-center justify-center">
                  <svg className="h-2.5 w-2.5 text-white" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                  </svg>
                </div>
              )}
            </div>

            {/* 状态文本 */}
            <div className="flex-1">
              <div className={cn(
                "text-sm font-medium",
                status === 'error' && "text-red-800",
                status === 'success' && "text-green-800",
                status === 'loading' && "text-blue-800"
              )}>
                {status === 'error' ? '执行失败' : 
                 status === 'success' ? '执行完成' :
                 currentStep?.name || '正在执行...'}
              </div>
              {status === 'error' && errorMessage && (
                <div className="text-xs text-red-600 mt-1 max-w-sm">
                  {errorMessage}
                  {errorMessage.includes('网络') || errorMessage.includes('连接') ? (
                    <div className="mt-1 text-xs text-red-500">
                      请检查网络连接或稍后重试
                    </div>
                  ) : null}
                </div>
              )}
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex items-center gap-1 ml-2">
            {/* 重试按钮 */}
            {status === 'error' && retryable && onRetry && (
              <button
                onClick={onRetry}
                className="flex-shrink-0 px-2 py-1 text-xs bg-red-100 text-red-700 hover:bg-red-200 rounded transition-colors"
                title="重试"
              >
                重试
              </button>
            )}
            
            {/* 关闭按钮 */}
            {(status === 'error' || status === 'success') && onDismiss && (
              <button
                onClick={onDismiss}
                className={cn(
                  "flex-shrink-0 rounded-full p-1 hover:bg-gray-100 transition-colors",
                  status === 'error' && "hover:bg-red-100",
                  status === 'success' && "hover:bg-green-100"
                )}
              >
                <svg className="h-3 w-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                </svg>
              </button>
            )}
          </div>
        </div>

        {/* 进度指示器 */}
        {status === 'loading' && totalSteps > 1 && (
          <div className="mt-3">
            <div className="flex justify-between text-xs text-gray-600 mb-1">
              <span>步骤 {stepIndex + 1} / {totalSteps}</span>
              <span>{Math.round(((stepIndex + 1) / totalSteps) * 100)}%</span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-1.5">
              <div 
                className="bg-blue-500 h-1.5 rounded-full transition-all duration-300 ease-out"
                style={{ width: `${((stepIndex + 1) / totalSteps) * 100}%` }}
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================================================
// 状态管理Hook
// ============================================================================

/**
 * 状态栏状态管理Hook
 * 
 * 提供状态栏的状态管理和操作方法
 * 
 * @returns 状态栏状态和操作方法
 */
export function useStatusBar() {
  const [statusBarState, setStatusBarState] = useState<StatusBarState>({
    isVisible: false,
    currentStep: null,
    stepIndex: 0,
    totalSteps: 1,
    status: 'idle',
    errorMessage: undefined,
    retryable: false
  });

  const showStatusBar = (step: ExecutionStep, stepIndex: number = 0, totalSteps: number = 1) => {
    setStatusBarState({
      isVisible: true,
      currentStep: step,
      stepIndex,
      totalSteps,
      status: 'loading',
      errorMessage: undefined
    });
  };

  const updateStep = (step: ExecutionStep, stepIndex: number) => {
    setStatusBarState(prev => ({
      ...prev,
      currentStep: step,
      stepIndex,
      status: 'loading'
    }));
  };

  const showSuccess = () => {
    setStatusBarState(prev => ({
      ...prev,
      status: 'success'
    }));
  };

  const showError = (errorMessage: string, retryable: boolean = false) => {
    setStatusBarState(prev => ({
      ...prev,
      status: 'error',
      errorMessage,
      retryable
    }));
  };

  const hideStatusBar = () => {
    setStatusBarState(prev => ({
      ...prev,
      isVisible: false
    }));
  };

  return {
    statusBarState,
    showStatusBar,
    updateStep,
    showSuccess,
    showError,
    hideStatusBar
  };
}