import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { http } from '../../api';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, Package, Search, History, ArrowUpRight, ArrowDownRight, Boxes, Shirt } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import type { FinishedProduct, FinishedProductInventoryRecord } from '../../types';

interface FinishedProductWithDetails extends FinishedProduct {
  warehouse_name?: string;
  inventory_records?: FinishedProductInventoryRecord[];
}

const statusMap: Record<string, { label: string; color: string; bgColor: string }> = {
  in_stock: { label: '在库', color: 'text-green-600', bgColor: 'bg-green-50' },
  partial_out: { label: '部分出库', color: 'text-amber-600', bgColor: 'bg-amber-50' },
  sold_out: { label: '已售罄', color: 'text-gray-600', bgColor: 'bg-gray-50' }
};

export function FinishedWarehouse() {
  const navigate = useNavigate();
  const { auth } = useAuth();
  const { isMobile } = useResponsive();
  const [products, setProducts] = useState<FinishedProductWithDetails[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedProduct, setSelectedProduct] = useState<FinishedProductWithDetails | null>(null);
  const [recordsModalOpen, setRecordsModalOpen] = useState(false);
  const [inventoryRecords, setInventoryRecords] = useState<FinishedProductInventoryRecord[]>([]);

  useEffect(() => {
    if (auth.company) {
      fetchProducts();
    }
  }, [auth.company]);

  const fetchProducts = async () => {
    setLoading(true);
    try {
      const res = await http.get<FinishedProductWithDetails[]>('/purchaser/finished-products');
      setProducts(res.data || []);
    } catch {
      setProducts([]);
    }
    setLoading(false);
  };

  const fetchInventoryRecords = async (productId: string) => {
    try {
      const res = await http.get<FinishedProductInventoryRecord[]>(
        `/purchaser/finished-products/${productId}/records`
      );
      setInventoryRecords(res.data || []);
    } catch {
      setInventoryRecords([]);
    }
  };

  const openRecordsModal = async (product: FinishedProductWithDetails) => {
    setSelectedProduct(product);
    await fetchInventoryRecords(product.id);
    setRecordsModalOpen(true);
  };

  const filteredProducts = products.filter(product =>
    product.product_name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    product.fabric_code?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    product.color?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = {
    totalProducts: products.length,
    totalStockMeters: products.reduce((sum, p) => sum + (p.stock_meters || 0), 0),
    totalStockRolls: products.reduce((sum, p) => sum + (p.stock_rolls || 0), 0),
    inStockCount: products.filter(p => p.status === 'in_stock').length
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-amber-50 to-orange-50">
      {/* Header */}
      <header className="bg-gradient-to-r from-amber-500 to-orange-500 shadow-lg">
        <div className="max-w-7xl mx-auto px-4 md:px-8 py-4 flex items-center gap-3">
          <button
            onClick={() => navigate('/purchaser')}
            className="p-2 hover:bg-white/20 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5 text-white" />
          </button>
          <div>
            <h1 className="text-lg font-bold text-white">水洗仓库</h1>
            <p className="text-xs text-white/70">管理水洗厂内坯布库存</p>
          </div>
        </div>
      </header>

      <div className="p-4 md:p-8 max-w-7xl mx-auto">
        {/* 统计卡片 */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 mb-6">
          <div className="bg-white rounded-xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-1">成品种类</p>
            <p className="text-2xl font-bold text-gray-800">{stats.totalProducts}</p>
          </div>
          <div className="bg-white rounded-xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-1">库存米数</p>
            <p className="text-2xl font-bold text-amber-600">{stats.totalStockMeters.toFixed(2)}</p>
          </div>
          <div className="bg-white rounded-xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-1">库存匹/件数</p>
            <p className="text-2xl font-bold text-blue-600">{stats.totalStockRolls}</p>
          </div>
          <div className="bg-white rounded-xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-1">在库品种</p>
            <p className="text-2xl font-bold text-green-600">{stats.inStockCount}</p>
          </div>
        </div>

        {/* 搜索栏 */}
        <div className="bg-white rounded-xl p-4 shadow-sm mb-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder="搜索成品名称、坯布码、颜色..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent"
            />
          </div>
        </div>

        {/* 成品列表 */}
        {loading ? (
          <div className="text-center py-12 text-gray-400">加载中...</div>
        ) : filteredProducts.length === 0 ? (
          <div className="text-center py-12 text-gray-400">
            <Boxes className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p>暂无成品记录</p>
            <p className="text-sm mt-1">完成水洗计划后将自动入库</p>
          </div>
        ) : (
          <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
            <div className="p-4 border-b border-gray-100 flex items-center justify-between">
              <h2 className="text-base font-semibold text-gray-800">成品列表</h2>
              <span className="text-sm text-gray-500">共 {filteredProducts.length} 条</span>
            </div>
            <div className="divide-y divide-gray-100">
              {filteredProducts.map((product) => (
                <motion.div
                  key={product.id}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  className="p-4 hover:bg-gray-50 transition-colors"
                >
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <span className={`px-2 py-1 rounded-lg text-xs font-medium ${statusMap[product.status]?.bgColor} ${statusMap[product.status]?.color}`}>
                          {statusMap[product.status]?.label}
                        </span>
                        <span className="text-xs text-gray-400">{product.fabric_code}</span>
                      </div>
                      <h3 className="font-medium text-gray-800 mb-1">
                        {product.product_name} - {product.color}
                      </h3>
                      <div className="flex flex-wrap gap-4 text-sm text-gray-600">
                        <span>洗后米数: {product.washed_meters}米</span>
                        <span>缩水率: {product.shrinkage_rate}%</span>
                        <span>匹/件数: {product.rolls}匹/件</span>
                      </div>
                      <div className="flex flex-wrap gap-4 mt-1 text-sm text-gray-500">
                        <span>库存: {product.stock_meters}米 / {product.stock_rolls}匹/件</span>
                        {product.warehouse_name && (
                          <span>仓库: {product.warehouse_name}</span>
                        )}
                      </div>
                    </div>
                    <button
                      onClick={() => openRecordsModal(product)}
                      className="px-4 py-2 text-amber-600 hover:bg-amber-50 rounded-lg transition-colors text-sm font-medium flex items-center gap-1"
                    >
                      <History className="w-4 h-4" />
                      出入库记录
                    </button>
                  </div>
                </motion.div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* 出入库记录弹窗 */}
      <AnimatePresence>
        {recordsModalOpen && selectedProduct && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50"
            onClick={() => setRecordsModalOpen(false)}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-white rounded-2xl w-full max-w-2xl max-h-[80vh] overflow-hidden"
              onClick={e => e.stopPropagation()}
            >
              <div className="p-4 border-b border-gray-100 flex items-center justify-between">
                <div>
                  <h3 className="text-lg font-semibold text-gray-800">出入库记录</h3>
                  <p className="text-sm text-gray-500">
                    {selectedProduct.product_name} - {selectedProduct.color}
                  </p>
                </div>
                <button
                  onClick={() => setRecordsModalOpen(false)}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <span className="text-gray-400 text-xl">&times;</span>
                </button>
              </div>

              <div className="p-4 overflow-y-auto max-h-[60vh]">
                {inventoryRecords.length === 0 ? (
                  <div className="text-center py-8 text-gray-400">
                    <History className="w-10 h-10 mx-auto mb-2 text-gray-300" />
                    <p>暂无出入库记录</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {inventoryRecords.map((record) => (
                      <div
                        key={record.id}
                        className="bg-gray-50 rounded-lg p-3 flex items-center justify-between"
                      >
                        <div className="flex items-center gap-3">
                          {record.record_type === 'inbound' ? (
                            <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                              <ArrowDownRight className="w-4 h-4 text-green-600" />
                            </div>
                          ) : (
                            <div className="w-8 h-8 bg-amber-100 rounded-full flex items-center justify-center">
                              <ArrowUpRight className="w-4 h-4 text-amber-600" />
                            </div>
                          )}
                          <div>
                            <p className="font-medium text-gray-800">
                              {record.record_type === 'inbound' ? '入库' : '出库'}
                            </p>
                            <p className="text-xs text-gray-500">
                              {new Date(record.created_at).toLocaleString('zh-CN')}
                            </p>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="font-medium text-gray-800">
                            {record.meters}米 / {record.rolls}匹/件
                          </p>
                          {record.batch_no && (
                            <p className="text-xs text-gray-500">批号: {record.batch_no}</p>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              <div className="p-4 border-t border-gray-100 bg-gray-50">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">当前库存:</span>
                  <span className="font-medium text-gray-800">
                    {selectedProduct.stock_meters}米 / {selectedProduct.stock_rolls}匹/件
                  </span>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
