import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, AlertTriangle, Package, Check, Loader2, Edit3, Search } from 'lucide-react';
import { http } from '../api';
import type { YarnRatio, YarnStock } from '../types';

interface YarnAllocation {
  yarnRatio: YarnRatio;
  allocatedYarn: YarnStock | null;
  requiredQuantity: number;
  availableQuantity: number;
  isSufficient: boolean;
  manualName?: string;
  manualQuantity?: number;
}

interface YarnAllocationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (allocations: YarnAllocation[]) => void;
  yarnRatios: YarnRatio[];
  companyId: string;
  planTargetQuantity: number;
  planId?: string;
}

export function YarnAllocationModal({
  isOpen,
  onClose,
  onConfirm,
  yarnRatios,
  companyId,
  planTargetQuantity,
  planId
}: YarnAllocationModalProps) {
  const [yarnStock, setYarnStock] = useState<YarnStock[]>([]);
  const [allocations, setAllocations] = useState<YarnAllocation[]>([]);
  const [loading, setLoading] = useState(true);
  const [confirming, setConfirming] = useState(false);
  const [isManualMode, setIsManualMode] = useState(false);
  const [autoMatchFailed, setAutoMatchFailed] = useState(false);

  useEffect(() => {
    if (isOpen && companyId) {
      fetchYarnStock();
    }
  }, [isOpen, companyId]);

  useEffect(() => {
    if (yarnStock.length > 0 && yarnRatios.length > 0) {
      calculateAllocations();
    }
  }, [yarnStock, yarnRatios]);

  const fetchYarnStock = async () => {
    setLoading(true);
    try {
      const res = await http.get<YarnStock[]>('/textile/yarn-stock', { company_id: companyId });
      setYarnStock(res.data || []);
    } catch {
      setYarnStock([]);
    }
    setLoading(false);
  };

  const calculateAllocations = () => {
    const newAllocations: YarnAllocation[] = yarnRatios.map(ratio => {
      const requiredQuantity = ratio.total_amount || 0;
      
      // 尝试匹配相同名称的纱线
      const matchingYarn = yarnStock.find(yarn => 
        yarn.name.toLowerCase().includes(ratio.yarn_name.toLowerCase()) ||
        ratio.yarn_name.toLowerCase().includes(yarn.name.toLowerCase())
      );
      
      const availableQuantity = matchingYarn?.quantity || 0;
      
      return {
        yarnRatio: ratio,
        allocatedYarn: matchingYarn || null,
        requiredQuantity,
        availableQuantity,
        isSufficient: availableQuantity >= requiredQuantity,
        manualName: ratio.yarn_name,
        manualQuantity: requiredQuantity
      };
    });
    
    setAllocations(newAllocations);
    
    // 检查是否有自动匹配失败的情况
    const hasUnmatched = newAllocations.some(a => !a.allocatedYarn);
    const hasInsufficient = newAllocations.some(a => a.allocatedYarn && !a.isSufficient);
    setAutoMatchFailed(hasUnmatched || hasInsufficient);
  };

  const handleYarnSelect = (ratioId: string, yarnId: string) => {
    const selectedYarn = yarnStock.find(y => y.id === yarnId);
    if (!selectedYarn) return;
    
    setAllocations(prev => prev.map(alloc => {
      if (alloc.yarnRatio.id === ratioId) {
        return {
          ...alloc,
          allocatedYarn: selectedYarn,
          availableQuantity: selectedYarn.quantity,
          isSufficient: selectedYarn.quantity >= alloc.requiredQuantity
        };
      }
      return alloc;
    }));
  };

  const handleManualNameChange = (ratioId: string, name: string) => {
    setAllocations(prev => prev.map(alloc => {
      if (alloc.yarnRatio.id === ratioId) {
        return { ...alloc, manualName: name };
      }
      return alloc;
    }));
  };

  const handleManualQuantityChange = (ratioId: string, quantity: string) => {
    const numQuantity = parseFloat(quantity) || 0;
    setAllocations(prev => prev.map(alloc => {
      if (alloc.yarnRatio.id === ratioId) {
        return { ...alloc, manualQuantity: numQuantity };
      }
      return alloc;
    }));
  };

  const handleConfirm = async () => {
    if (isManualMode) {
      // 手动模式：验证输入
      const emptyName = allocations.filter(a => !a.manualName?.trim());
      if (emptyName.length > 0) {
        alert('请为所有纱线输入名称');
        return;
      }

      const emptyQuantity = allocations.filter(a => !a.manualQuantity || a.manualQuantity <= 0);
      if (emptyQuantity.length > 0) {
        alert('请为所有纱线输入有效的重量');
        return;
      }
    } else {
      // 自动模式：检查是否所有纱线都有分配
      const unallocated = allocations.filter(a => !a.allocatedYarn);
      if (unallocated.length > 0) {
        alert(`请为以下纱线选择库存：${unallocated.map(a => a.yarnRatio.yarn_name).join(', ')}`);
        return;
      }

      // 检查库存是否足够
      const insufficient = allocations.filter(a => !a.isSufficient);
      if (insufficient.length > 0) {
        alert(
          `以下纱线库存不足，无法确认采纱：\n${insufficient.map(a =>
            `${a.yarnRatio.yarn_name}: 需要 ${a.requiredQuantity}kg，库存 ${a.availableQuantity}kg`
          ).join('\n')}\n\n请切换到手动分配模式或补充库存后再确认。`
        );
        return;
      }
    }

    // 计算实际消耗总量
    const totalConsumption = isManualMode
      ? allocations.reduce((sum, a) => sum + (a.manualQuantity || 0), 0)
      : allocations.reduce((sum, a) => sum + a.requiredQuantity, 0);

    // 显示确认对话框，包含实际消耗统计
    const confirmMessage = isManualMode
      ? `确认采纱完成？\n\n实际消耗统计：\n${allocations.map(a =>
          `${a.manualName}: ${a.manualQuantity}kg`
        ).join('\n')}\n\n总计消耗: ${totalConsumption}kg`
      : `确认采纱完成？\n\n实际消耗统计：\n${allocations.map(a =>
          `${a.yarnRatio.yarn_name}: ${a.requiredQuantity}kg`
        ).join('\n')}\n\n总计消耗: ${totalConsumption}kg`;

    if (!window.confirm(confirmMessage)) {
      return;
    }

    setConfirming(true);
    
    try {
      if (isManualMode) {
        for (const alloc of allocations) {
          const manualName = alloc.manualName!;
          const manualQty = alloc.manualQuantity!;

          const existingYarn = yarnStock.find(y =>
            y.name.toLowerCase() === manualName.toLowerCase()
          );

          if (existingYarn) {
            if (existingYarn.quantity >= manualQty) {
              const newQuantity = existingYarn.quantity - manualQty;
              await http.put(`/textile/yarn-stock/${existingYarn.id}`, { quantity: newQuantity });

              await http.post(`/textile/yarn-stock/${existingYarn.id}/records`, {
                change_type: 'outbound',
                quantity: manualQty,
                notes: `采纱出库 - 计划: ${planId || '未知'}`,
              });
            } else {
              alert(`纱线 "${manualName}" 库存不足，需要 ${manualQty}kg，库存 ${existingYarn.quantity}kg`);
              setConfirming(false);
              return;
            }
          } else {
            const res = await http.post<YarnStock>('/textile/yarn-stock', {
              company_id: companyId,
              name: manualName,
              quantity: -manualQty,
              unit: 'kg',
              min_stock: 0
            });
            const newYarn = res.data;

            if (newYarn) {
              await http.post(`/textile/yarn-stock/${newYarn.id}/records`, {
                change_type: 'outbound',
                quantity: manualQty,
                notes: `采纱出库(新纱线) - 计划: ${planId || '未知'}`,
              });
            }
          }
        }
      } else {
        for (const alloc of allocations) {
          if (alloc.allocatedYarn && alloc.isSufficient) {
            const newQuantity = alloc.allocatedYarn.quantity - alloc.requiredQuantity;
            await http.put(`/textile/yarn-stock/${alloc.allocatedYarn.id}`, { quantity: newQuantity });

            await http.post(`/textile/yarn-stock/${alloc.allocatedYarn.id}/records`, {
              change_type: 'outbound',
              quantity: alloc.requiredQuantity,
              notes: `采纱出库 - 计划: ${planId || '未知'}`,
            });
          }
        }
      }

      onConfirm(allocations);
      onClose();
    } catch (error) {
      console.error('库存扣减失败:', error);
      alert('库存扣减失败，请重试');
    } finally {
      setConfirming(false);
    }
  };

  const hasInsufficientYarn = allocations.some(a => !a.isSufficient && !isManualMode);
  const hasUnallocatedYarn = allocations.some(a => !a.allocatedYarn && !isManualMode);

  if (!isOpen) return null;

  return (
    <AnimatePresence>
      <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={onClose}
      >
        <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 }}
          className="bg-white rounded-2xl w-full max-w-lg shadow-xl overflow-hidden"
          onClick={e => e.stopPropagation()}
        >
          {/* 头部 */}
          <div className="bg-gradient-to-r from-emerald-500 to-teal-500 p-4 text-white">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Package className="w-5 h-5" />
                <h2 className="text-lg font-semibold">
                  {isManualMode ? '手动纱线分配' : '纱线分配确认'}
                </h2>
              </div>
              <button
                onClick={onClose}
                className="p-2 hover:bg-white/20 rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <p className="text-sm text-white/80 mt-1">
              计划产量: {planTargetQuantity}米 | {isManualMode ? '请手动输入纱线信息' : '请确认纱线库存分配'}
            </p>
          </div>

          {/* 模式切换按钮 */}
          {!loading && allocations.length > 0 && (
            <div className="px-4 pt-4">
              <div className="flex gap-2">
                <button
                  onClick={() => setIsManualMode(false)}
                  className={`flex-1 py-2 px-3 rounded-lg text-sm font-medium transition-colors flex items-center justify-center gap-2 ${
                    !isManualMode 
                      ? 'bg-emerald-100 text-emerald-700 border border-emerald-300' 
                      : 'bg-gray-100 text-gray-600 border border-gray-200'
                  }`}
                >
                  <Search className="w-4 h-4" />
                  自动匹配
                </button>
                <button
                  onClick={() => setIsManualMode(true)}
                  className={`flex-1 py-2 px-3 rounded-lg text-sm font-medium transition-colors flex items-center justify-center gap-2 ${
                    isManualMode 
                      ? 'bg-blue-100 text-blue-700 border border-blue-300' 
                      : 'bg-gray-100 text-gray-600 border border-gray-200'
                  }`}
                >
                  <Edit3 className="w-4 h-4" />
                  手动分配
                </button>
              </div>
              {autoMatchFailed && !isManualMode && (
                <div className="mt-2 p-2 bg-amber-50 border border-amber-200 rounded-lg">
                  <p className="text-xs text-amber-700 flex items-center gap-1">
                    <AlertTriangle className="w-3 h-3" />
                    自动匹配失败，建议切换到手动分配模式
                  </p>
                </div>
              )}
            </div>
          )}

          {/* 内容 */}
          <div className="p-4 max-h-[60vh] overflow-y-auto">
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="w-6 h-6 animate-spin text-emerald-500" />
                <span className="ml-2 text-gray-500">加载库存数据...</span>
              </div>
            ) : allocations.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <AlertTriangle className="w-12 h-12 mx-auto mb-3 text-amber-400" />
                <p>该计划没有纱线配比数据</p>
              </div>
            ) : isManualMode ? (
              /* 手动分配模式 */
              <div className="space-y-3">
                {allocations.map((alloc, index) => (
                  <div
                    key={alloc.yarnRatio.id}
                    className="border border-blue-200 bg-blue-50/30 rounded-xl p-3"
                  >
                    <div className="mb-2">
                      <h3 className="font-medium text-gray-800">
                        {index + 1}. 所需纱线
                      </h3>
                      <p className="text-xs text-gray-500">
                        计划配比: {alloc.yarnRatio.yarn_name} | 
                        计划用量: {alloc.requiredQuantity}kg
                      </p>
                    </div>

                    {/* 手动输入纱线名称 */}
                    <div className="mt-2">
                      <label className="text-xs text-gray-600 mb-1 block font-medium">
                        实际使用纱线名称
                      </label>
                      <input
                        type="text"
                        value={alloc.manualName || ''}
                        onChange={(e) => handleManualNameChange(alloc.yarnRatio.id, e.target.value)}
                        placeholder="输入纱线名称"
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      />
                    </div>

                    {/* 手动输入重量 */}
                    <div className="mt-2">
                      <label className="text-xs text-gray-600 mb-1 block font-medium">
                        实际使用重量 (kg)
                      </label>
                      <input
                        type="number"
                        value={alloc.manualQuantity || ''}
                        onChange={(e) => handleManualQuantityChange(alloc.yarnRatio.id, e.target.value)}
                        placeholder="输入重量"
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      />
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              /* 自动分配模式 */
              <div className="space-y-3">
                {allocations.map((alloc, index) => (
                  <div
                    key={alloc.yarnRatio.id}
                    className={`border rounded-xl p-3 ${
                      alloc.isSufficient 
                        ? 'border-emerald-200 bg-emerald-50/30' 
                        : alloc.allocatedYarn 
                          ? 'border-red-200 bg-red-50/30'
                          : 'border-amber-200 bg-amber-50/30'
                    }`}
                  >
                    <div className="flex items-start justify-between mb-2">
                      <div>
                        <h3 className="font-medium text-gray-800">
                          {index + 1}. {alloc.yarnRatio.yarn_name}
                        </h3>
                        <p className="text-xs text-gray-500">
                          配比: {Number(alloc.yarnRatio.ratio).toFixed(0)}% | 
                          每米用量: {alloc.yarnRatio.amount_per_meter}g/m |
                          总需: {alloc.requiredQuantity}kg
                        </p>
                      </div>
                      {!alloc.allocatedYarn ? (
                        <span className="text-xs bg-amber-100 text-amber-600 px-2 py-0.5 rounded-full">
                          未匹配
                        </span>
                      ) : !alloc.isSufficient ? (
                        <span className="text-xs bg-red-100 text-red-600 px-2 py-0.5 rounded-full">
                          库存不足
                        </span>
                      ) : (
                        <span className="text-xs bg-emerald-100 text-emerald-600 px-2 py-0.5 rounded-full">
                          匹配成功
                        </span>
                      )}
                    </div>

                    {/* 纱线选择 */}
                    <div className="mt-2">
                      <label className="text-xs text-gray-500 mb-1 block">
                        选择库存纱线
                      </label>
                      <select
                        value={alloc.allocatedYarn?.id || ''}
                        onChange={(e) => handleYarnSelect(alloc.yarnRatio.id, e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
                      >
                        <option value="">请选择纱线...</option>
                        {yarnStock.map(yarn => (
                          <option key={yarn.id} value={yarn.id}>
                            {yarn.name} {yarn.spec ? `(${yarn.spec})` : ''} - 
                            库存: {yarn.quantity}kg
                          </option>
                        ))}
                      </select>
                    </div>

                    {/* 库存状态 */}
                    {alloc.allocatedYarn && (
                      <div className="mt-2 flex items-center gap-2 text-xs">
                        <span className={alloc.isSufficient ? 'text-emerald-600' : 'text-red-600'}>
                          {alloc.isSufficient ? (
                            <span className="flex items-center gap-1">
                              <Check className="w-3 h-3" />
                              库存充足 ({alloc.availableQuantity}kg)
                            </span>
                          ) : (
                            <span className="flex items-center gap-1">
                              <AlertTriangle className="w-3 h-3" />
                              库存不足 (缺 {alloc.requiredQuantity - alloc.availableQuantity}kg)
                            </span>
                          )}
                        </span>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}

            {/* 提示信息 */}
            {hasInsufficientYarn && !isManualMode && (
              <div className="mt-4 p-3 bg-amber-50 border border-amber-200 rounded-lg">
                <div className="flex items-start gap-2">
                  <AlertTriangle className="w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5" />
                  <p className="text-xs text-amber-700">
                    部分纱线库存不足或匹配失败，建议切换到手动分配模式。
                  </p>
                </div>
              </div>
            )}
          </div>

          {/* 底部按钮 */}
          <div className="p-4 border-t border-gray-100 flex gap-3">
            <button
              onClick={onClose}
              className="flex-1 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm font-medium"
            >
              取消
            </button>
            <motion.button
              whileTap={{ scale: 0.98 }}
              onClick={handleConfirm}
              disabled={confirming || allocations.length === 0}
              className={`flex-1 py-2.5 text-white rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium flex items-center justify-center gap-2 ${
                isManualMode 
                  ? 'bg-blue-500 hover:bg-blue-600' 
                  : 'bg-emerald-500 hover:bg-emerald-600'
              }`}
            >
              {confirming ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  确认中...
                </>
              ) : (
                <>
                  <Check className="w-4 h-4" />
                  {isManualMode ? '确认手动分配' : '确认采纱'}
                </>
              )}
            </motion.button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
