import React, { useState, useEffect } from 'react';
import { ArrowLeft, Package, ChevronDown, ChevronUp, List } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { textileApi, http } from '../../api';
import { motion, AnimatePresence } from 'framer-motion';
import { InventoryRecordsModal } from '../../components/InventoryRecordsModal';

interface FabricInventory {
 id: string;
 plan_id: string;
 fabric_code: string;
 plan_code: string;
 weight: number;
 target_quantity: number;
 completed_quantity: number;
 in_records: { time: string; quantity: number; rolls: number }[];
}

// 示例数据 - 用于展示参考
const demoInventory: FabricInventory[] = [
  {
    id: 'demo-1',
    plan_id: 'plan-1',
    fabric_code: 'SX1',
    plan_code: 'PLAN-2026-199465',
    weight: 280,
    target_quantity: 10000,
    completed_quantity: 7400,
    in_records: [
      { time: '2026-05-23T15:30:00Z', quantity: 1800, rolls: 20 },
      { time: '2026-05-22T09:15:00Z', quantity: 1350, rolls: 15 },
      { time: '2026-05-21T14:20:00Z', quantity: 1250, rolls: 14 },
      { time: '2026-05-20T11:00:00Z', quantity: 1500, rolls: 17 },
      { time: '2026-05-19T16:30:00Z', quantity: 1500, rolls: 16 }
    ]
  },
  {
    id: 'demo-2',
    plan_id: 'plan-2',
    fabric_code: 'SX1',
    plan_code: 'PLAN-2026-199466',
    weight: 280,
    target_quantity: 8000,
    completed_quantity: 5760,
    in_records: [
      { time: '2026-05-22T16:00:00Z', quantity: 1620, rolls: 18 },
      { time: '2026-05-20T11:30:00Z', quantity: 1260, rolls: 14 },
      { time: '2026-05-18T09:00:00Z', quantity: 1440, rolls: 16 },
      { time: '2026-05-16T14:00:00Z', quantity: 1440, rolls: 16 }
    ]
  },
  {
    id: 'demo-3',
    plan_id: 'plan-3',
    fabric_code: 'ZT320',
    plan_code: 'PLAN-2026-199460',
    weight: 320,
    target_quantity: 5000,
    completed_quantity: 4500,
    in_records: [
      { time: '2026-05-21T10:00:00Z', quantity: 2250, rolls: 25 },
      { time: '2026-05-19T15:30:00Z', quantity: 1125, rolls: 12 },
      { time: '2026-05-17T11:00:00Z', quantity: 1125, rolls: 13 }
    ]
  },
  {
    id: 'demo-4',
    plan_id: 'plan-4',
    fabric_code: 'CM180',
    plan_code: 'PLAN-2026-199458',
    weight: 180,
    target_quantity: 6000,
    completed_quantity: 3600,
    in_records: [
      { time: '2026-05-20T09:00:00Z', quantity: 1800, rolls: 20 },
      { time: '2026-05-18T14:30:00Z', quantity: 900, rolls: 10 },
      { time: '2026-05-16T10:00:00Z', quantity: 900, rolls: 10 }
    ]
  }
];

