import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Check, Clock, Loader2, Package, AlertCircle, List } from 'lucide-react';
import { YarnAllocationModal } from './YarnAllocationModal';
import type { StepType, StepStatus, YarnRatio } from '../types';

interface ProcessNode {
  id: string;
  name: string;
  status: StepStatus;
  timestamp?: string | null;
  stepType: StepType;
  operatorName?: string;
}

interface ProcessFlowProps {
  nodes: ProcessNode[];
  onConfirm?: (stepId: string, quantity?: number, rolls?: number) => void;
  onReject?: (stepId: string) => void;
  confirmLoading?: string | null;
  showConfirmButton?: boolean;
  planTargetQuantity?: number;
  planCompletedQuantity?: number;
  isPlanLocked?: boolean;
  lastInventoryTime?: string | null;
  inventoryRecords?: { time: string; quantity: number; rolls: number | null }[];
  yarnRatios?: YarnRatio[];
  companyId?: string;
  planId?: string;
}

const stepTypeConfig: Record<StepType, { name: string; icon: React.ReactNode }> = {
  confirm: { name: '确认计划', icon: <Check className="w-4 h-4" /> },
  yarn_purchase: { name: '采纱', icon: <Clock className="w-4 h-4" /> },
  dyeing: { name: '染纱', icon: <Clock className="w-4 h-4" /> },
  machine_start: { name: '上机', icon: <Clock className="w-4 h-4" /> },
  fabric_warehouse: { name: '坯布生产', icon: <Package className="w-4 h-4" /> }
};

