import React, { useMemo, useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ChevronDown, ChevronRight, Factory, Share2, Edit3, Trash2, CheckCircle, XCircle, Building2 } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import { animationConfig, statusMap } from '../../utils/constants';
import { calculateProgress } from '../../utils/helpers';
import { PlanEditModal } from './PlanEditModal';
import type { PlanWithSteps, Company, YarnRatio } from '../../types';

// 纱线类型显示映射
const yarnTypeLabels: Record<string, string> = {
  warp: '经线',
  weft: '纬线',
  all: '全部'
};

interface PlanGroupProps {
  factory: Company;
  plans: PlanWithSteps[];
  isExpanded: boolean;
  expandedPlan: string | null;
  onToggleGroup: () => void;
  onTogglePlan: (planId: string) => void;
  onShare: (planId: string, type: 'textile' | 'washing', factoryName: string, factoryId: string, productName?: string, color?: string, colorCode?: string) => void;
  onPlanUpdated?: () => void;
  operatorNames: Record<string, string>;
}

export function PlanGroup({
  factory,
  plans,
  isExpanded,
  expandedPlan,
  onToggleGroup,
  onTogglePlan,
  onShare,
  onPlanUpdated,
  operatorNames
}: PlanGroupProps) {
  const { isMobile } = useResponsive();

  const activeCount = useMemo(() => 
    plans.filter(p => 
      p.status === 'producing' || 
      (p.status === 'pending' && p.processSteps.some(s => s.status === 'active'))
    ).length,
    [plans]
  );

  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      whileHover={isMobile ? {} : { y: -2 }}
      className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden"
    >
      {/* 工厂头部 */}
      <div
        onClick={onToggleGroup}
        className="flex items-center justify-between p-3 sm:p-4 cursor-pointer hover:bg-gray-50 transition-colors"
      >
        <div className="flex items-center gap-2 sm:gap-3 min-w-0">
          <div className={`w-7 h-7 sm:w-8 sm:h-8 rounded-lg flex items-center justify-center transition-colors flex-shrink-0 ${isExpanded ? 'bg-blue-100' : 'bg-gray-100'}`}>
            {isExpanded ? (
              <ChevronDown size={isMobile ? 16 : 18} className="text-blue-600" />
            ) : (
              <ChevronRight size={isMobile ? 16 : 18} className="text-gray-500" />
            )}
          </div>
          <div className="min-w-0">
            <h3 className="font-semibold text-gray-900 text-sm sm:text-base truncate">{factory.name}</h3>
            <p className="text-xs sm:text-sm text-gray-500">
              {plans.length === 0 ? '无计划' : `${plans.length}个计划 · ${activeCount}个进行中`}
            </p>
          </div>
        </div>
        {activeCount > 0 && (
          <span className="px-2 py-0.5 sm:px-2.5 sm:py-1 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex-shrink-0 ml-2">
            {activeCount}进行中
          </span>
        )}
      </div>

      {/* 计划列表 */}
      <AnimatePresence>
        {isExpanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={animationConfig.transition}
            className="border-t border-gray-100"
          >
            <div className="p-3 sm:p-4 space-y-2 sm:space-y-3">
              {plans.map(plan => (
                <PlanCard
                  key={plan.id}
                  plan={plan}
                  isExpanded={expandedPlan === plan.id}
                  onToggle={() => onTogglePlan(plan.id)}
                  onShare={() => onShare(plan.id, factory.role as 'textile' | 'washing', factory.name, factory.id, plan.product_name, plan.color, plan.color_code)}
                  operatorNames={operatorNames}
                  factoryName={factory.name}
                />
              ))}
              {plans.length === 0 && (
                <div className="text-center py-6 sm:py-8 text-gray-400">
                  <p className="text-sm">暂无匹配的计划</p>
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

// 计划卡片组件
interface PlanCardProps {
  plan: PlanWithSteps;
  isExpanded: boolean;
  onToggle: () => void;
  onShare: () => void;
  onPlanUpdated?: () => void;
  operatorNames: Record<string, string>;
  factoryName?: string; // 关联的工厂名称
}

function PlanCard({ plan, isExpanded, onToggle, onShare, onPlanUpdated, operatorNames, factoryName }: PlanCardProps) {
  const [showEditModal, setShowEditModal] = useState(false);
  const [showRejectModal, setShowRejectModal] = useState(false);
  const { isMobile } = useResponsive();

  // 检测是否被纺织厂拒绝（采购商视角）- 必须先声明
  const rejectedStep = plan.processSteps.find(s => s.status === 'rejected');
  const isRejected = !!rejectedStep;
  const rejectReason = rejectedStep?.notes?.replace('拒绝原因: ', '') || '';

  // 如果被拒绝，显示已拒绝状态
  const displayStatus = isRejected ? statusMap.rejected : (statusMap[plan.status] || statusMap.pending);
  const progress = calculateProgress(plan.completed_quantity, plan.target_quantity);

  // 判断是否需要显示分享按钮
  // 规则：只有当"确认计划"步骤状态为 pending 时才显示分享按钮
  const confirmStep = plan.processSteps.find(s => s.step_type === 'confirm');
  const shouldShowShareButton = confirmStep?.status === 'pending';

  // 判断是否可以编辑/删除：只有当"确认计划"步骤状态为 pending 时才允许
  const canModify = confirmStep?.status === 'pending';

  // 获取当前环节
  const currentStep = useMemo(() => {
    const stepOrder = ['confirm', 'yarn_purchase', 'dyeing', 'machine_start', 'fabric_warehouse'];
    const stepNames: Record<string, string> = {
      confirm: '确认计划',
      yarn_purchase: '采纱',
      dyeing: '染纱',
      machine_start: '上机',
      fabric_warehouse: '坯布生产'
    };
    
    const sortedSteps = stepOrder
      .map(type => plan.processSteps.find(s => s.step_type === type))
      .filter(Boolean);
    
    const activeStep = sortedSteps.find(s => s?.status === 'active');
    if (activeStep) return `· 当前环节: ${stepNames[activeStep.step_type] || activeStep.step_type}`;
    
    const pendingStep = sortedSteps.find(s => s?.status === 'pending');
    if (pendingStep) return `· 当前环节: ${stepNames[pendingStep.step_type] || pendingStep.step_type}`;
    
    const allCompleted = sortedSteps.every(s => s?.status === 'completed');
    if (allCompleted && sortedSteps.length > 0) return '· 已完成';
    
    return '· 待开始';
  }, [plan.processSteps]);

  // 被拒绝时自动显示弹窗（每个计划只弹一次）
  useEffect(() => {
    if (isRejected && plan.id) {
      // 检查该计划的拒绝弹窗是否已经显示过
      const viewedKey = `rejected_modal_viewed_${plan.id}`;
      const hasViewed = localStorage.getItem(viewedKey);
      if (!hasViewed) {
        setShowRejectModal(true);
        // 标记该计划的拒绝弹窗已显示
        localStorage.setItem(viewedKey, 'true');
      }
    }
  }, [isRejected, plan.id]);

  return (
    <div className={`border rounded-xl overflow-hidden transition-colors ${isRejected ? 'border-gray-300 bg-gray-100' : 'border-gray-200 hover:border-blue-200'}`}>
      {/* 计划头部 */}
      <div
        onClick={onToggle}
        className="p-3 sm:p-4 cursor-pointer hover:bg-gray-50 transition-colors"
      >
        <div className="flex items-start justify-between gap-2 sm:gap-4">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-1.5 sm:gap-2 mb-1">
              <h4 className="font-medium text-gray-900 text-sm sm:text-base truncate">
                {plan.product_name}-{plan.color}
              </h4>
              <span className={`px-1.5 sm:px-2 py-0.5 text-xs font-medium rounded-full flex-shrink-0 ${displayStatus.bgColor} ${displayStatus.color} border ${displayStatus.borderColor}`}>
                {displayStatus.label}
              </span>
            </div>
            <p className="text-xs sm:text-sm text-gray-500">{plan.fabric_code}-{plan.color_code}</p>
            <p className="text-xs text-gray-400 mt-0.5">{plan.plan_code}</p>
            
            {/* 显示关联工厂信息 */}
            {factoryName && (
              <div className="mt-2 flex items-center gap-1.5 text-xs text-blue-600 bg-blue-50 px-2 py-1 rounded-lg">
                <Building2 size={12} />
                <span>关联工厂: {factoryName}</span>
              </div>
            )}
            
            {/* 已拒绝计划显示拒绝理由 */}
            {isRejected && (
              <div className="mt-2 p-2 bg-red-50 border border-red-100 rounded-lg">
                <p className="text-xs text-red-600 font-medium">拒绝理由：</p>
                <p className="text-xs text-red-700 mt-0.5">{rejectReason || '未说明原因'}</p>
              </div>
            )}
          </div>
          <div className="text-right flex-shrink-0">
            <p className="text-sm font-medium text-gray-900">{plan.target_quantity.toLocaleString()}米</p>
            <p className="text-xs text-gray-500">已入库 {plan.completed_quantity.toLocaleString()}米</p>
          </div>
        </div>

        {/* 进度条 */}
        <div className="mt-2 sm:mt-3">
          <div className="flex items-center justify-between text-xs text-gray-500 mb-1">
            <div className="flex items-center gap-2">
              <span>生产进度</span>
              {plan.processSteps.length > 0 && (
                <span className="text-blue-600">{currentStep}</span>
              )}
            </div>
            <span className="font-medium">{progress}%</span>
          </div>
          <div className="h-1.5 sm:h-2 bg-gray-100 rounded-full overflow-hidden">
            <motion.div
              initial={{ width: 0 }}
              animate={{ width: `${progress}%` }}
              className="h-full bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full"
              transition={{ duration: 0.5 }}
            />
          </div>
        </div>

        {/* 展开指示器 */}
        <div className="flex items-center justify-center mt-2">
          <motion.div
            animate={{ rotate: isExpanded ? 180 : 0 }}
            transition={{ duration: 0.2 }}
          >
            <ChevronDown size={16} className="text-gray-400" />
          </motion.div>
        </div>
      </div>

      {/* 计划详情展开区域 */}
      <AnimatePresence>
        {isExpanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.3 }}
            className="border-t border-gray-100 bg-gray-50/50"
          >
            <div className="p-3 sm:p-4 space-y-3">
              {/* 产品图片和基本信息 */}
              <div className="flex items-start gap-3 mb-3">
                {plan.image_url ? (
                  <img
                    src={plan.image_url}
                    alt={plan.product_name}
                    className="w-16 h-16 sm:w-20 sm:h-20 rounded-lg object-cover border border-gray-200 flex-shrink-0"
                  />
                ) : (
                  <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
                    <span className="text-gray-400 text-[10px] sm:text-xs">无图片</span>
                  </div>
                )}
                <div className="flex-1 grid grid-cols-2 gap-x-2 gap-y-1 text-xs sm:text-sm">
                  <div className="truncate">
                    <span className="text-gray-400">编号:</span>
                    <span className="ml-1 text-gray-700 font-medium">{plan.plan_code}</span>
                  </div>
                  <div className="truncate">
                    <span className="text-gray-400">坯布:</span>
                    <span className="ml-1 text-gray-700 font-medium">{plan.fabric_code}</span>
                  </div>
                  <div className="truncate">
                    <span className="text-gray-400">色号:</span>
                    <span className="ml-1 text-gray-700 font-medium">{plan.color_code}</span>
                  </div>
                  <div className="truncate">
                    <span className="text-gray-400">计划:</span>
                    <span className="ml-1 text-gray-700 font-medium">{plan.target_quantity.toLocaleString()}米</span>
                  </div>
                  <div className="truncate">
                    <span className="text-gray-400">完成:</span>
                    <span className="ml-1 text-gray-700 font-medium">{plan.completed_quantity.toLocaleString()}米</span>
                  </div>
                  <div className="truncate">
                    <span className="text-gray-400">进度:</span>
                    <span className="ml-1 text-blue-600 font-medium">{progress}%</span>
                  </div>
                  <div className="truncate">
                    <span className="text-gray-400">创建:</span>
                    <span className="ml-1 text-gray-700">{new Date(plan.created_at).toLocaleDateString('zh-CN')}</span>
                  </div>
                  <div className="truncate">
                    <span className="text-gray-400">开始:</span>
                    <span className="ml-1 text-gray-700">{plan.start_time ? new Date(plan.start_time).toLocaleDateString('zh-CN') : '-'}</span>
                  </div>
                </div>
              </div>

              {/* 关联工厂信息（展开后更详细显示） */}
              {factoryName && (
                <div className="bg-blue-50 border border-blue-100 rounded-lg p-3">
                  <div className="flex items-center gap-2 mb-2">
                    <Building2 size={16} className="text-blue-600" />
                    <span className="font-medium text-blue-900 text-sm">关联工厂信息</span>
                  </div>
                  <p className="text-sm text-blue-800">工厂名称: {factoryName}</p>
                  <p className="text-xs text-blue-600 mt-1">该计划已通过分享链接与此工厂建立关联</p>
                </div>
              )}

              {/* 备注信息 */}
              {plan.remark && (
                <div className="text-xs sm:text-sm bg-gray-50 p-2 rounded-lg mb-3">
                  <span className="text-gray-400">备注:</span>
                  <span className="ml-1 text-gray-700">{plan.remark}</span>
                </div>
              )}

              {/* 克重和采购价信息 */}
              <div className="grid grid-cols-2 sm:grid-cols-5 gap-2 text-xs sm:text-sm">
                <div className="truncate">
                  <span className="text-gray-400">克重:</span>
                  <span className="ml-1 text-gray-700 font-medium">{(plan as any).weight || plan.total_weight || plan.yarn_usage_per_meter || '-'}g</span>
                </div>
                <div className="truncate">
                  <span className="text-gray-400">经线:</span>
                  <span className="ml-1 text-gray-700 font-medium">{plan.warp_weight || '-'}g</span>
                </div>
                <div className="truncate">
                  <span className="text-gray-400">纬线:</span>
                  <span className="ml-1 text-gray-700 font-medium">{plan.weft_weight || '-'}g</span>
                </div>
                <div className="truncate">
                  <span className="text-gray-400">总克重:</span>
                  <span className="ml-1 text-gray-700 font-medium">{plan.total_weight || '-'}g</span>
                </div>
                <div className="truncate">
                  <span className="text-gray-400">采购价:</span>
                  <span className="ml-1 text-gray-700 font-medium">¥{plan.production_price || 0}/米</span>
                </div>
              </div>

              {/* 纱线配比信息 */}
              {plan.yarn_ratios && plan.yarn_ratios.length > 0 && (
                <div className="border-t border-gray-200 pt-3 mb-4">
                  <h5 className="text-sm font-medium text-gray-900 mb-2">纱线名称/占比</h5>
                  <div className="flex flex-wrap gap-2">
                    {plan.yarn_ratios.map((yarn, index) => (
                      <span key={index} className="inline-flex items-center px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-lg">
                        {yarnTypeLabels[yarn.yarn_type || 'all']}/{yarn.yarn_name}:{Number(yarn.ratio).toFixed(0)}%
                        {yarn.amount_per_meter && `(${yarn.amount_per_meter}g/m)`}
                      </span>
                    ))}
                  </div>
                  {plan.yarn_usage_per_meter && (
                    <p className="text-xs text-gray-500 mt-2">
                      每米纱用量: {plan.yarn_usage_per_meter}g/m
                    </p>
                  )}
                </div>
              )}

              {/* 操作按钮 */}
              <div className="flex gap-2 pt-2 border-t border-gray-200">
                {shouldShowShareButton && (
                  <button
                    onClick={(e) => { e.stopPropagation(); onShare(); }}
                    className="flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-colors"
                  >
                    <Share2 size={14} />
                    分享
                  </button>
                )}
                {canModify && (
                  <>
                    <button
                      onClick={(e) => { e.stopPropagation(); setShowEditModal(true); }}
                      className="flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                    >
                      <Edit3 size={14} />
                      编辑
                    </button>
                    <button
                      onClick={(e) => { e.stopPropagation(); /* 删除逻辑 */ }}
                      className="flex items-center gap-1 px-3 py-1.5 text-xs font-medium text-red-600 bg-red-50 hover:bg-red-100 rounded-lg transition-colors"
                    >
                      <Trash2 size={14} />
                      删除
                    </button>
                  </>
                )}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 编辑弹窗 */}
      {showEditModal && (
        <PlanEditModal
          plan={plan}
          isOpen={true}
          onClose={() => setShowEditModal(false)}
          onPlanUpdated={onPlanUpdated}
        />
      )}

      {/* 拒绝通知弹窗 */}
      {showRejectModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ scale: 0.95, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            className="bg-white rounded-xl p-6 max-w-md w-full"
          >
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
                <XCircle className="w-6 h-6 text-red-600" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900">计划被拒绝</h3>
            </div>
            <p className="text-sm text-gray-600 mb-2">纺织厂拒绝了您的计划</p>
            <div className="bg-red-50 p-3 rounded-lg mb-4">
              <p className="text-xs text-red-600 font-medium">拒绝理由：</p>
              <p className="text-sm text-red-700 mt-1">{rejectReason || '未说明原因'}</p>
            </div>
            <button
              onClick={() => setShowRejectModal(false)}
              className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              我知道了
            </button>
          </motion.div>
        </div>
      )}
    </div>
  );
}