export function FabricWarehouse() {
 const navigate = useNavigate();
 const { auth } = useAuth();
 const [inventory, setInventory] = useState<FabricInventory[]>([]);
 const [loading, setLoading] = useState(true);
 const [expandedItems, setExpandedItems] = useState<Record<string, boolean>>({});
 const [recordsModalOpen, setRecordsModalOpen] = useState(false);
 const [selectedRecords, setSelectedRecords] = useState<any[]>([]);
 const [selectedPlanCode, setSelectedPlanCode] = useState('');

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

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

 try {
   const response = await textileApi.listPlans();
   const plansData = response.data || [];

   if (plansData.length === 0) {
     setInventory(demoInventory);
     setLoading(false);
     return;
   }

   const planIds = plansData.map(p => p.id);
   const purchaserIds = [...new Set(plansData.map(p => p.purchaser_id))];

   const [productsRes, ...inventoryResults] = await Promise.all([
     http.get<any[]>('/common/products', { company_ids: purchaserIds.join(',') }),
     ...planIds.map(id => textileApi.listInventory(id).catch(() => []))
   ]);

   const productWeightMap: Record<string, number> = {};
   (productsRes.data || []).forEach((p: any) => {
     productWeightMap[p.fabric_code] = p.weight;
   });

   const recordsByPlan: Record<string, { time: string; quantity: number; rolls: number }[]> = {};
   planIds.forEach((id, index) => {
     const records = inventoryResults[index] as any[] || [];
     recordsByPlan[id] = records.map((r: any) => ({
       time: r.created_at,
       quantity: Number(r.quantity) || 0,
       rolls: Number(r.rolls) || 0
     }));
   });

   const inventoryList: FabricInventory[] = plansData.map(plan => {
     const records = recordsByPlan[plan.id] || [];
     const totalInFromRecords = records.reduce((sum, r) => sum + r.quantity, 0);

     const completedQty = totalInFromRecords > 0 ? totalInFromRecords : (plan.completed_quantity || 0);

     return {
       id: plan.id,
       plan_id: plan.id,
       fabric_code: plan.fabric_code,
       plan_code: plan.plan_code,
       weight: productWeightMap[plan.fabric_code] || 0,
       target_quantity: plan.target_quantity,
       completed_quantity: completedQty,
       in_records: records
     };
   });

   setInventory(inventoryList.length > 0 ? inventoryList : demoInventory);
 } catch {
   setInventory(demoInventory);
 }

 setLoading(false);
 };

 const toggleExpand = (planId: string) => {
 setExpandedItems(prev => ({
 ...prev,
 [planId]: !prev[planId]
 }));
 };

 // 按坯布识别码分组
 const groupByFabricCode = () => {
 const groups: Record<string, FabricInventory[]> = {};
 inventory.forEach(item => {
 const key = item.fabric_code;
 if (!groups[key]) {
 groups[key] = [];
 }
 groups[key].push(item);
 });
 return groups;
 };

 const fabricGroups = groupByFabricCode();

 return (
 <div className="min-h-screen bg-gray-50">
 {/* Header */}
 <header className="bg-white border-b border-gray-200 sticky top-0 z-10">
 <div className="max-w-7xl mx-auto px-3 sm:px-4 py-3 sm:py-4 flex items-center gap-3 sm:gap-4">
 <motion.button
 whileTap={{ scale: 0.95 }}
 onClick={() => navigate('/textile')}
 className="p-2 hover:bg-gray-100 rounded-lg transition-colors will-change-transform"
 >
 <ArrowLeft className="w-5 h-5 text-gray-600" />
 </motion.button>
 <h1 className="text-base sm:text-lg font-bold text-gray-900">已生产坯布</h1>
 </div>
 </header>

 <div className="max-w-7xl mx-auto px-3 sm:px-4 py-4 sm:py-6">
 {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-emerald-500 border-t-transparent rounded-full mb-3"
 />
 <p className="text-gray-500 text-xs sm:text-sm">加载中...</p>
 </div>
 ) : inventory.length === 0 ? (
 <motion.div
 initial={{ opacity: 0, y: 10 }}
 animate={{ opacity: 1, y: 0 }}
 transition={{ duration: 0.3 }}
 className="text-center py-12 sm:py-16 bg-white rounded-2xl border border-dashed border-gray-300"
 >
 <div className="w-14 h-14 sm:w-16 sm:h-16 bg-gray-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
 <Package className="w-7 h-7 sm:w-8 sm:h-8 text-gray-400" />
 </div>
 <p className="text-gray-500 text-base sm:text-lg font-medium mb-2">暂无原坯布库存</p>
 <p className="text-gray-400 text-sm">关联的计划暂无入库记录</p>
 </motion.div>
 ) : (
 <div className="space-y-3">
 {Object.entries(fabricGroups).map(([fabricCode, items], groupIndex) => {
 const isExpanded = expandedItems[fabricCode];
 const totalInMeters = items.reduce((sum, item) => sum + item.completed_quantity, 0);
 const totalTargetMeters = items.reduce((sum, item) => sum + item.target_quantity, 0);

 return (
 <motion.div
 key={fabricCode}
 initial={{ opacity: 0, y: 15 }}
 animate={{ opacity: 1, y: 0 }}
 transition={{ delay: groupIndex * 0.08, duration: 0.35, ease: [0.25, 0.46, 0.45, 0.94] }}
 className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden"
 >
            {/* 分组头部 */}
            <motion.div
              onClick={() => toggleExpand(fabricCode)}
              whileTap={{ scale: 0.995 }}
              className="flex items-center justify-between p-4 sm:p-5 cursor-pointer hover:bg-gray-50/50 transition-colors will-change-transform"
            >
              <div className="flex items-center gap-3 sm:gap-4 min-w-0">
                <motion.div
                  animate={{ rotate: isExpanded ? 180 : 0 }}
                  transition={{ duration: 0.2 }}
                  className={`w-9 h-9 sm:w-10 sm:h-10 rounded-xl flex items-center justify-center transition-colors flex-shrink-0 ${isExpanded ? 'bg-emerald-100' : 'bg-gray-100'}`}
                >
                  <ChevronDown size={18} className="sm:w-5 sm:h-5 text-gray-500" style={{ color: isExpanded ? '#059669' : undefined }} />
                </motion.div>
                <div className="min-w-0">
                  <p className="text-sm font-medium text-gray-900 truncate">
                    {fabricCode}
                  </p>
                  <p className="text-xs text-gray-500 mt-0.5">
                    已入库 <span className="text-emerald-600 font-medium">{totalInMeters.toLocaleString()}</span> 米 · 计划 {totalTargetMeters.toLocaleString()} 米
                  </p>
                </div>
              </div>
              <span className="px-3 py-1 bg-emerald-50 text-emerald-700 text-xs font-medium rounded-full flex-shrink-0 ml-2">
                {items.length} 个计划
              </span>
            </motion.div>

            {/* 展开的库存列表 - 移动端卡片式，桌面端表格 */}
            <AnimatePresence>
              {isExpanded && (
                <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="hidden sm:block overflow-x-auto">
                    <table className="w-full min-w-[500px]">
                      <thead className="bg-gray-50 border-b border-gray-100">
                        <tr>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">计划编号</th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">规格</th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">计划/入库</th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入库记录</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-100">
                        {items.map((item, itemIndex) => (
                          <motion.tr
                            key={item.plan_id}
                            initial={{ opacity: 0, x: -10 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{ delay: itemIndex * 0.05, duration: 0.25 }}
                            className="hover:bg-emerald-50/30 transition-colors"
                          >
                            <td className="px-4 py-3">
                              <span className="px-2.5 py-1 bg-emerald-50 text-emerald-700 rounded-lg text-xs font-mono font-medium">
                                {item.plan_code}
                              </span>
                            </td>
                            <td className="px-4 py-3">
                              <p className="text-sm text-gray-900 font-medium">{item.weight}g</p>
                            </td>
                            <td className="px-4 py-3">
                              <div className="text-sm">
                                <span className="text-gray-500">{item.target_quantity.toLocaleString()}米</span>
                                <span className="text-gray-300 mx-2">/</span>
                                <span className="text-emerald-600 font-semibold">{item.completed_quantity.toLocaleString()}米</span>
                              </div>
                            </td>
                            <td className="px-4 py-3">
                              {item.in_records.length > 0 ? (
                                <div className="text-xs text-gray-600">
                                  <span className="inline-flex items-center gap-1.5">
                                    <svg className="w-3.5 h-3.5 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                    </svg>
                                    {new Date(item.in_records[0].time).toLocaleDateString('zh-CN')}
                                    <span className="text-emerald-600 font-medium">{item.in_records[0].quantity}米</span>
                                    <span className="text-gray-400">/</span>
                                    <span>{item.in_records[0].rolls}匹/件</span>
                                  </span>
                                  {item.in_records.length > 1 && (
                                    <button
                                      onClick={(e) => {
                                        e.stopPropagation();
                                        setSelectedRecords(item.in_records);
                                        setSelectedPlanCode(item.plan_code);
                                        setRecordsModalOpen(true);
                                      }}
                                      className="inline-flex items-center gap-1 px-2.5 py-1 bg-emerald-50 text-emerald-600 rounded-lg text-xs font-medium hover:bg-emerald-100 transition-colors ml-2"
                                    >
                                      <List className="w-3.5 h-3.5" />
                                      全部 ({item.in_records.length}条)
                                    </button>
                                  )}
                                </div>
                              ) : (
                                <span className="text-xs text-gray-400 flex items-center gap-1">
                                  <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
                                  </svg>
                                  暂无入库
                                </span>
                              )}
                            </td>
                          </motion.tr>
                        ))}
                      </tbody>
                    </table>
                  </div>

                  {/* 移动端卡片 */}
                  <div className="sm:hidden p-4 space-y-3">
                    {items.map((item, itemIndex) => (
                      <motion.div
                        key={item.plan_id}
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: itemIndex * 0.05, duration: 0.25 }}
                        className="bg-white rounded-2xl border border-gray-100 p-4 shadow-sm"
                      >
                        <div className="flex items-center justify-between mb-3">
                          <span className="px-2.5 py-1 bg-emerald-50 text-emerald-700 rounded-lg text-xs font-mono font-medium">
                            {item.plan_code}
                          </span>
                          <span className="text-xs text-gray-600 font-medium">{item.weight}g</span>
                        </div>
                        <div className="flex items-center justify-between mb-3">
                          <div className="text-sm">
                            <span className="text-gray-400">计划</span>
                            <span className="text-gray-700 font-medium ml-1.5">{item.target_quantity.toLocaleString()}米</span>
                          </div>
                          <div className="text-sm">
                            <span className="text-gray-400">已入</span>
                            <span className="text-emerald-600 font-semibold ml-1.5">{item.completed_quantity.toLocaleString()}米</span>
                          </div>
                        </div>
                        {item.in_records.length > 0 ? (
                          <div className="flex items-center justify-between pt-3 border-t border-gray-100">
                            <div className="text-xs text-gray-600 flex items-center gap-1.5">
                              <svg className="w-3.5 h-3.5 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                              </svg>
                              <span>{new Date(item.in_records[0].time).toLocaleDateString('zh-CN')}</span>
                              <span className="text-emerald-600 font-medium">{item.in_records[0].quantity}米</span>
                              <span className="text-gray-400">/</span>
                              <span>{item.in_records[0].rolls}匹/件</span>
                            </div>
                            {item.in_records.length > 1 && (
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setSelectedRecords(item.in_records);
                                  setSelectedPlanCode(item.plan_code);
                                  setRecordsModalOpen(true);
                                }}
                                className="inline-flex items-center gap-1 px-2.5 py-1 bg-emerald-50 text-emerald-600 rounded-lg text-xs font-medium hover:bg-emerald-100 transition-colors"
                              >
                                <List className="w-3.5 h-3.5" />
                                全部 ({item.in_records.length}条)
                              </button>
                            )}
                          </div>
                        ) : (
                          <div className="text-xs text-gray-400 pt-3 border-t border-gray-100 flex items-center gap-1">
                            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
                            </svg>
                            暂无入库
                          </div>
                        )}
                      </motion.div>
                    ))}
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
 </motion.div>
 );
 })}
 </div>
 )}
 </div>

 {/* 入库记录弹窗 */}
 <InventoryRecordsModal
 isOpen={recordsModalOpen}
 onClose={() => setRecordsModalOpen(false)}
 records={selectedRecords}
 title={`${selectedPlanCode} - 入库记录`}
 />
 </div>
 );
}
