import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { http } from '../api';
import { motion } from 'framer-motion';
import { ArrowLeft, CheckCircle, AlertTriangle, Package, Droplet, Link2, Clock, XCircle, Building2 } from 'lucide-react';
import { decryptShareParams } from '../utils/shareCrypto';
import { useResponsive } from '../hooks/useResponsive';
import { useErrorHandler } from '../hooks/useErrorHandler';
import { SHARE_LINK_STATUS } from '../utils/constants';
import type { ProductionPlan, WashingPlan, YarnRatio, FactoryType } from '../types';

const containerVariants = {
  hidden: { opacity: 0 },
  visible: { opacity: 1, transition: { staggerChildren: 0.1 } }
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.4 } }
};

// 分享链接状态类型
type ShareLinkStatus = 'pending' | 'clicked' | 'confirmed' | 'rejected' | 'expired' | 'cancelled';

export function ImportPlanPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { auth } = useAuth();
  const { isMobile } = useResponsive();
  const handleError = useErrorHandler();

  const token = searchParams.get('token') || '';
  const shortCode = searchParams.get('s') || '';
  
  const [planId, setPlanId] = useState('');
  const [factoryType, setFactoryType] = useState<FactoryType | null>(null);
  const [hideSensitive, setHideSensitive] = useState(false);
  const [decrypting, setDecrypting] = useState(true);
  
  // 新流程状态
  const [shareLinkStatus, setShareLinkStatus] = useState<ShareLinkStatus | null>(null);
  const [linkExpired, setLinkExpired] = useState(false);
  const [linkClicked, setLinkClicked] = useState(false);
  const [timeRemaining, setTimeRemaining] = useState<string>('');
  const [rejectReason, setRejectReason] = useState('');
  const [showRejectForm, setShowRejectForm] = useState(false);

  // 解析链接并检查状态
  useEffect(() => {
    const resolveLink = async () => {
      if (shortCode) {
        try {
          const res = await http.get<any>(`/common/share-links/${shortCode}`);
          const data = res.data;

          if (data) {
            setShareLinkStatus(data.status as ShareLinkStatus);

            const expiresAt = data.expires_at ? new Date(data.expires_at) : null;
            const now = new Date();
            if (expiresAt && expiresAt < now) {
              setLinkExpired(true);
              await http.put(`/common/share-links/${shortCode}`, { status: SHARE_LINK_STATUS.EXPIRED });
            }

            const usedStatuses: ShareLinkStatus[] = [SHARE_LINK_STATUS.CONFIRMED as ShareLinkStatus, SHARE_LINK_STATUS.REJECTED as ShareLinkStatus, SHARE_LINK_STATUS.EXPIRED as ShareLinkStatus, SHARE_LINK_STATUS.CANCELLED as ShareLinkStatus];
            if (usedStatuses.includes(data.status as ShareLinkStatus)) {
              setDecrypting(false);
              return;
            }

            setPlanId(data.plan_id);
            setFactoryType(data.factory_type as FactoryType);
            setHideSensitive(data.hide_sensitive || false);

            if (data.status === SHARE_LINK_STATUS.PENDING) {
              try {
                await http.put(`/common/share-links/${shortCode}`, {
                  status: SHARE_LINK_STATUS.CLICKED,
                  clicked_at: new Date().toISOString()
                });
                setShareLinkStatus(SHARE_LINK_STATUS.CLICKED as ShareLinkStatus);
              } catch (err) {
                handleError(err, { userMessage: '更新链接点击状态失败', context: { shortCode } });
              }
              setLinkClicked(true);
            } else if (data.status === SHARE_LINK_STATUS.CLICKED) {
              setLinkClicked(true);
            }

            await http.post(`/common/share-links/${shortCode}/click`).catch(() => {});
          }
        } catch (err) {
          handleError(err, { userMessage: '短链查询失败', context: { shortCode } });
        }
        setDecrypting(false);
      } else if (token) {
        const decrypted = await decryptShareParams(token);
        if (decrypted) {
          setPlanId(decrypted.planId);
          setFactoryType(decrypted.factoryType as FactoryType);
          setHideSensitive(decrypted.hideSensitive || false);
        }
        setDecrypting(false);
      } else {
        setPlanId(searchParams.get('plan') || '');
        setFactoryType(searchParams.get('type') as FactoryType | null);
        setDecrypting(false);
      }
    };

    resolveLink();
  }, [token, shortCode]);

  // 倒计时显示
  useEffect(() => {
    if (!shortCode || !shareLinkStatus) return;

    const updateTimer = async () => {
      try {
        const res = await http.get<any>(`/common/share-links/${shortCode}`);
        const data = res.data;
        if (!data || !data.expires_at) return;

        const expiresAt = new Date(data.expires_at);
        const now = new Date();
        const diff = expiresAt.getTime() - now.getTime();

        if (diff <= 0) {
          setTimeRemaining('已过期');
          setLinkExpired(true);
          if (data.status !== SHARE_LINK_STATUS.EXPIRED && data.status !== SHARE_LINK_STATUS.CONFIRMED && data.status !== SHARE_LINK_STATUS.REJECTED) {
            await http.put(`/common/share-links/${shortCode}`, { status: SHARE_LINK_STATUS.EXPIRED });
            setShareLinkStatus(SHARE_LINK_STATUS.EXPIRED as ShareLinkStatus);
          }
        } else {
          const minutes = Math.floor(diff / 60000);
          const seconds = Math.floor((diff % 60000) / 1000);
          setTimeRemaining(`${minutes}分${seconds}秒`);
        }
      } catch {
        // ignore timer errors
      }
    };

    updateTimer();
    const timer = setInterval(updateTimer, 1000);

    return () => clearInterval(timer);
  }, [shortCode, shareLinkStatus]);

  const [plan, setPlan] = useState<ProductionPlan | WashingPlan | null>(null);
  const [yarns, setYarns] = useState<YarnRatio[]>([]);
  const [purchaserName, setPurchaserName] = useState('');
  const [purchaserCompanyId, setPurchaserCompanyId] = useState('');
  const [alreadyImported, setAlreadyImported] = useState(false);
  const [loading, setLoading] = useState(true);
  const [importing, setImporting] = useState(false);
  const [importSuccess, setImportSuccess] = useState(false);
  const [isWashingPlan, setIsWashingPlan] = useState(false);

  useEffect(() => {
    if (!planId) { setLoading(false); return; }
    fetchPlanData();
  }, [planId]);

  const fetchPlanData = async () => {
    try {
      const planRes = await http.get<any>(`/common/plans/${planId}`);
      const planData = planRes.data;

      if (planData && planData.type === 'production') {
        setPlan(planData);
        setIsWashingPlan(false);
        setPurchaserCompanyId(planData.purchaser_id);

        setYarns(planData.yarn_ratios || []);
        setPurchaserName(planData.purchaser_name || '未知');

        if (auth.company) {
          setAlreadyImported(!!planData.already_imported);
        }
      } else if (planData && planData.type === 'washing') {
        setPlan(planData);
        setIsWashingPlan(true);
        setPurchaserCompanyId(planData.company_id);
        setPurchaserName(planData.purchaser_name || '未知');

        if (auth.company) {
          setAlreadyImported(!!planData.already_imported);
        }
      } else if (planData) {
        setPlan(planData);
        setIsWashingPlan(false);
        setPurchaserCompanyId(planData.purchaser_id || planData.company_id);
        setPurchaserName(planData.purchaser_name || '未知');
        setYarns(planData.yarn_ratios || []);
        if (auth.company) {
          setAlreadyImported(!!planData.already_imported);
        }
      }
    } catch {
      // plan not found
    }
    setLoading(false);
  };

  // 确认导入（建立合作关系）
  const handleConfirm = async () => {
    if (!auth.company || !planId || !factoryType || !purchaserCompanyId) return;
    setImporting(true);

    try {
      await http.post(`/common/plans/${planId}/confirm`, {
        factory_id: auth.company.id,
        factory_type: factoryType,
        is_washing_plan: isWashingPlan,
        purchaser_company_id: purchaserCompanyId,
        short_code: shortCode || undefined
      });

      setImportSuccess(true);
      setImporting(false);
      setTimeout(() => { navigate(`/${auth.currentRole}/plans`); }, 2000);
    } catch (err) {
      handleError(err, { userMessage: '确认失败' });
      setImporting(false);
    }
  };

  // 拒绝计划
  const handleReject = async () => {
    if (!shortCode) return;

    setImporting(true);

    try {
      await http.put(`/common/share-links/${shortCode}`, {
        status: SHARE_LINK_STATUS.REJECTED,
        responded_at: new Date().toISOString(),
        response_result: 'rejected',
        reject_reason: rejectReason
      });
    } catch {
      // ignore
    }

    setImporting(false);
    setTimeout(() => { navigate('/role-select'); }, 2000);
  };

  // 等待解密完成
  if (decrypting) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 flex items-center justify-center">
        <p className="text-gray-500">加载中...</p>
      </div>
    );
  }

  // 链接已过期
  if (linkExpired || shareLinkStatus === 'expired') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 flex items-center justify-center p-4 relative overflow-hidden">
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-gradient-to-br from-amber-400/20 to-red-400/20 rounded-full blur-3xl animate-pulse" />
        <motion.div initial={{ opacity: 0, y: 30, scale: 0.95 }} animate={{ opacity: 1, y: 0, scale: 1 }} transition={{ duration: 0.6 }} className="bg-white/10 backdrop-blur-xl rounded-2xl p-6 md:p-8 max-w-sm md:max-w-md w-full text-center border border-white/20 shadow-2xl relative z-10">
          <div className="w-14 h-14 md:w-16 md:h-16 bg-gradient-to-br from-amber-500 to-orange-500 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-amber-500/30">
            <Clock className="w-7 h-7 md:w-8 md:h-8 text-white" />
          </div>
          <h2 className="text-lg md:text-xl font-bold text-white mb-2">链接已过期</h2>
          <p className="text-blue-200/70 mb-2 text-sm md:text-base">此分享链接已超过30分钟有效期</p>
          <p className="text-blue-200/50 mb-6 text-xs">请联系采购商重新生成分享链接</p>
          <motion.button whileHover={{ scale: isMobile ? 1 : 1.02 }} whileTap={{ scale: 0.98 }} onClick={() => navigate('/role-select')} className="w-full py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl hover:from-blue-600 hover:to-indigo-600 transition-all shadow-lg shadow-blue-500/30">返回首页</motion.button>
        </motion.div>
      </div>
    );
  }

  // 链接已确认
  if (shareLinkStatus === 'confirmed') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-green-50 to-emerald-50 flex items-center justify-center p-4">
        <motion.div initial={{ opacity: 0, y: 30 }} animate={{ opacity: 1, y: 0 }} className="bg-white/80 backdrop-blur rounded-2xl p-6 md:p-8 max-w-sm md:max-w-md w-full text-center border border-white/50 shadow-xl">
          <div className="w-14 h-14 md:w-16 md:h-16 bg-gradient-to-br from-green-500 to-emerald-500 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-green-500/30">
            <CheckCircle className="w-7 h-7 md:w-8 md:h-8 text-white" />
          </div>
          <h2 className="text-lg md:text-xl font-bold text-gray-800 mb-2">计划已确认</h2>
          <p className="text-gray-500 mb-6 text-sm md:text-base">您已确认此计划，合作关系已建立</p>
          <motion.button whileHover={{ scale: isMobile ? 1 : 1.02 }} whileTap={{ scale: 0.98 }} onClick={() => navigate(`/${auth.currentRole}/plans`)} className="w-full py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl shadow-lg shadow-blue-500/30">查看计划</motion.button>
        </motion.div>
      </div>
    );
  }

  // 链接已拒绝
  if (shareLinkStatus === 'rejected') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-red-50 to-rose-50 flex items-center justify-center p-4">
        <motion.div initial={{ opacity: 0, y: 30 }} animate={{ opacity: 1, y: 0 }} className="bg-white/80 backdrop-blur rounded-2xl p-6 md:p-8 max-w-sm md:max-w-md w-full text-center border border-white/50 shadow-xl">
          <div className="w-14 h-14 md:w-16 md:h-16 bg-gradient-to-br from-red-500 to-rose-500 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-red-500/30">
            <XCircle className="w-7 h-7 md:w-8 md:h-8 text-white" />
          </div>
          <h2 className="text-lg md:text-xl font-bold text-gray-800 mb-2">计划已拒绝</h2>
          <p className="text-gray-500 mb-6 text-sm md:text-base">您已拒绝此计划</p>
          <motion.button whileHover={{ scale: isMobile ? 1 : 1.02 }} whileTap={{ scale: 0.98 }} onClick={() => navigate('/role-select')} className="w-full py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl shadow-lg shadow-blue-500/30">返回首页</motion.button>
        </motion.div>
      </div>
    );
  }

  // 链接已取消
  if (shareLinkStatus === 'cancelled') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 flex items-center justify-center p-4 relative overflow-hidden">
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-gradient-to-br from-amber-400/20 to-red-400/20 rounded-full blur-3xl animate-pulse" />
        <motion.div initial={{ opacity: 0, y: 30, scale: 0.95 }} animate={{ opacity: 1, y: 0, scale: 1 }} transition={{ duration: 0.6 }} className="bg-white/10 backdrop-blur-xl rounded-2xl p-6 md:p-8 max-w-sm md:max-w-md w-full text-center border border-white/20 shadow-2xl relative z-10">
          <div className="w-14 h-14 md:w-16 md:h-16 bg-gradient-to-br from-amber-500 to-orange-500 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-amber-500/30">
            <AlertTriangle className="w-7 h-7 md:w-8 md:h-8 text-white" />
          </div>
          <h2 className="text-lg md:text-xl font-bold text-white mb-2">链接已失效</h2>
          <p className="text-blue-200/70 mb-6 text-sm md:text-base">此分享链接已被取消</p>
          <motion.button whileHover={{ scale: isMobile ? 1 : 1.02 }} whileTap={{ scale: 0.98 }} onClick={() => navigate('/role-select')} className="w-full py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl hover:from-blue-600 hover:to-indigo-600 transition-all shadow-lg shadow-blue-500/30">返回首页</motion.button>
        </motion.div>
      </div>
    );
  }

  // 角色匹配检查
  const roleMatches = auth.company && auth.currentRole === factoryType;
  const planTypeMatchesRole = isWashingPlan ? factoryType === 'washing' : factoryType === 'textile';

  // 未登录
  if (!auth.isLoggedIn) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 flex items-center justify-center p-4 relative overflow-hidden">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-gradient-to-br from-blue-400/20 to-purple-400/20 rounded-full blur-3xl animate-pulse" />
        <motion.div initial={{ opacity: 0, y: 30, scale: 0.95 }} animate={{ opacity: 1, y: 0, scale: 1 }} transition={{ duration: 0.6 }} className="bg-white/10 backdrop-blur-xl rounded-2xl p-6 md:p-8 max-w-sm md:max-w-md w-full text-center border border-white/20 shadow-2xl relative z-10">
          <div className="w-14 h-14 md:w-16 md:h-16 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-blue-500/30">
            <Link2 className="w-7 h-7 md:w-8 md:h-8 text-white" />
          </div>
          <h2 className="text-lg md:text-xl font-bold text-white mb-2">导入关联计划</h2>
          <p className="text-blue-200/70 mb-6 text-sm md:text-base">请先登录后再导入计划</p>
          <motion.button whileHover={{ scale: isMobile ? 1 : 1.02 }} whileTap={{ scale: 0.98 }} onClick={() => navigate('/login')} className="w-full py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl hover:from-blue-600 hover:to-indigo-600 transition-all shadow-lg shadow-blue-500/30">前往登录</motion.button>
        </motion.div>
      </div>
    );
  }

  // 角色不匹配
  if (!roleMatches && auth.company) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 flex items-center justify-center p-4 relative overflow-hidden">
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-gradient-to-br from-amber-400/20 to-red-400/20 rounded-full blur-3xl animate-pulse" />
        <motion.div initial={{ opacity: 0, y: 30, scale: 0.95 }} animate={{ opacity: 1, y: 0, scale: 1 }} transition={{ duration: 0.6 }} className="bg-white/10 backdrop-blur-xl rounded-2xl p-6 md:p-8 max-w-sm md:max-w-md w-full text-center border border-white/20 shadow-2xl relative z-10">
          <div className="w-14 h-14 md:w-16 md:h-16 bg-gradient-to-br from-amber-500 to-orange-500 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-amber-500/30">
            <AlertTriangle className="w-7 h-7 md:w-8 md:h-8 text-white" />
          </div>
          <h2 className="text-lg md:text-xl font-bold text-white mb-2">角色不匹配</h2>
          <p className="text-blue-200/70 mb-2 text-sm md:text-base">此链接是为{factoryType === 'textile' ? '纺织厂' : '水洗厂'}角色生成的</p>
          <p className="text-blue-200/70 mb-6 text-sm md:text-base">当前您的角色是：{auth.currentRole === 'purchaser' ? '采购商' : auth.currentRole === 'textile' ? '纺织厂' : '水洗厂'}</p>
          <motion.button whileHover={{ scale: isMobile ? 1 : 1.02 }} whileTap={{ scale: 0.98 }} onClick={() => navigate('/role-select')} className="w-full py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl hover:from-blue-600 hover:to-indigo-600 transition-all shadow-lg shadow-blue-500/30">切换角色</motion.button>
        </motion.div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 flex items-center justify-center">
        <p className="text-gray-500">加载中...</p>
      </div>
    );
  }

  if (!plan) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 flex items-center justify-center p-4">
        <motion.div initial={{ opacity: 0, y: 30 }} animate={{ opacity: 1, y: 0 }} className="bg-white/10 backdrop-blur-xl rounded-2xl p-6 md:p-8 max-w-sm md:max-w-md w-full text-center border border-white/20 shadow-2xl">
          <div className="w-14 h-14 md:w-16 md:h-16 bg-gradient-to-br from-red-500 to-rose-500 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-red-500/30">
            <AlertTriangle className="w-7 h-7 md:w-8 md:h-8 text-white" />
          </div>
          <h2 className="text-lg md:text-xl font-bold text-white mb-2">计划不存在</h2>
          <p className="text-blue-200/70 mb-6 text-sm md:text-base">该链接关联的计划可能已被删除</p>
          <motion.button whileHover={{ scale: isMobile ? 1 : 1.02 }} whileTap={{ scale: 0.98 }} onClick={() => navigate('/role-select')} className="w-full py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl shadow-lg shadow-blue-500/30">返回首页</motion.button>
        </motion.div>
      </div>
    );
  }

  // 导入成功
  if (importSuccess) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-green-50 to-emerald-50 flex items-center justify-center p-4">
        <motion.div initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} transition={{ type: 'spring' }} className="bg-white/80 backdrop-blur rounded-2xl p-6 md:p-8 max-w-sm md:max-w-md w-full text-center border border-white/50 shadow-xl">
          <motion.div initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ delay: 0.2, type: 'spring' }} className="w-14 h-14 md:w-16 md:h-16 bg-gradient-to-br from-green-500 to-emerald-500 rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg shadow-green-500/30">
            <CheckCircle className="w-7 h-7 md:w-8 md:h-8 text-white" />
          </motion.div>
          <h2 className="text-lg md:text-xl font-bold text-gray-800 mb-2">确认成功</h2>
          <p className="text-gray-500 mb-2 text-sm md:text-base">计划已确认，合作关系已建立</p>
          <p className="text-gray-400 mb-6 text-xs">即将跳转到计划总览...</p>
        </motion.div>
      </div>
    );
  }

  // 拒绝表单
  if (showRejectForm) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 p-4 md:p-8">
        <div className="max-w-2xl mx-auto">
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="bg-white/80 backdrop-blur rounded-2xl shadow-sm p-6 border border-white/50">
            <div className="flex items-center gap-3 mb-6">
              <div className="w-12 h-12 bg-gradient-to-br from-red-500 to-rose-500 rounded-xl flex items-center justify-center shadow-md">
                <XCircle className="w-6 h-6 text-white" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-gray-800">拒绝计划</h2>
                <p className="text-sm text-gray-500">请填写拒绝原因（可选）</p>
              </div>
            </div>
            
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">拒绝原因</label>
              <textarea
                value={rejectReason}
                onChange={(e) => setRejectReason(e.target.value)}
                placeholder="请输入拒绝原因，将反馈给采购商..."
                className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-red-500/20 focus:border-red-500 resize-none"
                rows={4}
              />
            </div>
            
            <div className="flex gap-3">
              <button
                onClick={() => setShowRejectForm(false)}
                className="flex-1 py-3 border border-gray-300 rounded-xl text-gray-700 hover:bg-gray-50 transition-colors font-medium"
              >
                返回
              </button>
              <button
                onClick={handleReject}
                disabled={importing}
                className="flex-1 py-3 bg-gradient-to-r from-red-500 to-rose-500 text-white rounded-xl hover:from-red-600 hover:to-rose-600 transition-all shadow-lg shadow-red-500/30 disabled:opacity-50 font-medium"
              >
                {importing ? '提交中...' : '确认拒绝'}
              </button>
            </div>
          </motion.div>
        </div>
      </div>
    );
  }

  // 正常导入确认页面（新流程：确认/拒绝）
  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 p-4 md:p-8">
      <div className="max-w-2xl md:max-w-4xl mx-auto">
        <motion.div variants={containerVariants} initial="hidden" animate="visible">
          <motion.div variants={itemVariants} className="flex items-center gap-3 md:gap-4 mb-6 md:mb-8">
            <button onClick={() => navigate('/role-select')} className="p-2 md:p-3 hover:bg-white/80 rounded-full transition-colors shadow-sm">
              <ArrowLeft className="w-6 h-6 md:w-7 md:h-7 text-gray-600" />
            </button>
            <h1 className="text-2xl md:text-3xl font-bold text-gray-800">计划确认</h1>
          </motion.div>

          {/* 倒计时提示 */}
          {shortCode && timeRemaining && (
            <motion.div variants={itemVariants} className={`rounded-2xl p-4 mb-6 flex items-center gap-3 border ${
              linkExpired ? 'bg-red-50 border-red-200' : 'bg-amber-50 border-amber-200'
            }`}>
              <Clock className={`w-5 h-5 ${linkExpired ? 'text-red-500' : 'text-amber-500'}`} />
              <div className="flex-1">
                <p className={`font-medium ${linkExpired ? 'text-red-700' : 'text-amber-700'}`}>
                  {linkExpired ? '链接已过期' : `链接有效期剩余：${timeRemaining}`}
                </p>
                <p className="text-xs text-gray-500">请在有效期内确认或拒绝此计划</p>
              </div>
            </motion.div>
          )}

          <motion.div variants={itemVariants} className="bg-white/80 backdrop-blur rounded-2xl shadow-sm p-4 md:p-6 mb-4 md:mb-6 border border-white/50">
            <div className="flex items-center gap-3 md:gap-4 mb-3 md:mb-4">
              <div className="w-12 h-12 md:w-14 md:h-14 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-xl flex items-center justify-center shadow-md">
                <Building2 className="w-6 h-6 md:w-7 md:h-7 text-white" />
              </div>
              <div>
                <p className="text-xs md:text-sm text-gray-500">来自采购商</p>
                <p className="font-semibold text-lg md:text-xl text-gray-800">{purchaserName}</p>
              </div>
            </div>
            <div className="bg-blue-50 rounded-xl p-3 border border-blue-100">
              <p className="text-sm text-blue-700">
                <span className="font-medium">首次合作确认</span> - 确认后将建立长期合作关系，后续计划可直接推送
              </p>
            </div>
          </motion.div>

          <motion.div variants={itemVariants} className="bg-white/80 backdrop-blur rounded-2xl shadow-sm p-4 md:p-6 mb-4 md:mb-6 border border-white/50">
            <h2 className="font-semibold text-lg md:text-xl text-gray-800 mb-4 md:mb-6">计划详情</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6 text-sm md:text-base">
              <div>
                <span className="text-gray-500 text-xs md:text-sm">计划编号</span>
                <p className="font-medium text-base md:text-lg text-gray-800">{plan.plan_code}</p>
              </div>
              <div>
                <span className="text-gray-500 text-xs md:text-sm">坯布识别码</span>
                <p className="font-medium text-base md:text-lg text-gray-800">{(plan as ProductionPlan).fabric_code}</p>
              </div>

              {!hideSensitive && (plan as ProductionPlan).product_name && (
                <div>
                  <span className="text-gray-500 text-xs md:text-sm">成品名称</span>
                  <p className="font-medium text-base md:text-lg text-gray-800">{(plan as ProductionPlan).product_name}</p>
                </div>
              )}
              {!hideSensitive && (plan as ProductionPlan).color && (
                <div>
                  <span className="text-gray-500 text-xs md:text-sm">颜色</span>
                  <p className="font-medium text-base md:text-lg text-gray-800">{(plan as ProductionPlan).color}</p>
                </div>
              )}
              {!hideSensitive && (plan as ProductionPlan).color_code && (
                <div>
                  <span className="text-gray-500 text-xs md:text-sm">色号</span>
                  <p className="font-medium text-base md:text-lg text-gray-800">{(plan as ProductionPlan).color_code}</p>
                </div>
              )}

              {isWashingPlan ? (
                <>
                  <div>
                    <span className="text-gray-500 text-xs md:text-sm">计划水洗米数</span>
                    <p className="font-medium text-base md:text-lg text-gray-800">{(plan as WashingPlan).planned_meters?.toLocaleString()} 米</p>
                  </div>
                  <div>
                    <span className="text-gray-500 text-xs md:text-sm">水洗单价</span>
                    <p className="font-medium text-base md:text-lg text-gray-800">¥{(plan as WashingPlan).washing_price}/米</p>
                  </div>
                </>
              ) : (
                <>
                  <div>
                    <span className="text-gray-500 text-xs md:text-sm">计划产量</span>
                    <p className="font-medium text-base md:text-lg text-gray-800">{(plan as ProductionPlan).target_quantity?.toLocaleString()} 米</p>
                  </div>
                  <div>
                    <span className="text-gray-500 text-xs md:text-sm">生产采购价</span>
                    <p className="font-medium text-base md:text-lg text-gray-800">¥{(plan as ProductionPlan).production_price}/米</p>
                  </div>
                </>
              )}
            </div>
          </motion.div>

          <motion.div variants={itemVariants} className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl p-4 md:p-5 mb-6 md:mb-8 flex items-center gap-3 md:gap-4 border border-blue-100">
            {factoryType === 'textile' ? (
              <Package className="w-5 h-5 md:w-6 md:h-6 text-blue-600" />
            ) : (
              <Droplet className="w-5 h-5 md:w-6 md:h-6 text-purple-600" />
            )}
            <p className="text-sm md:text-base text-blue-700">
              确认后，此计划将关联到您的{factoryType === 'textile' ? '纺织厂' : '水洗厂'}，
              并与<span className="font-medium">{purchaserName}</span>建立合作关系
            </p>
          </motion.div>

          <motion.div variants={itemVariants} className="flex gap-3 md:gap-4">
            <button
              onClick={() => setShowRejectForm(true)}
              className="flex-1 py-3 md:py-4 border border-red-300 text-red-600 rounded-xl hover:bg-red-50 transition-colors text-base md:text-lg font-medium"
            >
              拒绝
            </button>
            <motion.button
              whileHover={{ scale: isMobile ? 1 : 1.02 }}
              whileTap={{ scale: 0.98 }}
              onClick={handleConfirm}
              disabled={importing || linkExpired}
              className="flex-1 py-3 md:py-4 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl hover:from-blue-600 hover:to-indigo-600 transition-all shadow-lg shadow-blue-500/30 disabled:opacity-50 text-base md:text-lg font-medium"
            >
              {importing ? '确认中...' : '确认计划'}
            </motion.button>
          </motion.div>
        </motion.div>
      </div>
    </div>
  );
}
