import React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Package, Calendar, Factory, Hash } from 'lucide-react';

interface InventoryRecord {
  time?: string;
  rolls: number;
  meters: number;
  quantity?: number;
  plan_code?: string;
  factory_name?: string;
  batch_no?: string;
  source?: 'self' | 'textile';
  price_per_meter?: number;
  price_note?: string | null;
  created_at?: string;
  record_type?: 'in' | 'out';
}

interface InventoryRecordsModalProps {
  isOpen: boolean;
  onClose: () => void;
  records: InventoryRecord[];
  title?: string;
}

export function InventoryRecordsModal({ 
  isOpen, 
  onClose, 
  records, 
  title = '生产记录详情' 
}: InventoryRecordsModalProps) {
  if (!records || records.length === 0) return null;

  // 分别计算入库和出库的统计
  const inRecords = records.filter(r => r.record_type !== 'out');
  const outRecords = records.filter(r => r.record_type === 'out');
  const totalInRolls = inRecords.reduce((sum, r) => sum + (r.rolls || 0), 0);
  const totalInMeters = inRecords.reduce((sum, r) => sum + (r.meters || r.quantity || 0), 0);
  const totalOutRolls = outRecords.reduce((sum, r) => sum + (r.rolls || 0), 0);
  const totalOutMeters = outRecords.reduce((sum, r) => sum + (r.meters || r.quantity || 0), 0);

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
          onClick={onClose}
        >
          <motion.div
            initial={{ opacity: 0, scale: 0.95, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 20 }}
            className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[80vh] overflow-hidden"
            onClick={e => e.stopPropagation()}
          >
            {/* 头部 */}
            <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-xl flex items-center justify-center">
                  <Package className="w-5 h-5 text-white" />
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-gray-900">{title}</h3>
                  <p className="text-xs text-gray-500">共 {records.length} 条记录</p>
                </div>
              </div>
              <button
                onClick={onClose}
                className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* 统计摘要 */}
            <div className="px-4 py-3 bg-gray-50 border-b border-gray-100">
              {outRecords.length > 0 ? (
                // 有出库记录时，显示入库和出库对比
                <div className="space-y-2">
                  <div className="flex gap-4">
                    <div className="flex-1 text-center">
                      <p className="text-xs text-emerald-600 mb-1">入库匹/件</p>
                      <p className="text-lg font-semibold text-emerald-700">{totalInRolls} <span className="text-sm font-normal text-gray-500">匹/件</span></p>
                    </div>
                    <div className="flex-1 text-center border-l border-gray-200">
                      <p className="text-xs text-emerald-600 mb-1">入库米数</p>
                      <p className="text-lg font-semibold text-emerald-700">{totalInMeters} <span className="text-sm font-normal text-gray-500">米</span></p>
                    </div>
                  </div>
                  <div className="flex gap-4 pt-2 border-t border-gray-200">
                    <div className="flex-1 text-center">
                      <p className="text-xs text-red-600 mb-1">出库匹/件</p>
                      <p className="text-lg font-semibold text-red-700">{totalOutRolls} <span className="text-sm font-normal text-gray-500">匹/件</span></p>
                    </div>
                    <div className="flex-1 text-center border-l border-gray-200">
                      <p className="text-xs text-red-600 mb-1">出库米数</p>
                      <p className="text-lg font-semibold text-red-700">{totalOutMeters} <span className="text-sm font-normal text-gray-500">米</span></p>
                    </div>
                  </div>
                </div>
              ) : (
                // 只有入库记录时，简化显示
                <div className="flex gap-4">
                  <div className="flex-1 text-center">
                    <p className="text-xs text-gray-500 mb-1">总匹/件数</p>
                    <p className="text-lg font-semibold text-gray-900">{totalInRolls} <span className="text-sm font-normal text-gray-500">匹/件</span></p>
                  </div>
                  <div className="flex-1 text-center border-l border-gray-200">
                    <p className="text-xs text-gray-500 mb-1">总米数</p>
                    <p className="text-lg font-semibold text-gray-900">{totalInMeters} <span className="text-sm font-normal text-gray-500">米</span></p>
                  </div>
                </div>
              )}
            </div>

            {/* 记录列表 */}
            <div className="overflow-y-auto max-h-[50vh]">
              <div className="divide-y divide-gray-100">
                {records.map((record, index) => (
                  <div
                    key={index}
                    className={`p-4 hover:bg-gray-50 transition-colors ${record.record_type === 'out' ? 'bg-red-50/50' : ''}`}
                  >
                    <div className="flex items-start gap-3">
                      <div className={`w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5 ${record.record_type === 'out' ? 'bg-red-100' : 'bg-blue-100'}`}>
                        <span className={`text-xs font-medium ${record.record_type === 'out' ? 'text-red-600' : 'text-blue-600'}`}>{index + 1}</span>
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <Calendar className="w-3.5 h-3.5 text-gray-400" />
                          <span className="text-sm font-medium text-gray-900">
                            {record.time || record.created_at ? new Date(record.time || record.created_at || '').toLocaleDateString('zh-CN') : '-'}
                          </span>
                          <span className="text-xs text-gray-400">
                            {record.time || record.created_at ? new Date(record.time || record.created_at || '').toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : ''}
                          </span>
                          {record.record_type === 'out' && (
                            <span className="text-xs px-1.5 py-0.5 bg-red-100 text-red-600 rounded">出库</span>
                          )}
                        </div>

                        <div className="flex flex-wrap gap-2 text-xs">
                          {record.plan_code && (
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-blue-50 text-blue-700 rounded">
                              <Hash className="w-3 h-3" />
                              {record.plan_code}
                            </span>
                          )}
                          {record.factory_name && (
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-gray-100 text-gray-700 rounded">
                              <Factory className="w-3 h-3" />
                              {record.factory_name}
                            </span>
                          )}
                          {record.batch_no && record.batch_no !== '-' && (
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-amber-50 text-amber-700 rounded">
                              批号: {record.batch_no}
                            </span>
                          )}
                        </div>

                        <div className="mt-2 flex items-center gap-3 text-sm">
                          <span className={`font-medium ${record.record_type === 'out' ? 'text-red-600' : 'text-gray-900'}`}>
                            {record.record_type === 'out' ? '-' : ''}{record.rolls || 0} 匹/件
                          </span>
                          <span className="text-gray-400">·</span>
                          <span className={`font-medium ${record.record_type === 'out' ? 'text-red-600' : 'text-gray-900'}`}>
                            {record.record_type === 'out' ? '-' : ''}{record.meters || record.quantity || 0} 米
                          </span>
                          {record.record_type !== 'out' && record.source === 'self' && (
                            <span className="text-xs px-1.5 py-0.5 bg-emerald-50 text-emerald-600 rounded">自入库</span>
                          )}
                          {record.record_type !== 'out' && record.source === 'textile' && (
                            <span className="text-xs px-1.5 py-0.5 bg-blue-50 text-blue-600 rounded">纺织厂</span>
                          )}
                        </div>

                        {/* 单价信息 */}
                        {(record.price_per_meter || 0) > 0 && (
                          <div className="mt-2 flex items-center gap-2 text-xs">
                            <span className="text-gray-500">单价:</span>
                            <span className="font-medium text-amber-600">¥{record.price_per_meter}/米</span>
                            <span className="text-gray-400">·</span>
                            <span className="font-medium text-gray-700">¥{((record.meters || record.quantity || 0) * (record.price_per_meter || 0)).toFixed(2)}</span>
                            {record.price_note && (
                              <span className="text-gray-400">({record.price_note})</span>
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* 底部 */}
            <div className="p-4 border-t border-gray-200 bg-gray-50">
              <button
                onClick={onClose}
                className="w-full py-2.5 bg-white border border-gray-300 text-gray-700 rounded-xl font-medium hover:bg-gray-50 transition-colors"
              >
                关闭
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
