import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { washingApi, http } from '../../api';
import { motion, AnimatePresence } from 'framer-motion';
import { ChevronDown, ChevronRight, ArrowLeft, Link2, Clipboard, Check, Loader2, X, Droplets, Package, Clock } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import { extractParamsFromLink } from '../../utils/helpers';
import { useErrorHandler } from '../../hooks/useErrorHandler';
import { WASHING_PLAN_STATUS } from '../../utils/constants';
import type { WashingPlan, WashingProcessStep, Company, Profile } from '../../types';

interface WashingPlanWithDetails extends WashingPlan {
  product_name?: string;
  product_color?: string;
  fabric_code?: string;
  purchaser_name?: string;
  processSteps: WashingProcessStep[];
}

interface PlanGroup {
  purchaserId: string;
  purchaserName: string;
  plans: WashingPlanWithDetails[];
}

const statusMap: Record<string, { label: string; color: string }> = {
  pending: { label: '待处理', color: 'bg-amber-100 text-amber-700' },
  processing: { label: '处理中', color: 'bg-purple-100 text-purple-700' },
  completed: { label: '已完成', color: 'bg-green-100 text-green-700' }
};

const stepNames: Record<string, string> = {
  confirm: '确认计划',
  start_washing: '开始水洗',
  complete: '拆布打匹/件出库'
};

