import React, { useState, useEffect, useMemo } from "react";
import {
  Form,
  Input,
  InputNumber,
  Select,
  Button,
  Space,
  Card,
  Typography,
  message,
  Popconfirm,
  Modal,
  Divider,
} from "antd";
import {
  PlusOutlined,
  ArrowLeftOutlined,
  SaveOutlined,
  DeleteOutlined,
  CloseOutlined,
  EditOutlined,
  CheckOutlined,
} from "@ant-design/icons";
import { supabase } from "@/config/supabase";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";

const { TextArea } = Input;
const { Title, Text } = Typography;

// 添加货币符号映射
const CURRENCY_SYMBOLS = {
  CNY: "¥",
  TWD: "NT$",
  USD: "$",
};

const QuotationForm = () => {
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const isEdit = searchParams.get("edit") === "true";
  const templateId = searchParams.get("templateId");
  const isView = id && !isEdit;
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [dataSource, setDataSource] = useState([{ id: Date.now() }]);
  const [totalAmount, setTotalAmount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [currentCurrency, setCurrentCurrency] = useState("CNY");
  const [customers, setCustomers] = useState([]);
  const [selectedCustomers, setSelectedCustomers] = useState([]);
  const [formValues, setFormValues] = useState({});
  const [templateModalVisible, setTemplateModalVisible] = useState(false);
  const [availableSections, setAvailableSections] = useState([]);
  const [editingSectionIndex, setEditingSectionIndex] = useState(null);
  const [editingSectionName, setEditingSectionName] = useState("");
  const [taxRate, setTaxRate] = useState(0);
  const [discount, setDiscount] = useState(0);

  // 计算单项金额
  const calculateItemAmount = useMemo(
    () => (quantity, price) => {
      const safeQuantity = Number(quantity) || 0;
      const safePrice = Number(price) || 0;
      return safeQuantity * safePrice;
    },
    []
  );

  // 计算小节总额
  const calculateSectionTotal = useMemo(
    () =>
      (items = []) => {
        if (!Array.isArray(items)) return 0;
        return items.reduce((sum, item) => {
          if (!item) return sum;
          return sum + calculateItemAmount(item.quantity, item.price);
        }, 0);
      },
    [calculateItemAmount]
  );

  // 计算总金额
  const calculateTotalAmount = useMemo(
    () =>
      (sections = []) => {
        if (!Array.isArray(sections)) return 0;
        return sections.reduce((sum, section) => {
          if (!section) return sum;
          return sum + calculateSectionTotal(section.items);
        }, 0);
      },
    [calculateSectionTotal]
  );

  // 格式化货币
  const formatCurrency = useMemo(
    () =>
      (amount, currency = currentCurrency) => {
        const safeAmount = Number(amount) || 0;
        return `${CURRENCY_SYMBOLS[currency] || ""}${safeAmount.toLocaleString(
          "zh-CN",
          {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          }
        )}`;
      },
    [currentCurrency]
  );

  // 处理表单值变化
  const handleValuesChange = (changedValues, allValues) => {
    console.log("Form values changed:", allValues); // 调试用
    setFormValues(allValues);
    if (changedValues.currency) {
      setCurrentCurrency(changedValues.currency);
    }
  };

  // 修改初始值，确保每个项目都有唯一ID
  const initialValues = {
    currency: "CNY",
    sections: [
      {
        key: uuidv4(),
        sectionName: "服务类型 1",
        items: [
          {
            key: uuidv4(),
            productName: "",
            quantity: 1,
            price: 0,
            note: "",
            unit: "",
          },
        ],
      },
    ],
  };

  // 改添加小节的函数
  const handleAddSection = () => {
    setTemplateModalVisible(true);
    fetchAvailableSections();
  };

  // 修改添加项目的函数
  const handleAddItem = (add, sectionIndex) => {
    add({
      key: uuidv4(),
      productName: "",
      quantity: 1,
      price: 0,
      note: "",
    });
  };

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

      if (error) throw error;

      if (data?.attributes) {
        const formData = {
          quataName: data.attributes.quataName,
          customers: data.attributes.customers.map((customer) => customer.id) || [],
          description: data.attributes.description,
          currency: data.attributes.currency || "CNY",
          sections: data.attributes.sections.map((section) => ({
            key: uuidv4(),
            sectionName: section.sectionName,
            items: section.items.map((item) => ({
              key: uuidv4(),
              productName: item.name,
              quantity: Number(item.quantity) || 0,
              price: Number(item.price) || 0,
              note: item.description || "",
              unit: item.unit || "",
            })),
          })),
          taxRate: data.attributes.taxRate || 0,
          discount: data.attributes.discount || 0,
        };

        form.setFieldsValue(formData);
        setFormValues(formData);
        setCurrentCurrency(data.attributes.currency || "CNY");
        setTaxRate(data.attributes.taxRate || 0);
        setDiscount(data.attributes.discount || 0);

        if (data.attributes.customers) {
          setSelectedCustomers(data.attributes.customers);
        }
      }
    } catch (error) {
      console.error("获取报价单详情失败:", error);
      message.error("获取报价单详情失败");
    } finally {
      setLoading(false);
    }
  };

  // 添加获取可用小节模板的方法
  const fetchAvailableSections = async () => {
    try {
      const { data: sections, error } = await supabase
        .from("resources")
        .select("*")
        .eq("type", "sections")
        .order("created_at", { ascending: false });

      if (error) throw error;
      setAvailableSections(sections || []);
    } catch (error) {
      message.error("获取小节模版失败");
      console.error(error);
    }
  };

  // 使用选中的模版
  const handleUseTemplate = (template) => {
    const sections = form.getFieldValue("sections") || [];
    const newSection = {
      key: uuidv4(),
      sectionName: template.attributes.name,
      items: (template.attributes.items || []).map((item) => ({
        key: uuidv4(),
        productName: item.name || "",
        note: item.description || "",
        price: item.price || 0,
        quantity: item.quantity || 1,
        unit: item.unit || "",
      })),
    };

    const newSections = [...sections, newSection];
    form.setFieldValue("sections", newSections);
    
    // 更新 formValues 以触发重新计算
    const currentFormValues = form.getFieldsValue();
    setFormValues({
      ...currentFormValues,
      sections: newSections,
    });
    
    setTemplateModalVisible(false);
    message.success("套用模版成功");
  };

  // 创建自定义小节
  const handleCreateCustom = () => {
    const sections = form.getFieldValue("sections") || [];
    const newSection = {
      key: uuidv4(),
      sectionName: `服务类型 ${sections.length + 1}`,
      items: [
        {
          key: uuidv4(),
          productName: "",
          note: "",
          price: 0,
          quantity: 1,
          unit: "",
        },
      ],
    };

    form.setFieldValue("sections", [...sections, newSection]);
    setTemplateModalVisible(false);
  };

  // 添加模板选择弹窗内容渲染方法
  const renderTemplateModalContent = () => (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {availableSections.map((section) => (
          <div
            key={section.id}
            className="group relative bg-white dark:bg-gray-800 rounded-lg shadow-sm 
              border border-gray-200 dark:border-gray-700 hover:shadow-lg 
              transition-all duration-300 cursor-pointer"
            onClick={() => handleUseTemplate(section)}
          >
            <div className="p-6">
              {/* 标题和项目数量 */}
              <div className="text-center mb-4">
                <h3
                  className="text-lg font-medium text-gray-900 dark:text-gray-100 
                  group-hover:text-blue-500 transition-colors"
                >
                  {section.attributes.name}
                </h3>
                <div className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  {section.attributes.items?.length || 0} 个项目
                </div>
              </div>

              {/* 项目列表预览 */}
              <div className="space-y-2 mt-4 border-t dark:border-gray-700 pt-4">
                {(section.attributes.items || [])
                  .slice(0, 3)
                  .map((item, index) => (
                    <div
                      key={index}
                      className="flex justify-between items-center"
                    >
                      <span className="text-sm text-gray-600 dark:text-gray-300 truncate flex-1">
                        {item.name}
                      </span>
                      <span className="text-sm text-gray-500 dark:text-gray-400 ml-2">
                        {formatCurrency(item.price)}
                      </span>
                    </div>
                  ))}
                {(section.attributes.items || []).length > 3 && (
                  <div className="text-sm text-gray-500 dark:text-gray-400 text-center">
                    还有 {section.attributes.items.length - 3} 个项目...
                  </div>
                )}
              </div>

              {/* 小节总金额 */}
              <div className="mt-4 pt-4 border-t dark:border-gray-700 flex justify-between items-center">
                <span className="text-sm text-gray-600 dark:text-gray-300">
                  总金额
                </span>
                <span className="text-base font-medium text-blue-500">
                  {formatCurrency(
                    (section.attributes.items || []).reduce(
                      (sum, item) =>
                        sum + (item.price * (item.quantity || 1) || 0),
                      0
                    )
                  )}
                </span>
              </div>
            </div>

            {/* 悬边框效果 */}
            <div
              className="absolute inset-0 border-2 border-transparent 
              group-hover:border-blue-500 rounded-lg transition-colors duration-300"
            />

            {/* 选择指示器 */}
            <div
              className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 
              transition-opacity duration-300"
            >
              <Button
                type="primary"
                size="small"
                className="flex items-center gap-1"
                icon={<PlusOutlined />}
              >
                套用
              </Button>
            </div>
          </div>
        ))}
      </div>

      {availableSections.length === 0 && (
        <div className="text-center py-8">
          <div className="text-gray-500 dark:text-gray-400">暂无可用模版</div>
        </div>
      )}

      <Divider className="dark:border-gray-700" />

      <div className="flex justify-center">
        <Button
          type="dashed"
          icon={<PlusOutlined />}
          onClick={handleCreateCustom}
          className="w-1/3 border-2 hover:border-blue-400 hover:text-blue-500 
            dark:border-gray-600 dark:text-gray-400 dark:hover:text-blue-400
            transition-all duration-300"
        >
          自定义小节
        </Button>
      </div>
    </div>
  );

  const fetchTemplateData = async () => {
    try {
      setLoading(true);
      const { data: template, error } = await supabase
        .from("resources")
        .select("*")
        .eq("type", "serviceTemplate")
        .eq("id", templateId)
        .single();

      if (error) throw error;

      if (template?.attributes) {
        const quotationData = {
          quataName: template.attributes.templateName,
          description: template.attributes.description,
          currency: "CNY",
          category: template.attributes.category,
          sections: template.attributes.sections.map((section) => ({
            key: uuidv4(),
            sectionName: section.sectionName,
            items: section.items.map((item) => ({
              key: uuidv4(),
              productName: item.name,
              quantity: item.quantity,
              price: item.price,
              note: item.description,
              unit: item.unit,
            })),
          })),
        };

        form.setFieldsValue(quotationData);
        setFormValues(quotationData);
      }
    } catch (error) {
      console.error("获取模板数据失败:", error);
      message.error("获取模板数据失败");
    } finally {
      setLoading(false);
    }
  };

  // 使用 useMemo 计算税后金额
  const afterTaxAmount = useMemo(() => {
    const beforeTaxAmount = calculateTotalAmount(formValues?.sections) || 0;
    const taxAmount = beforeTaxAmount * (taxRate / 100);
    return beforeTaxAmount + taxAmount;
  }, [formValues?.sections, taxRate, calculateTotalAmount]);

  // 修改保存函数
  const onFinish = async (values) => {
    try {
      setLoading(true);
      const beforeTaxAmount = calculateTotalAmount(values.sections);
      
      const quotationData = {
        type: "quota",
        attributes: {
          quataName: values.quataName,
          customers: customers
            .filter(customer => values.customers.includes(customer.id))
            .map(customer => ({
              id: customer.id,
              name: customer.attributes.name
            })),
          description: values.description,
          currency: currentCurrency,
          sections: values.sections.map((section) => ({
            sectionName: section.sectionName,
            items: section.items.map((item) => ({
              name: item.productName,
              unit: item.unit,
              price: item.price,
              quantity: item.quantity,
              description: item.note,
            })),
          })),
          beforeTaxAmount,
          taxRate,
          afterTaxAmount,
          discount,
          finalAmount: discount || afterTaxAmount,
        },
      };

      let result;
      if (id) {
        result = await supabase
          .from("resources")
          .update(quotationData)
          .eq("id", id)
          .select();
      } else {
        result = await supabase
          .from("resources")
          .insert([quotationData])
          .select();
      }

      if (result.error) throw result.error;

      message.success("保存成功");
      navigate("/company/quotation");
    } catch (error) {
      console.error("保存失败:", error);
      message.error("保存失败");
    } finally {
      setLoading(false);
    }
  };

  const fetchCustomers = async () => {
    try {
      const { data, error } = await supabase
        .from("resources")
        .select("*")
        .eq("type", "customer");

      if (error) throw error;
      setCustomers(data || []);
    } catch (error) {
      console.error("获取客户列表失败:", error);
    }
  };

  useEffect(() => {
    fetchCustomers();
  }, []);

  const renderItemFields = (itemField, itemIndex, sectionIndex) => (
    <div 
      key={`${sectionIndex}-${itemIndex}-${itemField.key}`}
      className="grid grid-cols-[3fr_4fr_1fr_1fr_2fr_1fr_40px] gap-4 mb-4 items-start"
    >
      <Form.Item
        {...itemField}
        name={[itemField.name, "productName"]}
        className="!mb-0"
      >
        <Input placeholder="服务项目名称" />
      </Form.Item>
      <Form.Item
        {...itemField}
        name={[itemField.name, "note"]}
        className="!mb-0"
      >
        <Input placeholder="请输入描述/备注" />
      </Form.Item>
      <Form.Item
        {...itemField}
        name={[itemField.name, "unit"]}
        className="!mb-0"
      >
        <Input placeholder="单位" />
      </Form.Item>
      <Form.Item
        {...itemField}
        name={[itemField.name, "quantity"]}
        className="!mb-0"
      >
        <InputNumber placeholder="数量" min={0} className="w-full" />
      </Form.Item>
      <Form.Item
        {...itemField}
        name={[itemField.name, "price"]}
        className="!mb-0"
      >
        <InputNumber placeholder="单价" min={0} className="w-full" />
      </Form.Item>
      <div className="text-right">
        <span className="text-gray-500">
          {formatCurrency(
            calculateItemAmount(
              formValues?.sections?.[sectionIndex]?.items?.[itemIndex]
                ?.quantity,
              formValues?.sections?.[sectionIndex]?.items?.[itemIndex]?.price
            )
          )}
        </span>
      </div>
      {!isView && itemFields.length > 1 && (
        <Button
          type="text"
          danger
          icon={<DeleteOutlined />}
          onClick={() => removeItem(itemField.name)}
          className="flex items-center justify-center"
        />
      )}
    </div>
  );

  // 确保在组件加载时正确获取数据
  useEffect(() => {
    if (id) {
      fetchQuotationDetail();
    } else if (templateId) {
      fetchTemplateData();
    } else {
      // 如果既不是编辑也不是从模板创建，则设置初始值
      form.setFieldsValue(initialValues);
      setFormValues(initialValues);
    }
  }, [id, templateId]);

  // 处理小节名称编辑
  const handleSectionNameEdit = (sectionIndex, initialValue) => {
    setEditingSectionIndex(sectionIndex);
    setEditingSectionName(initialValue || "");
  };

  // 保存小节名称
  const handleSectionNameSave = () => {
    if (!editingSectionName.trim()) {
      message.error("请输入小节名称");
      return;
    }

    const sections = form.getFieldValue("sections");
    const newSections = [...sections];
    newSections[editingSectionIndex] = {
      ...newSections[editingSectionIndex],
      sectionName: editingSectionName.trim(),
    };
    form.setFieldValue("sections", newSections);
    setEditingSectionIndex(null);
    setEditingSectionName("");
  };

  // 取消编辑
  const handleSectionNameCancel = () => {
    setEditingSectionIndex(null);
    setEditingSectionName("");
  };

  return (
    <div className="bg-gradient-to-b from-gray-50 to-white min-h-screen p-6">
      <Card
        className="shadow-lg rounded-lg border-0"
        title={
          <div className="flex justify-between items-center py-2">
            <div className="flex items-center space-x-3">
              <Title level={4} className="mb-0 text-gray-800">
                {id ? (isEdit ? "编辑报价单" : "查看报价单") : "新建报价单"}
              </Title>
              <span className="text-gray-400 text-sm">
                {id
                  ? isEdit
                    ? "请修改报价单信息"
                    : "报价单详情"
                  : "请填写报价单信息"}
              </span>
            </div>
            <Space size="middle">
              <Button
                icon={<ArrowLeftOutlined />}
                onClick={() => navigate("/company/quotation")}
              >
                返回
              </Button>
              {!isView && (
                <Button
                  type="primary"
                  icon={<SaveOutlined />}
                  onClick={() => form.submit()}
                  loading={loading}
                >
                  保存
                </Button>
              )}
            </Space>
          </div>
        }
      >
        <Form
          form={form}
          onFinish={onFinish}
          onValuesChange={handleValuesChange}
          layout="vertical"
          disabled={isView}
          initialValues={initialValues}
        >
          {/* 基本信息卡片 */}
          <Card
            className="shadow-sm rounded-lg"
            type="inner"
            title={
              <span className="flex items-center space-x-2 text-gray-700">
                <span className="w-1 h-4 bg-blue-500 rounded-full" />
                <span>基本信息</span>
              </span>
            }
            bordered={false}
          >
            <div className="grid grid-cols-2 gap-8">
              <Form.Item
                name="quataName"
                label={
                  <span className="text-gray-700 font-medium">活动名称</span>
                }
                rules={[{ required: true, message: "活动名称" }]}
              >
                <Input
                  placeholder="请输入活动名"
                  className="rounded-md hover:border-blue-400 focus:border-blue-500"
                />
              </Form.Item>

              <Form.Item
                name="currency"
                label={<span className="text-gray-700 font-medium">货币类型</span>}
                rules={[{ required: true, message: "请选择货币类型" }]}
              >
                <Select className="w-full">
                  <Select.Option value="CNY">RMB</Select.Option>
                  <Select.Option value="TWD">台币</Select.Option>
                  <Select.Option value="USD">美元</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="customers"
                label={<span className="text-gray-700 font-medium">客户名称</span>}
                rules={[{ required: true, message: "请选择至少一个客户" }]}
              >
                <Select
                  mode="multiple"
                  placeholder="请选择客户"
                  className="rounded-md hover:border-blue-400 focus:border-blue-500"
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
                  }
                  options={customers.map((customer) => ({
                    value: customer.id,
                    label: customer.attributes.name,
                  }))}
                  value={(formValues.customers || []).map(customer => customer.id)}
                />
              </Form.Item>
            </div>
          </Card>

          {/* 报价单细卡片 */}
          <Form.List name="sections">
            {(fields, { add, remove }) => (
              <>
                <div className="space-y-4">
                  {fields.map((field, sectionIndex) => (
                    <Card
                      key={`section-${field.key}`}
                      className="shadow-sm rounded-lg"
                      type="inner"
                      title={
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            {editingSectionIndex === sectionIndex ? (
                              <div className="flex items-center gap-2">
                                <Input
                                  value={editingSectionName}
                                  onChange={(e) =>
                                    setEditingSectionName(e.target.value)
                                  }
                                  onPressEnter={handleSectionNameSave}
                                  autoFocus
                                  className="w-48"
                                />
                                <Button
                                  type="link"
                                  icon={<CheckOutlined />}
                                  onClick={handleSectionNameSave}
                                  className="text-green-500 hover:text-green-600"
                                />
                                <Button
                                  type="link"
                                  icon={<CloseOutlined />}
                                  onClick={handleSectionNameCancel}
                                  className="text-red-500 hover:text-red-600"
                                />
                              </div>
                            ) : (
                              <div className="flex items-center gap-2">
                                <span className="w-1 h-4 bg-purple-500 rounded-full" />
                                <Text
                                  strong
                                  className="text-lg dark:text-gray-200"
                                >
                                  {form.getFieldValue([
                                    "sections",
                                    sectionIndex,
                                    "sectionName",
                                  ]) || `服务类�� ${sectionIndex + 1}`}
                                </Text>
                                {(!id || isEdit) && (
                                  <Button
                                    type="link"
                                    icon={<EditOutlined />}
                                    onClick={() =>
                                      handleSectionNameEdit(
                                        sectionIndex,
                                        form.getFieldValue([
                                          "sections",
                                          sectionIndex,
                                          "sectionName",
                                        ]) || `服务类型 ${sectionIndex + 1}`
                                      )
                                    }
                                    className="text-gray-400 hover:text-blue-500"
                                  />
                                )}
                              </div>
                            )}
                          </div>
                        </div>
                      }
                    >
                      <Form.List name={[field.name, "items"]}>
                        {(itemFields, { add: addItem, remove: removeItem }) => (
                          <>
                            {/* 表头 */}
                            <div className="grid grid-cols-[3fr_4fr_1fr_1fr_2fr_1fr_40px] gap-4 mb-2 text-gray-500 px-2">
                              <div>项目明细</div>
                              <div>描述/备注</div>
                              <div>单位</div>
                              <div className="text-center">数量</div>
                              <div className="text-center">单价</div>
                              <div className="text-right">小计</div>
                              <div>操作</div>
                            </div>
                            {itemFields.map((itemField, itemIndex) => (
                              <div
                                key={`${sectionIndex}-${itemIndex}`}
                                className="grid grid-cols-[3fr_4fr_1fr_1fr_2fr_1fr_40px] gap-4 mb-4 items-start"
                              >
                               <Form.Item
                                  {...itemField}
                                  name={[itemField.name, "productName"]}
                                  className="!mb-0"
                                >
                                  <Input placeholder="服务项目名称" />
                                </Form.Item>
                                <Form.Item
                                  {...itemField}
                                  name={[itemField.name, "note"]}
                                  className="!mb-0"
                                >
                                  <Input placeholder="请输入描述/备注" />
                                </Form.Item>
                                <Form.Item
                                  {...itemField}
                                  name={[itemField.name, "unit"]}
                                  className="!mb-0"
                                >
                                  <Input placeholder="单位" />
                                </Form.Item>
                                <Form.Item
                                  {...itemField}
                                  name={[itemField.name, "quantity"]}
                                  className="!mb-0"
                                >
                                  <InputNumber
                                    placeholder="数量"
                                    min={0}
                                    className="w-full"
                                  />
                                </Form.Item>
                                <Form.Item
                                  {...itemField}
                                  name={[itemField.name, "price"]}
                                  className="!mb-0"
                                >
                                  <InputNumber
                                    placeholder="单价"
                                    min={0}
                                    className="w-full"
                                  />
                                </Form.Item>
                                <div className="text-right">
                                  <span className="text-gray-500">
                                    {formatCurrency(
                                      calculateItemAmount(
                                        formValues?.sections?.[sectionIndex]
                                          ?.items?.[itemIndex]?.quantity,
                                        formValues?.sections?.[sectionIndex]
                                          ?.items?.[itemIndex]?.price
                                      )
                                    )}
                                  </span>
                                </div>
                                {!isView && (
                                  <Button
                                    type="text"
                                    danger
                                    icon={<DeleteOutlined />}
                                    onClick={() => removeItem(itemField.name)}
                                    className="flex items-center justify-center"
                                  />
                                )}
                              </div>
                            ))}

                            {!isView && (
                              <Button
                                type="dashed"
                                onClick={() =>
                                  handleAddItem(addItem, sectionIndex)
                                }
                                icon={<PlusOutlined />}
                                className="w-full hover:border-blue-400 hover:text-blue-500 mb-4"
                              >
                                添加服务项目
                              </Button>
                            )}

                            <div className="flex justify-end border-t pt-4">
                              <span className="text-gray-500">
                                小计总额：
                                <span className="text-blue-500 font-medium ml-2">
                                  {formatCurrency(
                                    calculateSectionTotal(
                                      formValues?.sections?.[sectionIndex]
                                        ?.items
                                    )
                                  )}
                                </span>
                              </span>
                            </div>
                          </>
                        )}
                      </Form.List>
                    </Card>
                  ))}
                </div>

                {/* Add section button */}
                {!isView && (
                  <div className="mt-6 flex justify-center">
                    <Button
                      type="dashed"
                      onClick={handleAddSection}
                      icon={<PlusOutlined />}
                      className="w-1/3 border-2 hover:border-blue-400 hover:text-blue-500"
                    >
                      新建小节
                    </Button>
                  </div>
                )}

                {/* 总金额统计 */}
                <div className="mt-6 space-y-4 pt-4 border-t">
                  <div className="flex justify-end items-center space-x-4">
                    <span className="text-gray-600 font-medium">税前总计:</span>
                    <span className="text-2xl font-semibold text-blue-600">
                      {formatCurrency(calculateTotalAmount(formValues?.sections))}
                    </span>
                  </div>
                  
                  <div className="flex justify-end items-center space-x-4">
                    <span className="text-gray-600">税率:</span>
                    <div style={{ width: '150px' }}>
                      <Input
                        value={taxRate}
                        suffix="%"
                        onChange={(e) => {
                          const value = e.target.value.replace(/[^\d]/g, '');
                          setTaxRate(Number(value) || 0);
                        }}
                      />
                    </div>
                  </div>

                  <div className="flex justify-end items-center space-x-4">
                    <span className="text-gray-600 font-medium">税后总计:</span>
                    <span className="text-xl font-semibold text-blue-600">
                      {formatCurrency(afterTaxAmount)}
                    </span>
                  </div>

                  <div className="flex justify-end items-center space-x-4">
                    <span className="text-gray-600">折扣价:</span>
                    <div style={{ width: '150px' }}>
                      <Input
                        value={discount}
                        prefix={CURRENCY_SYMBOLS[currentCurrency]}
                        onChange={(e) => {
                          const value = e.target.value.replace(/[^\d]/g, '');
                          setDiscount(Number(value) || 0);
                        }}
                      />
                    </div>
                  </div>

                  <div className="flex justify-end items-center space-x-4">
                    <span className="text-gray-600 font-medium">最终金额:</span>
                    <span className="text-2xl font-semibold text-blue-600">
                      {formatCurrency(discount || afterTaxAmount)}
                    </span>
                  </div>
                </div>

                <Card
                  className="shadow-sm rounded-lg"
                  type="inner"
                  title={
                    <span className="flex items-center space-x-2 text-gray-700">
                      <span className="w-1 h-4 bg-purple-500 rounded-full" />
                      <span>补充说明</span>
                    </span>
                  }
                  bordered={false}
                >
                  <Form.Item name="description" className="mb-0">
                    <TextArea
                      rows={4}
                      placeholder="请输入补充说明信息"
                      className="rounded-md hover:border-purple-400 focus:border-purple-500"
                    />
                  </Form.Item>
                </Card>
              </>
            )}
          </Form.List>
        </Form>
      </Card>
      <Modal
        title={
          <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">
            选择小节模版
          </h3>
        }
        open={templateModalVisible}
        onCancel={() => setTemplateModalVisible(false)}
        footer={null}
        width={800}
        className="dark:bg-gray-800"
        closeIcon={
          <CloseOutlined className="text-gray-500 dark:text-gray-400" />
        }
      >
        {renderTemplateModalContent()}
      </Modal>
    </div>
  );
};

export default QuotationForm;
