/**
 * 产品信息展示组件
 * 作者: 阿瑞
 * 功能: 展示产品详细信息
 * 版本: 1.0.0
 */

'use client';

import React, { useState, useMemo } from 'react';
import Image from 'next/image';
import { MdShoppingCart } from 'react-icons/md';
import { useThemeMode } from '@/store/settingStore';
import { ThemeMode } from '@/types/enum';
import Modal from '@/components/ui/Modal';
import Card from '@/components/ui/Card';
import { Tag } from 'antd';
import MyTooltip from '@/components/tooltip/MyTooltip';
import styles from './ProductInfoModal.module.css';

interface ProductProps {
  productId?: number;
  productName?: string;
  productCode?: string;
  productSku?: string;
  price?: number;
  quantity?: number;
  brandId?: number;
  brandName?: string;
  categoryId?: number;
  categoryName?: string;
  supplierId?: number;
  supplierName?: string;
  image?: string;
  description?: string;
  logisticsStatus?: string; // 物流状态
  logisticsDetails?: string; // 物流详情JSON字符串
  logisticsTrackingNumber?: string; // 物流单号
  logisticsCompany?: string; // 物流公司
}

// 定义物流轨迹项的类型
interface LogisticsRoute {
  acceptTime?: string;
  time?: string;
  remark?: string;
  content?: string;
  acceptAddress?: string;
  location?: string;
}

// 定义物流详情数据接口
interface LogisticsDetails {
  routes?: LogisticsRoute[];
  [key: string]: unknown;
}

/**
 * 获取物流状态对应的标签样式
 */
const getLogisticsStatusStyle = (status?: string) => {
  if (!status) return { color: 'default', text: '未知' };
  
  switch (status) {
    case '已填单':
      return { color: 'default', text: '已填单' };
    case '已揽件':
      return { color: 'processing', text: '已揽件' };
    case '运输中':
      return { color: 'processing', text: '运输中' };
    case '已签收':
      return { color: 'success', text: '已签收' };
    default:
      return { color: 'processing', text: status };
  }
};

/**
 * 产品信息展示组件
 */
