import React, { useEffect, useState } from 'react';
import { Card, Button, Typography, Space, Spin, Divider, Tag, message } from 'antd';
import { FileTextOutlined, DownloadOutlined } from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import { supabase } from '@/config/supabase';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

const { Title, Text } = Typography;

const CURRENCY_SYMBOLS = {
  CNY: "¥",
  TWD: "NT$",
  USD: "$",
};

const QuotationPreview = () => {
  const { id } = useParams();
  const [loading, setLoading] = useState(false);
  const [quotation, setQuotation] = useState(null);

  // 获取报价单详情
  const fetchQuotationDetail = async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from("resources")
        .select("*")
        .eq("id", id)
        .single();

      if (error) throw error;
      setQuotation(data);
    } catch (error) {
      message.error("获取报价单详情失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (id) {
      fetchQuotationDetail();
    }
  }, [id]);

  // PDF导出函数
  const exportPDF = async () => {
    try {
      // 显示加载中
      message.loading('正在生成PDF...', 0);
      
      // 获取要导出的DOM元素
      const element = document.getElementById('quotation-content');
      
      // 使用html2canvas将DOM转换为canvas
      const canvas = await html2canvas(element, {
        scale: 2, // 提高清晰度
        useCORS: true, // 允许加载跨域图片
        logging: false, // 关闭日志
        backgroundColor: '#ffffff' // 设置背景色
      });

      // 获取canvas的宽高
      const imgWidth = 210; // A4纸的宽度(mm)
      const pageHeight = 297; // A4纸的高度(mm)
      const imgHeight = canvas.height * imgWidth / canvas.width;
      const pdfWidth = imgWidth;
      const pdfHeight = imgHeight;

      // 将canvas转为图片
      const imgData = canvas.toDataURL('image/jpeg', 1.0);

      // 初始化jsPDF
      const pdf = new jsPDF('p', 'mm', 'a4');
      
      // 计算分页
      let position = 0;
      let currentPage = 1;

      while (position < pdfHeight) {
        // 添加图片到PDF
        pdf.addImage(
          imgData, 
          'JPEG', 
          0, // x坐标
          position === 0 ? 0 : -position, // y坐标
          pdfWidth, // 图片宽度
          pdfHeight // 图片高度
        );

        position += pageHeight;
        
        // 如果还有内容，添加新页面
        if (position < pdfHeight) {
          pdf.addPage();
          currentPage++;
        }
      }

      // 保存PDF
      pdf.save(`${quotation.attributes.quataName || '报价单'}.pdf`);
      
      // 关闭加载提示
      message.destroy();
      message.success('PDF导出成功！');
    } catch (error) {
      console.error('PDF导出失败:', error);
      message.error('PDF导出失败，请重试');
    }
  };

  // 导出按钮组件
  const ExportPDFButton = () => (
    <Button
      type="primary"
      icon={<DownloadOutlined />}
      onClick={exportPDF}
    >
      导出PDF
    </Button>
  );

  if (loading) {
    return (
      <div className="flex justify-center items-center h-full">
        <Spin size="large" />
      </div>
    );
  }

  if (!quotation) return null;

  const { attributes } = quotation;
  const currencySymbol = CURRENCY_SYMBOLS[attributes.currency] || '¥';

  return (
    <div className="max-w-4xl mx-auto p-6">
      <Card
        title={
          <div className="flex justify-between items-center">
            <Space>
              <FileTextOutlined className="text-blue-500" />
              <span>报价单预览</span>
            </Space>
            <ExportPDFButton />
          </div>
        }
      >
        <div id="quotation-content" className="p-6">
          {/* 报价单标题 */}
          <div className="text-center mb-8">
            <Title level={2}>{attributes.quataName}</Title>
            <Text type="secondary">创建日期：{new Date(quotation.created_at).toLocaleDateString()}</Text>
          </div>

          {/* 基本信息 */}
          <div className="bg-gray-50 p-4 rounded-lg mb-6">
            <Title level={4}>基本信息</Title>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Text type="secondary">客户：</Text>
                <Space>
                  {attributes.customers?.map(customer => (
                    <Tag key={customer.id} color="blue">{customer.name}</Tag>
                  ))}
                </Space>
              </div>
              <div>
                <Text type="secondary">货币类型：</Text>
                <Text>{attributes.currency}</Text>
              </div>
            </div>
          </div>

          {/* 报价明细 */}
          {attributes.sections?.map((section, sIndex) => (
            <div key={sIndex} className="mb-6">
              <div className="flex items-center gap-2 mb-3">
                <div className="h-4 w-1 bg-blue-500 rounded-full" />
                <Title level={4} className="!mb-0">{section.sectionName}</Title>
              </div>
              
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-sm font-medium text-gray-500">项目明细</th>
                      <th className="px-4 py-3 text-left text-sm font-medium text-gray-500">描述/备注</th>
                      <th className="px-4 py-3 text-left text-sm font-medium text-gray-500">单位</th>
                      <th className="px-4 py-3 text-right text-sm font-medium text-gray-500">数量</th>
                      <th className="px-4 py-3 text-right text-sm font-medium text-gray-500">单价</th>
                      <th className="px-4 py-3 text-right text-sm font-medium text-gray-500">小计</th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {section.items.map((item, iIndex) => (
                      <tr key={iIndex}>
                        <td className="px-4 py-3 text-sm text-gray-900">{item.name}</td>
                        <td className="px-4 py-3 text-sm text-gray-500">{item.description}</td>
                        <td className="px-4 py-3 text-sm text-gray-500">{item.unit}</td>
                        <td className="px-4 py-3 text-sm text-gray-900 text-right">{item.quantity}</td>
                        <td className="px-4 py-3 text-sm text-gray-900 text-right">
                          {currencySymbol}{item.price?.toLocaleString()}
                        </td>
                        <td className="px-4 py-3 text-sm text-gray-900 text-right">
                          {currencySymbol}{(item.quantity * item.price)?.toLocaleString()}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          ))}

          {/* 金额汇总 */}
          <div className="mt-8 border-t pt-4">
            <div className="flex justify-end space-y-2">
              <div className="w-64 space-y-2">
                <div className="flex justify-between">
                  <Text>税前总计：</Text>
                  <Text>{currencySymbol}{attributes.beforeTaxAmount?.toLocaleString()}</Text>
                </div>
                <div className="flex justify-between">
                  <Text>税率</Text>
                  <Text>{attributes.taxRate}%</Text>
                </div>
                <div className="flex justify-between">
                  <Text>税后总计：</Text>
                  <Text>{currencySymbol}{attributes.afterTaxAmount?.toLocaleString()}</Text>
                </div>
                {attributes.discount > 0 && (
                  <div className="flex justify-between">
                    <Text>折扣价：</Text>
                    <Text type="success">{currencySymbol}{attributes.discount?.toLocaleString()}</Text>
                  </div>
                )}
                <Divider className="my-2" />
                <div className="flex justify-between">
                  <Text strong>最终金额：</Text>
                  <Text strong className="text-blue-500 text-xl">
                    {currencySymbol}{(attributes.discount || attributes.afterTaxAmount)?.toLocaleString()}
                  </Text>
                </div>
              </div>
            </div>
          </div>

          {/* 补充说明 */}
          {attributes.description && (
            <div className="mt-8">
              <Title level={4}>补充说明</Title>
              <div className="bg-gray-50 p-4 rounded-lg">
                <Text>{attributes.description}</Text>
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
};

export default QuotationPreview;