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 { supabase } from '../../supabase/client';
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();

 // 订阅入库记录变化，实现实时更新
 const subscription = supabase
 .channel('inventory_records_changes')
 .on(
 'postgres_changes',
 {
 event: '*',
 schema: 'public',
 table: 'inventory_records'
 },
 () => {
 // 有入库记录变化时刷新数据
 fetchFabricInventory();
 }
 )
 .subscribe();

 return () => {
 subscription.unsubscribe();
 };
 }, [auth.company]);

 const fetchFabricInventory = async () => {
 setLoading(true);
 
 // 获取纺织厂关联的所有计划
 const { data: planFactories } = await supabase
 .from('plan_factories')
 .select('plan_id')
 .eq('factory_id', auth.company!.id)
 .eq('factory_type', 'textile');

 if (!planFactories || planFactories.length === 0) {
 setInventory([]);
 setLoading(false);
 return;
 }

 const planIds = planFactories.map(pf => pf.plan_id);

 // 获取计划对应的产品信息
 const { data: plansData } = await supabase
 .from('production_plans')
 .select('id, plan_code, fabric_code, target_quantity, completed_quantity, purchaser_id')
 .in('id', planIds);

 if (!plansData || plansData.length === 0) {
 setInventory([]);
 setLoading(false);
 return;
 }

 // 获取采购商的产品信息（克重）
 const purchaserIds = [...new Set(plansData.map(p => p.purchaser_id))];
 const fabricCodes = plansData.map(p => p.fabric_code);

 const { data: productsData } = await supabase
 .from('products')
 .select('fabric_code, weight, company_id')
 .in('company_id', purchaserIds)
 .in('fabric_code', fabricCodes);

 const productWeightMap: Record<string, number> = {};
 productsData?.forEach(p => {
 productWeightMap[p.fabric_code] = p.weight;
 });

 // 获取入库记录 - 从 inventory_records 表查询
 const { data: inventoryRecords } = await supabase
 .from('inventory_records')
 .select('plan_id, quantity, rolls, created_at')
 .in('plan_id', planIds)
 .order('created_at', { ascending: false });

 // 按 plan_id 分组入库记录
 const recordsByPlan: Record<string, { time: string; quantity: number; rolls: number }[]> = {};
 inventoryRecords?.forEach(record => {
 if (!recordsByPlan[record.plan_id]) {
 recordsByPlan[record.plan_id] = [];
 }
 recordsByPlan[record.plan_id].push({
 time: record.created_at,
 quantity: Number(record.quantity) || 0,
 rolls: Number(record.rolls) || 0
 });
 });

 // 构建库存数据 - 每个计划一条记录
 // 以 inventory_records 实际入库记录为准，计算准确的已完成数量
 const inventoryList: FabricInventory[] = plansData.map(plan => {
 const records = recordsByPlan[plan.id] || [];
 // 从实际入库记录计算总米数和总匹/件数
 const totalInFromRecords = records.reduce((sum, r) => sum + r.quantity, 0);
 const totalRollsFromRecords = records.reduce((sum, r) => sum + r.rolls, 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);

    // 如果没有真实数据，使用示例数据
    if (inventoryList.length === 0) {
      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 will-change-transform"
 >
            {/* 分组头部 */}
            <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>
 );
}