export function ProcessFlow({
  nodes,
  onConfirm,
  onReject,
  confirmLoading,
  showConfirmButton = true,
  planTargetQuantity = 0,
  planCompletedQuantity = 0,
  isPlanLocked = false,
  lastInventoryTime,
  inventoryRecords = [],
  yarnRatios = [],
  companyId,
  planId
}: ProcessFlowProps) {
  const [inputQuantity, setInputQuantity] = useState<string>('');
  const [inputRolls, setInputRolls] = useState<string>('');
  const [showInput, setShowInput] = useState<string | null>(null);
  const [showCompleteModal, setShowCompleteModal] = useState(false);
  const [pendingQuantity, setPendingQuantity] = useState<number>(0);
  const [pendingRolls, setPendingRolls] = useState<number>(0);
  const [pendingNodeId, setPendingNodeId] = useState<string>('');
  const [showYarnModal, setShowYarnModal] = useState(false);
  const [pendingYarnStepId, setPendingYarnStepId] = useState<string>('');

  // 按顺序排序节点
  const sortedNodes = React.useMemo(() => {
    const order: StepType[] = ['confirm', 'yarn_purchase', 'dyeing', 'machine_start', 'fabric_warehouse'];
    return [...nodes].sort((a, b) => {
      const indexA = order.indexOf(a.stepType);
      const indexB = order.indexOf(b.stepType);
      return indexA - indexB;
    });
  }, [nodes]);

  // 找到第一个待确认的节点（第一个非 completed 的节点）
  const firstPendingIndex = sortedNodes.findIndex(n => n.status !== 'completed');

  // 计算当前进度
  const progressPercent = planTargetQuantity > 0 
    ? ((planCompletedQuantity / planTargetQuantity) * 100) 
    : 0;

  const handleConfirmClick = (nodeId: string, stepType: StepType) => {
    if (stepType === 'fabric_warehouse') {
      // 坯布入库需要输入数量
      setShowInput(nodeId);
      setInputQuantity('');
    } else if (stepType === 'yarn_purchase') {
      // 采纱环节需要检查纱线库存
      if (yarnRatios.length > 0 && companyId) {
        setPendingYarnStepId(nodeId);
        setShowYarnModal(true);
      } else {
        // 没有纱线配比数据，直接确认
        onConfirm?.(nodeId);
      }
    } else {
      // 其他节点直接确认
      onConfirm?.(nodeId);
    }
  };

  const handleYarnAllocationConfirm = () => {
    // 纱线分配确认后，继续确认采纱步骤
    onConfirm?.(pendingYarnStepId);
    setPendingYarnStepId('');
  };

  const handleWarehouseConfirm = (nodeId: string) => {
    const quantity = parseFloat(inputQuantity);
    const rolls = parseInt(inputRolls) || 0;
    if (isNaN(quantity) || quantity <= 0) {
      alert('请输入有效的入库米数');
      return;
    }
    if (quantity > planTargetQuantity - planCompletedQuantity) {
      alert(`入库数量不能超过剩余数量 (${planTargetQuantity - planCompletedQuantity}米)`);
      return;
    }

    // 检查入库后是否达到97%
    const newProgress = ((planCompletedQuantity + quantity) / planTargetQuantity) * 100;
    if (newProgress >= 97 && !isPlanLocked) {
      // 显示完成确认弹窗
      setPendingQuantity(quantity);
      setPendingRolls(rolls);
      setPendingNodeId(nodeId);
      setShowCompleteModal(true);
    } else {
      // 直接入库 - 传递米数和匹/件数
      onConfirm?.(nodeId, quantity, rolls);
    }
    setShowInput(null);
    setInputQuantity('');
    setInputRolls('');
  };

  const handleCompletePlan = () => {
    onConfirm?.(pendingNodeId, pendingQuantity, pendingRolls);
    setShowCompleteModal(false);
    setPendingQuantity(0);
    setPendingRolls(0);
    setPendingNodeId('');
  };

  return (
    <div className="space-y-0">
      {sortedNodes.map((node, index) => {
        const isLast = index === sortedNodes.length - 1;
        const config = stepTypeConfig[node.stepType] || { name: node.name, icon: <Clock className="w-4 h-4" /> };
        const isLoading = confirmLoading === node.id;
        // 当前节点是第一个待确认节点（pending 或 active）
        const isCurrentStep = index === firstPendingIndex && node.status !== 'completed';
        const canConfirm = showConfirmButton && isCurrentStep && onConfirm && !isLoading && !isPlanLocked;
        const isWarehouseInput = showInput === node.id && node.stepType === 'fabric_warehouse';
        
        return (
          <div key={node.id} className="relative">
            {/* 连接线 */}
            {!isLast && (
              <div 
                className={`absolute left-5 top-10 w-0.5 h-8 ${
                  node.status === 'completed' ? 'bg-green-500' : 'bg-gray-200'
                }`}
              />
            )}
            
            <div className="flex items-start gap-4 p-3 rounded-lg hover:bg-gray-50 transition-colors">
              {/* 节点图标 */}
              <div className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${
                node.status === 'completed'
                  ? 'bg-green-500 text-white'
                  : isCurrentStep
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-200 text-gray-400'
              }`}>
                {node.status === 'completed' ? (
                  <Check className="w-5 h-5" />
                ) : isCurrentStep ? (
                  <motion.div
                    animate={{ scale: [1, 1.15, 1] }}
                    transition={{ repeat: Infinity, duration: 1.2, ease: 'easeInOut' }}
                    style={{ willChange: 'transform' }}
                  >
                    {config.icon}
                  </motion.div>
                ) : (
                  <span className="text-sm">{index + 1}</span>
                )}
              </div>
              
              {/* 节点内容 */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2 whitespace-nowrap">
                    <h4 className={`font-medium whitespace-nowrap ${
                      node.status === 'pending' ? 'text-gray-400' : 'text-gray-800'
                    }`}>
                      {config.name}
                    </h4>
                    {isCurrentStep && (
                      <span className="text-xs text-blue-600 bg-blue-50 px-2 py-0.5 rounded whitespace-nowrap">
                        进行中
                      </span>
                    )}
                    {node.status === 'completed' && (
                      <span className="text-xs text-green-600 bg-green-50 px-2 py-0.5 rounded whitespace-nowrap">
                        已完成
                      </span>
                    )}
                  </div>
                </div>

                {node.timestamp && (
                  <p className="text-xs text-gray-500 mt-1">
                    {new Date(node.timestamp).toLocaleString('zh-CN')}
                    {node.operatorName && ` · ${node.operatorName}`}
                  </p>
                )}

                {/* 显示最近一次入库时间和记录 */}
                {node.stepType === 'fabric_warehouse' && inventoryRecords.length > 0 && (
                  <div className="text-xs text-gray-400 mt-2 whitespace-nowrap">
                    <span className="text-gray-500 font-medium">入库记录:</span>
                    <span className="ml-1 text-gray-700">
                      {new Date(inventoryRecords[0].time).toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' })}
                      <span className="mx-2 text-gray-400"> </span>
                      {inventoryRecords[0].quantity}米
                    </span>
                  </div>
                )}

                {/* 坯布入库输入框 */}
                <AnimatePresence>
                  {isWarehouseInput && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: 'auto', opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      transition={{ duration: 0.25, ease: [0.25, 0.46, 0.45, 0.94] }}
                      className="mt-3 bg-white rounded-lg border border-blue-200 p-3 sm:p-4"
                    >
                      <div className="flex items-center gap-2 mb-3">
                        <span className="text-xs sm:text-sm text-gray-600">本次入库数量：</span>
                        <span className="text-xs sm:text-sm text-gray-400">
                          (已入库: {planCompletedQuantity}米 / 计划: {planTargetQuantity}米)
                        </span>
                      </div>
                      <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 mb-3">
                        <div className="flex-1 min-w-0">
                          <label className="text-xs sm:text-sm text-gray-500 mb-1.5 block">匹/件数</label>
                          <div className="flex gap-2">
                            <input
                              type="number"
                              value={inputRolls}
                              onChange={(e) => setInputRolls(e.target.value)}
                              placeholder="输入匹/件数"
                              className="flex-1 min-w-0 px-3 py-3 sm:py-2.5 text-sm sm:text-base border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 touch-manipulation"
                              min="0"
                              inputMode="numeric"
                              pattern="[0-9]*"
                            />
                            <span className="text-sm sm:text-base text-gray-500 self-center flex-shrink-0">匹/件</span>
                          </div>
                        </div>
                        <div className="flex-1 min-w-0">
                          <label className="text-xs sm:text-sm text-gray-500 mb-1.5 block">米数</label>
                          <div className="flex gap-2">
                            <input
                              type="number"
                              value={inputQuantity}
                              onChange={(e) => setInputQuantity(e.target.value)}
                              placeholder={`剩余 ${planTargetQuantity - planCompletedQuantity} 米`}
                              className="flex-1 min-w-0 px-3 py-3 sm:py-2.5 text-sm sm:text-base border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 touch-manipulation"
                              min="0"
                              max={planTargetQuantity - planCompletedQuantity}
                              inputMode="decimal"
                              pattern="[0-9.]*"
                            />
                            <span className="text-sm sm:text-base text-gray-500 self-center flex-shrink-0">米</span>
                          </div>
                        </div>
                      </div>
                      <div className="flex gap-2 sm:gap-3">
                        <motion.button
                          whileTap={{ scale: 0.98 }}
                          onClick={() => { setShowInput(null); setInputRolls(''); setInputQuantity(''); }}
                          className="flex-1 px-3 py-2.5 sm:py-2 text-xs sm:text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors will-change-transform"
                        >
                          取消
                        </motion.button>
                        <motion.button
                          whileTap={{ scale: 0.98 }}
                          onClick={() => handleWarehouseConfirm(node.id)}
                          disabled={!inputQuantity || parseFloat(inputQuantity) <= 0}
                          className="flex-1 px-3 py-2.5 sm:py-2 text-xs sm:text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors will-change-transform"
                        >
                          确认入库
                        </motion.button>
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>

              {/* 确认/拒绝按钮 */}
              {canConfirm && !isWarehouseInput && (
                <>
                  {node.stepType === 'confirm' && onReject ? (
                    /* 确认计划步骤：显示同意/拒绝两个按钮 */
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <motion.button
                        whileTap={{ scale: 0.95 }}
                        onClick={() => onReject(node.id)}
                        disabled={isLoading}
                        className="px-3 py-1.5 text-xs bg-red-50 text-red-600 border border-red-200 rounded-lg hover:bg-red-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                      >
                        拒绝
                      </motion.button>
                      <motion.button
                        whileTap={{ scale: 0.95 }}
                        onClick={() => handleConfirmClick(node.id, node.stepType)}
                        disabled={isLoading}
                        className="px-3 py-1.5 text-xs bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-1"
                      >
                        {isLoading ? (
                          <Loader2 className="w-3 h-3 animate-spin" />
                        ) : (
                          <Check className="w-3 h-3" />
                        )}
                        同意
                      </motion.button>
                    </div>
                  ) : (
                    /* 其他步骤：显示单个确认按钮 */
                    <button
                      onClick={() => handleConfirmClick(node.id, node.stepType)}
                      disabled={isLoading}
                      className="w-8 h-8 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center transition-colors flex-shrink-0"
                    >
                      {isLoading ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Check className="w-4 h-4" />
                      )}
                    </button>
                  )}
                </>
              )}
            </div>
          </div>
        );
      })}

      {/* 计划完成确认弹窗 */}
      <AnimatePresence>
      {showCompleteModal && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
        >
          <motion.div
            initial={{ scale: 0.95, opacity: 0, y: 20 }}
            animate={{ scale: 1, opacity: 1, y: 0 }}
            exit={{ scale: 0.95, opacity: 0, y: 20 }}
            transition={{ duration: 0.2, ease: [0.25, 0.46, 0.45, 0.94] }}
            className="bg-white rounded-xl p-6 w-full max-w-sm shadow-xl"
          >
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-amber-100 flex items-center justify-center">
                <AlertCircle className="w-6 h-6 text-amber-600" />
              </div>
              <h3 className="text-lg font-semibold text-gray-800">计划即将完成</h3>
            </div>
            <p className="text-sm text-gray-600 mb-4">
              本次入库后计划进度将达到 <span className="font-semibold text-amber-600">{((planCompletedQuantity + pendingQuantity) / planTargetQuantity * 100).toFixed(1)}%</span>，
              满足完成条件（≥97%）。
            </p>
            <p className="text-xs text-gray-500 mb-6 bg-gray-50 p-3 rounded-lg">
              点击"完成计划"后，所有记录将被保存且不可更改或删除。
            </p>
            <div className="flex gap-3">
              <motion.button
                whileTap={{ scale: 0.98 }}
                onClick={() => setShowCompleteModal(false)}
                className="flex-1 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 text-sm font-medium transition-colors will-change-transform"
              >
                继续入库
              </motion.button>
              <motion.button
                whileTap={{ scale: 0.98 }}
                onClick={handleCompletePlan}
                className="flex-1 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm font-medium transition-colors will-change-transform"
              >
                完成计划
              </motion.button>
            </div>
          </motion.div>
        </motion.div>
      )}
      </AnimatePresence>

      {/* 纱线分配弹窗 */}
      <YarnAllocationModal
        isOpen={showYarnModal}
        onClose={() => setShowYarnModal(false)}
        onConfirm={handleYarnAllocationConfirm}
        yarnRatios={yarnRatios}
        companyId={companyId || ''}
        planTargetQuantity={planTargetQuantity}
        planId={planId}
      />
    </div>
  );
}