export function WashingPlanOverview() {
  const navigate = useNavigate();
  const { auth } = useAuth();
  const { isMobile } = useResponsive();
  const handleError = useErrorHandler();
  const [groups, setGroups] = useState<PlanGroup[]>([]);
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
  const [expandedPlan, setExpandedPlan] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [confirming, setConfirming] = useState<string | null>(null);
  const [importLink, setImportLink] = useState('');
  const [operatorNames, setOperatorNames] = useState<Record<string, string>>({});
  const [completeModalOpen, setCompleteModalOpen] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<WashingPlanWithDetails | null>(null);
  const [completeForm, setCompleteForm] = useState({
    rolls: '',
    meters: '',
    shrinkageRate: ''
  });

  useEffect(() => {
    if (!auth.company) return;
    fetchPlans();
  }, [auth.company]);

  const fetchPlans = async () => {
    setLoading(true);

    try {
      const response = await washingApi.listPlans();
      const washingPlans = response.data || [];

      if (washingPlans.length === 0) {
        setGroups([]);
        setLoading(false);
        return;
      }

      const planIds = washingPlans.map(p => p.id);

      let stepsData: any[] = [];
      try {
        const { data } = await http.get<any[]>('/washing/process-steps', { plan_ids: planIds.join(',') });
        stepsData = data || [];
      } catch {}

      const operatorIds = [...new Set(stepsData.filter(s => s.operator_id).map(s => s.operator_id))] as string[];
      if (operatorIds.length > 0) {
        try {
          const { data: profilesData } = await http.get<any[]>('/common/profiles', { ids: operatorIds.join(',') });
          const names: Record<string, string> = {};
          (profilesData || []).forEach(p => { names[p.id] = p.username; });
          setOperatorNames(names);
        } catch {}
      }

      const grouped: Record<string, PlanGroup> = {};
      washingPlans.forEach((plan: any) => {
        const purchaserId = plan.company_id;
        const purchaserName = plan.purchaser_name || plan.company?.name || '未知采购商';

        if (!grouped[purchaserId]) {
          grouped[purchaserId] = { purchaserId, purchaserName, plans: [] };
        }

        const processSteps = stepsData
          .filter(s => s.washing_plan_id === plan.id)
          .sort((a, b) => {
            const order = ['confirm', 'start_washing', 'complete'];
            return order.indexOf(a.step_type) - order.indexOf(b.step_type);
          });

        grouped[purchaserId].plans.push({
          ...plan,
          product_name: plan.product_name || plan.product?.product_name,
          product_color: plan.product_color || plan.product?.color,
          fabric_code: plan.fabric_code || plan.product?.fabric_code,
          purchaser_name: purchaserName,
          processSteps
        });
      });

      const groupList = Object.values(grouped);
      setGroups(groupList);
      if (groupList.length > 0) {
        setExpandedGroups(new Set([groupList[0].purchaserId]));
      }
    } catch (err) {
      handleError(err, { userMessage: '获取水洗计划失败' });
    }
    setLoading(false);
  };

  const toggleGroup = (id: string) => {
    setExpandedGroups(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const handleImportFromLink = () => {
    if (!importLink.trim()) return;

    const { token, plan, type, shortCode } = extractParamsFromLink(importLink);

    if (shortCode) {
      navigate(`/import?s=${shortCode}`);
    } else if (token) {
      navigate(`/import?token=${token}`);
    } else if (plan && type) {
      navigate(`/import?plan=${plan}&type=${type}`);
    } else {
      handleError(new Error('无效的链接格式'), { userMessage: '无效的链接格式，请确保链接包含 token、s 或 plan 参数', showAlert: true });
    }
  };

  const handlePasteFromClipboard = async () => {
    try {
      const text = await navigator.clipboard.readText();
      if (text.includes('/import?') || text.includes('#/import?')) {
        setImportLink(text);
        const { token, plan, type, shortCode } = extractParamsFromLink(text);

        if (shortCode) {
          navigate(`/import?s=${shortCode}`);
        } else if (token) {
          navigate(`/import?token=${token}`);
        } else if (plan && type) {
          navigate(`/import?plan=${plan}&type=${type}`);
        } else {
          handleError(new Error('链接格式不正确'), { userMessage: '链接格式不正确，请检查链接是否完整', showAlert: true });
        }
      } else {
        handleError(new Error('无效链接'), { userMessage: '剪贴板中没有检测到有效的导入链接', showAlert: true });
      }
    } catch (err) {
      handleError(err, { userMessage: '无法读取剪贴板，请手动粘贴链接', showAlert: true });
    }
  };

  // 确认流程步骤
  const handleConfirmStep = async (stepId: string, stepType: string) => {
    setConfirming(stepId);

    try {
      const plan = groups.flatMap(g => g.plans).find(
        p => p.processSteps.some(s => s.id === stepId)
      );
      if (!plan) { setConfirming(null); return; }

      if (stepType === 'confirm') {
        await washingApi.updatePlanStatus(plan.id, { status: WASHING_PLAN_STATUS.IN_PROGRESS });
      } else if (stepType === 'complete') {
        await washingApi.updatePlanStatus(plan.id, { status: WASHING_PLAN_STATUS.COMPLETED });
      }

      await http.patch(`/washing/process-steps/${stepId}`, {
        status: WASHING_PLAN_STATUS.COMPLETED,
        timestamp: new Date().toISOString(),
        operator_id: auth.user?.id
      });

      await fetchPlans();
    } catch (err) {
      handleError(err, { userMessage: '确认失败，请重试', showAlert: true });
    }
    setConfirming(null);
  };

  // 打开完成弹窗
  const openCompleteModal = (plan: WashingPlanWithDetails) => {
    setSelectedPlan(plan);
    setCompleteForm({
      rolls: '',
      meters: plan.estimated_washed_meters?.toString() || '',
      shrinkageRate: plan.estimated_shrinkage_rate?.toString() || ''
    });
    setCompleteModalOpen(true);
  };

  // 提交完成
  const handleCompleteSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedPlan || !auth.user) return;

    try {
      await washingApi.completePlan(selectedPlan.id, {
        actual_washed_meters: parseFloat(completeForm.meters),
        actual_shrinkage_rate: parseFloat(completeForm.shrinkageRate),
        rolls: parseInt(completeForm.rolls) || 0,
        washing_date: new Date().toISOString().split('T')[0],
      } as any);

      setCompleteModalOpen(false);
      setSelectedPlan(null);
      await fetchPlans();
      alert('水洗完成记录已保存！');
    } catch (err: any) {
      handleError(err, { userMessage: '保存失败: ' + err.message, showAlert: true });
    }
  };

  // 渲染流程节点
  const renderProcessSteps = (plan: WashingPlanWithDetails) => {
    const steps = plan.processSteps;
    const stepOrder = ['confirm', 'start_washing', 'complete'];
    
    return (
      <div className="mt-4 space-y-3">
        {stepOrder.map((stepType, index) => {
          const step = steps.find(s => s.step_type === stepType);
          const isCompleted = step?.status === 'completed';
          const isActive = step?.status === 'active' || (step?.status === 'pending' && 
            (index === 0 || steps.some(s => s.step_type === stepOrder[index - 1] && s.status === 'completed')));
          
          return (
            <div key={stepType} className="flex items-start gap-3">
              <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                isCompleted ? 'bg-green-500 text-white' :
                isActive ? 'bg-purple-500 text-white' : 'bg-gray-200 text-gray-400'
              }`}>
                {isCompleted ? <Check className="w-4 h-4" /> : index + 1}
              </div>
              <div className="flex-1">
                <div className="flex items-center justify-between">
                  <p className={`font-medium ${isCompleted ? 'text-green-700' : isActive ? 'text-purple-700' : 'text-gray-500'}`}>
                    {stepNames[stepType]}
                  </p>
                  {step?.timestamp && (
                    <span className="text-xs text-gray-400">
                      {new Date(step.timestamp).toLocaleString('zh-CN')}
                    </span>
                  )}
                </div>
                {step?.operator_id && operatorNames[step.operator_id] && (
                  <p className="text-xs text-gray-500 mt-1">
                    操作人: {operatorNames[step.operator_id]}
                  </p>
                )}
                {isActive && step && (
                  <button
                    onClick={() => handleConfirmStep(step.id, stepType)}
                    disabled={confirming === step.id}
                    className="mt-2 px-3 py-1 bg-purple-500 text-white text-xs rounded-lg hover:bg-purple-600 disabled:opacity-50"
                  >
                    {confirming === step.id ? '确认中...' : '确认'}
                  </button>
                )}
                {stepType === 'complete' && plan.status === 'processing' && !step && (
                  <button
                    onClick={() => openCompleteModal(plan)}
                    className="mt-2 px-3 py-1 bg-green-500 text-white text-xs rounded-lg hover:bg-green-600"
                  >
                    完成水洗
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-purple-50/30 to-violet-50/30">
      {/* Header - 与 Dashboard 一致 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-gray-200/50 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 md:px-8 py-4 flex items-center gap-3">
          <button
            onClick={() => navigate('/washing')}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5 text-gray-600" />
          </button>
          <div>
            <h1 className="text-lg font-bold text-gray-900">计划总览</h1>
            <p className="text-xs text-gray-500">查看和管理水洗计划</p>
          </div>
        </div>
      </header>

      <div className="p-3 sm:p-4 md:p-6 max-w-6xl mx-auto">

        {/* 导入链接区域 */}
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
          className="bg-white rounded-xl shadow-sm border border-gray-200 p-3 sm:p-4 mb-4 sm:mb-5 md:mb-6"
        >
          <div className="flex items-center justify-between mb-2 sm:mb-3">
            <h2 className="font-semibold text-gray-800 flex items-center gap-2 text-sm sm:text-base">
              <Link2 className="w-4 h-4 sm:w-5 sm:h-5 text-purple-600" />
              导入关联计划
            </h2>
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={handlePasteFromClipboard}
              className="flex items-center gap-1 px-2 sm:px-3 py-1 sm:py-1.5 text-xs sm:text-sm text-purple-600 hover:bg-purple-50 rounded-lg transition-colors will-change-transform"
            >
              <Clipboard className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
              识别剪贴板
            </motion.button>
          </div>
          <div className="flex gap-2">
            <input
              type="text"
              value={importLink}
              onChange={(e) => setImportLink(e.target.value)}
              placeholder="粘贴采购商分享的链接..."
              className="flex-1 px-3 sm:px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-xs sm:text-sm"
            />
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={handleImportFromLink}
              disabled={!importLink.trim()}
              className="px-3 sm:px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed text-xs sm:text-sm font-medium will-change-transform"
            >
              导入
            </motion.button>
          </div>
        </motion.div>

        {loading ? (
          <div className="flex flex-col items-center justify-center py-12 sm:py-16">
            <motion.div
              animate={{ rotate: 360 }}
              transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}
              className="w-6 h-6 sm:w-8 sm:h-8 border-2 border-purple-500 border-t-transparent rounded-full mb-3"
            />
            <p className="text-gray-400 text-sm">加载中...</p>
          </div>
        ) : groups.length === 0 ? (
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-center py-12 sm:py-16 text-gray-400"
          >
            <Droplets className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p className="mb-2 text-sm sm:text-base">暂无关联计划</p>
            <p className="text-xs sm:text-sm text-gray-400">请使用上方输入框粘贴采购商分享的链接</p>
          </motion.div>
        ) : (
          <div className="space-y-3 sm:space-y-4">
            {groups.map((group, groupIndex) => (
              <motion.div
                key={group.purchaserId}
                initial={{ opacity: 0, y: 15 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: groupIndex * 0.08, duration: 0.35 }}
                className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden"
              >
                <motion.div
                  onClick={() => toggleGroup(group.purchaserId)}
                  whileTap={{ scale: 0.995 }}
                  className="flex items-center justify-between p-3 sm:p-4 cursor-pointer hover:bg-gray-50 transition-colors will-change-transform"
                >
                  <div className="flex items-center gap-2 sm:gap-3">
                    <motion.button
                      animate={{ rotate: expandedGroups.has(group.purchaserId) ? 90 : 0 }}
                      transition={{ duration: 0.2 }}
                      className="p-1 rounded hover:bg-gray-200 will-change-transform"
                    >
                      <ChevronRight size={18} className="sm:w-5 sm:h-5" />
                    </motion.button>
                    <div>
                      <h3 className="font-semibold text-gray-800 text-sm sm:text-base">{group.purchaserName}</h3>
                      <span className="text-xs sm:text-sm text-gray-500">计划 ({group.plans.length})</span>
                    </div>
                  </div>
                </motion.div>
                <AnimatePresence>
                  {expandedGroups.has(group.purchaserId) && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: 'auto', opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      transition={{ duration: 0.3, ease: [0.25, 0.46, 0.45, 0.94] }}
                      className="border-t border-gray-100"
                    >
                      <div className="p-3 sm:p-4 space-y-3 sm:space-y-4">
                        {group.plans.map((plan, planIndex) => (
                          <motion.div
                            key={plan.id}
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: planIndex * 0.05, duration: 0.3 }}
                            className="border border-gray-200 rounded-lg overflow-hidden"
                          >
                            <motion.div
                              onClick={() => setExpandedPlan(expandedPlan === plan.id ? null : plan.id)}
                              whileTap={{ scale: 0.995 }}
                              className="p-3 sm:p-4 cursor-pointer hover:bg-gray-50 transition-colors will-change-transform"
                            >
                              <div className="flex items-start justify-between gap-2">
                                <div className="min-w-0 flex-1">
                                  <div className="flex items-center gap-2 mb-1.5 sm:mb-2">
                                    <span className={`px-2 py-0.5 sm:py-1 text-[10px] sm:text-xs rounded-full ${statusMap[plan.status]?.color || 'bg-gray-100'}`}>
                                      {statusMap[plan.status]?.label || plan.status}
                                    </span>
                                    <span className="text-[10px] sm:text-xs text-gray-400">{plan.plan_code}</span>
                                  </div>
                                  <p className="text-xs sm:text-sm text-gray-600 truncate">
                                    {plan.product_name} - {plan.product_color}
                                  </p>
                                  <p className="text-[10px] sm:text-xs text-gray-400">{plan.fabric_code}</p>
                                </div>
                                <div className="text-right text-xs sm:text-sm text-gray-600 flex-shrink-0">
                                  <p>计划: {plan.planned_meters}米</p>
                                  {plan.status === 'completed' && (
                                    <p className="text-green-600">洗后: {plan.actual_washed_meters}米</p>
                                  )}
                                </div>
                              </div>
                            </motion.div>
                            <AnimatePresence>
                              {expandedPlan === plan.id && (
                                <motion.div
                                  initial={{ height: 0, opacity: 0 }}
                                  animate={{ height: 'auto', opacity: 1 }}
                                  exit={{ height: 0, opacity: 0 }}
                                  transition={{ duration: 0.25 }}
                                  className="border-t border-gray-100 p-3 sm:p-4 bg-gray-50"
                                >
                                  <h5 className="font-medium mb-3 sm:mb-4 flex items-center gap-2 text-sm">
                                    <Clock className="w-4 h-4 text-purple-600" />
                                    水洗记录
                                  </h5>
                                  {renderProcessSteps(plan)}
                                </motion.div>
                              )}
                            </AnimatePresence>
                          </motion.div>
                        ))}
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
            ))}
          </div>
        )}
      </div>

      {/* 完成水洗弹窗 */}
      <AnimatePresence>
        {completeModalOpen && selectedPlan && (
          <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"
            onClick={() => setCompleteModalOpen(false)}
          >
            <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-md shadow-xl"
              onClick={e => e.stopPropagation()}
            >
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold text-gray-800">完成水洗</h3>
                <button
                  onClick={() => setCompleteModalOpen(false)}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <X className="w-5 h-5 text-gray-400" />
                </button>
              </div>
              
              <div className="bg-purple-50 rounded-lg p-3 mb-4">
                <p className="text-sm text-purple-700">
                  <span className="font-medium">{selectedPlan.product_name}</span> - {selectedPlan.product_color}
                </p>
                <p className="text-xs text-purple-600 mt-1">
                  计划米数: {selectedPlan.planned_meters}米
                </p>
              </div>

              <form onSubmit={handleCompleteSubmit} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      <Package className="w-4 h-4 inline mr-1" />
                      匹/件数 *
                    </label>
                    <input
                      type="number"
                      required
                      value={completeForm.rolls}
                      onChange={e => setCompleteForm({ ...completeForm, rolls: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                      placeholder="输入匹/件数"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      <Droplets className="w-4 h-4 inline mr-1" />
                      洗后米数 *
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      required
                      value={completeForm.meters}
                      onChange={e => setCompleteForm({ ...completeForm, meters: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                      placeholder="输入米数"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    实际缩水率 (%)
                  </label>
                  <input
                    type="number"
                    step="0.01"
                    required
                    value={completeForm.shrinkageRate}
                    onChange={e => setCompleteForm({ ...completeForm, shrinkageRate: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                    placeholder="输入缩水率"
                  />
                </div>

                <div className="flex gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => setCompleteModalOpen(false)}
                    className="flex-1 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 text-sm font-medium transition-colors"
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    className="flex-1 py-2 bg-gradient-to-r from-purple-500 to-violet-500 text-white rounded-lg hover:from-purple-600 hover:to-violet-600 text-sm font-medium transition-colors"
                  >
                    确认完成
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