const ProductInfoModal: React.FC<ProductProps> = (props) => {
  const {
    productName,
    price = 0,
    quantity = 0,
    brandName,
    categoryName,
    supplierName,
    image,
    logisticsStatus,
    logisticsDetails,
    logisticsTrackingNumber,
    logisticsCompany
  } = props;

  const themeMode = useThemeMode();
  const isDarkMode = themeMode === ThemeMode.Dark;
  
  // 图片预览状态
  const [previewOpen, setPreviewOpen] = useState(false);
  
  // 获取物流状态样式
  const statusStyle = getLogisticsStatusStyle(logisticsStatus);

  /**
   * 解析物流详情数据
   */
  const parsedLogisticsDetails = useMemo(() => {
    if (!logisticsDetails) return null;
    
    try {
      return JSON.parse(logisticsDetails) as LogisticsDetails;
    } catch (e) {
      console.error('解析物流详情失败:', e);
      return null;
    }
  }, [logisticsDetails]);

  /**
   * 格式化物流详情显示
   */
  const formatLogisticsDetails = useMemo(() => {
    try {
      if (!parsedLogisticsDetails || !parsedLogisticsDetails.routes || !Array.isArray(parsedLogisticsDetails.routes) || parsedLogisticsDetails.routes.length === 0) {
        return `
          物流单号: ${logisticsTrackingNumber || '-'} 
          物流公司: ${logisticsCompany || '-'}
          暂无物流轨迹信息
        `;
      }
      
      const routes = parsedLogisticsDetails.routes;
      
      // 提取最近的几条物流记录
      const recentRoutes = routes.slice(0, 3);
      
      let detailText = `
        物流单号: ${logisticsTrackingNumber || '-'} 
        物流公司: ${logisticsCompany || '-'}
        
        物流轨迹:
      `;
      
      recentRoutes.forEach((route: LogisticsRoute, index: number) => {
        const time = route.acceptTime || route.time || '-';
        const content = route.remark || route.content || '未知状态';
        const location = route.acceptAddress || route.location || '';
        
        detailText += `
          ${index + 1}. ${time}
             ${location ? `[${location}] ` : ''}${content}
        `;
      });
      
      if (routes.length > 3) {
        detailText += `
          ...更多${routes.length - 3}条记录
        `;
      }
      
      return detailText;
    } catch (e) {
      console.error('格式化物流详情失败:', e);
      return '物流详情格式错误';
    }
  }, [parsedLogisticsDetails, logisticsTrackingNumber, logisticsCompany]);

  /**
   * 格式化金额显示
   */
  const formatAmount = (amount: number | undefined) => {
    if (amount === undefined || amount === null) return '¥0.00';
    // 确保 amount 是数字类型
    const numAmount = Number(amount);
    // 检查是否为有效数字
    if (isNaN(numAmount)) return '¥0.00';
    return `¥${numAmount.toFixed(2)}`;
  };

  /**
   * 打开图片预览
   */
  const handleOpenPreview = (e: React.MouseEvent) => {
    e.stopPropagation();
    setPreviewOpen(true);
  };

  /**
   * 关闭图片预览
   */
  const handleClosePreview = () => {
    setPreviewOpen(false);
  };

  /**
   * 渲染产品信息标签
   */
  const renderProductInfoTag = (label: string, value: string | number | undefined) => {
    if (!value) return null;
    return (
      <div className="flex items-center rounded-md border border-slate-200 dark:border-slate-700 px-3 py-1 text-sm">
        <span className="font-medium mr-1">{label}:</span> 
        <span>{value}</span>
      </div>
    );
  };

  return (
    <>
      <div className={`${styles.productCard} ${isDarkMode ? styles.dark : styles.light}`}>
        <div className={styles.productImageContainer} onClick={handleOpenPreview}>
          {/* 产品图片 */}
          {image ? (
            <Image
              src={image}
              alt={productName || '产品'}
              width={120}
              height={120}
              className={styles.productImage}
            />
          ) : (
            <div className={`${styles.productImagePlaceholder} ${isDarkMode ? styles.dark : styles.light}`}>
              <MdShoppingCart size={48} style={{ color: '#6b7280' }} />
            </div>
          )}

          {/* 物流状态标签 - 右下角 - 简化样式 */}
          <div className={`${styles.exampleTag} ${isDarkMode ? styles.dark : styles.light}`}>
            {logisticsStatus ? (
              <MyTooltip 
                title={formatLogisticsDetails}
                placement="top"
                shouldWrapChildren={false}
              >
                <Tag 
                  color={statusStyle.color} 
                  className={`${styles.statusTag} m-0 cursor-pointer`}
                >
                  {statusStyle.text}
                </Tag>
              </MyTooltip>
            ) : (
              <Tag 
                color="default" 
                className={`${styles.statusTag} m-0`}
              >
                未发货
              </Tag>
            )}
          </div>

          {/* 供应商名称 - 左上角 */}
          {supplierName && (
            <div className={`${styles.supplierTag} ${isDarkMode ? styles.dark : styles.light}`}>
              {supplierName}
            </div>
          )}

          {/* 品牌+品类 - 右上角 */}
          {(brandName || categoryName) && (
            <div className={`${styles.brandCategoryTag} ${isDarkMode ? styles.dark : styles.light}`}>
              {brandName && categoryName ? `${brandName} · ${categoryName}` : brandName || categoryName}
            </div>
          )}

          {/* 数量 - 左下角价格上方 */}
          {quantity > 0 && (
            <div className={`${styles.quantityTag} ${isDarkMode ? styles.dark : styles.light}`}>
              x{quantity}
            </div>
          )}

          {/* 价格 - 左下角 */}
          <div className={`${styles.priceTag} ${isDarkMode ? styles.dark : styles.light}`}>
            {formatAmount(price)}
          </div>
        </div>
      </div>

      {/* 使用 Modal 组件进行图片预览 */}
      <Modal
        isOpen={previewOpen}
        onClose={handleClosePreview}
        size="lg"
        isGlass={true}
        glassLevel="medium"
        title={productName || "产品详情"}
      >
        <div className="flex flex-col items-center space-y-6">
          {/* 图片显示卡片 */}
          <Card padding="medium" glassEffect="none" hoverEffect={false} className="overflow-hidden">
            <div className="relative w-full h-[350px] flex items-center justify-center">
              {image ? (
                <Image
                  src={image}
                  alt={productName || '产品'}
                  fill
                  style={{ objectFit: 'contain' }}
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center bg-slate-100 dark:bg-slate-800">
                  <MdShoppingCart size={64} className="text-gray-400" />
                </div>
              )}
            </div>
          </Card>
          
          {/* 产品信息 */}
          <div className="w-full">
            <Card padding="medium" glassEffect="none" hoverEffect={false}>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {renderProductInfoTag("供应商", supplierName)}
                {renderProductInfoTag("品牌", brandName)}
                {renderProductInfoTag("品类", categoryName)}
                {renderProductInfoTag("价格", formatAmount(price))}
                {renderProductInfoTag("数量", quantity > 0 ? `x${quantity}` : undefined)}
                {logisticsStatus && (
                  <div className="flex items-center rounded-md border border-slate-200 dark:border-slate-700 px-3 py-1 text-sm">
                    <span className="font-medium mr-1">物流状态:</span>
                    <MyTooltip 
                      title={formatLogisticsDetails}
                      placement="top"
                    >
                      <Tag 
                        color={statusStyle.color} 
                        className="m-0 cursor-pointer text-xs py-0 px-2 h-5 leading-5"
                      >
                        {statusStyle.text}
                      </Tag>
                    </MyTooltip>
                  </div>
                )}
              </div>
            </Card>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default ProductInfoModal;
