import {
  Card,
  Table,
  Button,
  Space,
  Input,
  message,
  Popconfirm,
  Form,
  Tag,
  Typography,
} from "antd";
import {
  DownOutlined,
  UpOutlined,
  EyeOutlined,
  EditOutlined,
} from "@ant-design/icons";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/config/supabase";
import UnitManagement from "@/pages/company/service/unit";
import Sections from "@/pages/company/service/sections";
import CategoryDrawer from "@/pages/company/service/classify";
const { Paragraph } = Typography;

const ServicePage = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [categories, setCategories] = useState([]);
  const navigate = useNavigate();
  const [editingKey, setEditingKey] = useState("");

  // 获取服务模板列表
  const fetchServices = async () => {
    try {
      setLoading(true);
      const { data: services, error } = await supabase
        .from("resources")
        .select("*")
        .eq("type", "serviceTemplate")
        .order("created_at", { ascending: false });

      if (error) throw error;
      setData(services);
    } catch (error) {
      console.error("获取服务模板失败:", error);
      message.error("获取服务模板失败");
    } finally {
      setLoading(false);
    }
  };

  // 添加获取分类数据的方法
  const fetchCategories = async () => {
    try {
      const { data: categoriesData, error } = await supabase
        .from('resources')
        .select('*')
        .eq('type', 'categories')
        .order('created_at', { ascending: false });

      if (error) throw error;
      setCategories(categoriesData || []);
    } catch (error) {
      console.error('获取分类数据失败:', error);
      message.error('获取分类数据失败');
    }
  };

  // 修改保存逻辑
  const handleSaveItem = async (record) => {
    try {
      setLoading(true);
      const { serviceId, sectionIndex, itemIndex } = record;

      // 找到当前服务模板
      const currentService = data.find((item) => item.id === serviceId);
      if (!currentService) {
        throw new Error("Service not found");
      }

      const newAttributes = {
        ...currentService.attributes,
        templateName: currentService.attributes.templateName,
        description: currentService.attributes.description,
        category: currentService.attributes.category || [], // 确保 category 字段存在
        sections: currentService.attributes.sections.map((section, secIdx) => {
          if (secIdx === sectionIndex) {
            return {
              ...section,
              items: section.items.map((item, itemIdx) => {
                if (itemIdx === itemIndex) {
                  return {
                    name: record.name,
                    price: Number(record.price) || 0,
                    quantity: Number(record.quantity) || 0,
                    description: record.description || "",
                    unit: record.unit || "",
                  };
                }
                return item;
              }),
            };
          }
          return section;
        }),
      };

      // 重新计算总金额
      newAttributes.totalAmount = newAttributes.sections.reduce(
        (total, section) => {
          return (
            total +
            section.items.reduce(
              (sectionTotal, item) =>
                sectionTotal +
                (Number(item.price) || 0) * (Number(item.quantity) || 0),
              0
            )
          );
        },
        0
      );

      // 调用 supabase 更新数据
      const { error } = await supabase
        .from("resources")
        .update({
          type: "serviceTemplate",
          attributes: newAttributes,
        })
        .eq("id", serviceId);

      if (error) throw error;

      // 更新本地状态
      setData((prevData) =>
        prevData.map((item) =>
          item.id === serviceId ? { ...item, attributes: newAttributes } : item
        )
      );

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

  // 添加删除项目的方法
  const handleDeleteItem = async (record) => {
    try {
      setLoading(true);
      const { serviceId, sectionIndex, itemIndex } = record;

      // 找到目标服务
      const targetService = data.find((item) => item.id === serviceId);
      if (!targetService) throw new Error("Service not found");

      // 创建新的 attributes 对象，避免直接修改状态
      const newAttributes = {
        ...targetService.attributes,
        sections: targetService.attributes.sections.map((section, secIdx) => {
          if (secIdx === sectionIndex) {
            return {
              ...section,
              items: section.items.filter((_, idx) => idx !== itemIndex),
            };
          }
          return section;
        }),
      };

      // 重新计算总金额
      newAttributes.totalAmount = newAttributes.sections.reduce(
        (total, section) => {
          return (
            total +
            section.items.reduce(
              (sectionTotal, item) =>
                sectionTotal +
                (Number(item.price) || 0) * (Number(item.quantity) || 0),
              0
            )
          );
        },
        0
      );

      // 调用 supabase 更新数据
      const { error } = await supabase
        .from("resources")

        .update({
          attributes: newAttributes,
        })
        .eq("id", serviceId);

      if (error) throw error;

      // 更新本地状态
      setData((prevData) =>
        prevData.map((item) =>
          item.id === serviceId ? { ...item, attributes: newAttributes } : item
        )
      );

      message.success("删除成功");
    } catch (error) {
      console.error("删除失败:", error);
      message.error("删除失败");
    } finally {
      setLoading(false);
    }
  };

  // 添加删除服务模板的方法
  const handleDeleteService = async (serviceId) => {
    try {
      setLoading(true);

      // 调用 supabase 删除数据
      const { error } = await supabase
        .from("resources")
        .delete()
        .eq("id", serviceId);

      if (error) throw error;

      // 更新本地状态
      setData((prevData) => prevData.filter((item) => item.id !== serviceId));
      message.success("删除成功");
    } catch (error) {
      console.error("删除失败:", error);
      message.error("删除失败");
    } finally {
      setLoading(false);
    }
  };

  // 主表格列定义
  const columns = [
    {
      title: "模板名称",
      dataIndex: ["attributes", "templateName"],
      key: "templateName",
      className: "min-w-[200px]",
    },
    {
      title: "分类",
      dataIndex: ["attributes", "category"],
      key: "category",
      render: (categories) => {
        if (!categories || !Array.isArray(categories)) return null;
        
        return (
          <Paragraph
            ellipsis={{
              rows: 1,
              tooltip: (
                <Space size={[0, 8]} wrap>
                  {categories.map((category) => (
                    <Tag
                      size="small"
                      key={category.id}
                      color="blue"
                      className="px-2 py-1 rounded-md"
                    >
                      {category.name}
                    </Tag>
                  ))}
                </Space>
              ),
            }}
            className="mb-0"
          >
            <Space size={[0, 8]} nowrap>
              {categories.map((category) => (
                <Tag
                  size="small"
                  key={category.id}
                  color="blue"
                  className="px-2 py-1 rounded-md"
                >
                  {category.name}
                </Tag>
              ))}
            </Space>
          </Paragraph>
        );
      },
    },
    {
      title: "描述",
      dataIndex: ["attributes", "description"],
      key: "description",
      className: "min-w-[100px] ",
      render: (text) => (
        <Paragraph
          ellipsis={{
            rows: 2,
            tooltip: text,
          }}
          className="mb-0"
        >
          {text}
        </Paragraph>
      ),
    },
    {
      title: "总金额",
      dataIndex: ["attributes", "totalAmount"],
      key: "totalAmount",
      className: "min-w-[150px] text-right",
      render: (amount) => (
        <span style={{ color: "#f50", fontWeight: "bold" }}>
          ¥
          {amount?.toLocaleString("zh-CN", {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          }) || "0.00"}
        </span>
      ),
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      width: 220,
      render: (_, record) => (
        <Space onClick={(e) => e.stopPropagation()}>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() =>
              navigate(`/company/serviceTemplateInfo/${record.id}`)
            }
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() =>
              navigate(`/company/serviceTemplateInfo/${record.id}?edit=true`)
            }
          >
            编辑
          </Button>
          <Popconfirm
            title="删除确认"
            description="确定要删除这个服务模板吗？此操作不可恢复。"
            okText="确定"
            cancelText="取消"
            okButtonProps={{ danger: true }}
            onConfirm={() => handleDeleteService(record.id)}
          >
            <Button type="link" danger className="text-red-600">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 子表格列定义
  const itemColumns = [
    {
      title: "项目名称",
      dataIndex: "name",
      key: "name",
      width: "25%",
      render: (text, record) => {
        const isEditing = record.key === editingKey;
        return isEditing ? (
          <Form.Item
            key={`name-${record.key}`}
            name={[record.sectionIndex, "items", record.itemIndex, "name"]}
            className="!mb-0"
          >
            <Input
              value={text}
              onChange={(e) => {
                const newData = [...data];
                const targetService = newData.find(
                  (item) => item.id === record.serviceId
                );
                const targetItem =
                  targetService.attributes.sections[record.sectionIndex].items[
                    record.itemIndex
                  ];
                targetItem.name = e.target.value;
                setData(newData);
              }}
            />
          </Form.Item>
        ) : (
          text
        );
      },
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
      width: "25%",
      render: (text, record) => {
        const isEditing = record.key === editingKey;
        return isEditing ? (
          <Form.Item
            name={[
              record.sectionIndex,
              "items",
              record.itemIndex,
              "description",
            ]}
            className="!mb-0"
          >
            <Input
              value={text}
              onChange={(e) => {
                const newData = [...data];
                const targetService = newData.find(
                  (item) => item.id === record.serviceId
                );
                const targetItem =
                  targetService.attributes.sections[record.sectionIndex].items[
                    record.itemIndex
                  ];
                targetItem.description = e.target.value;
                setData(newData);
              }}
            />
          </Form.Item>
        ) : (
          <Paragraph
            ellipsis={{
              rows: 2,
              tooltip: text,
            }}
            className="mb-0"
          >
            {text}
          </Paragraph>
        );
      },
    },
    {
      title: "单价",
      dataIndex: "price",
      key: "price",
      width: "15%",
      render: (price, record) => {
        const isEditing = record.key === editingKey;
        return isEditing ? (
          <Input
            type="number"
            value={price}
            onChange={(e) => {
              const newData = [...data];
              const targetService = newData.find(
                (item) => item.id === record.serviceId
              );
              const targetItem =
                targetService.attributes.sections[record.sectionIndex].items[
                  record.itemIndex
                ];
              targetItem.price = Number(e.target.value);
              setData(newData);
            }}
          />
        ) : (
          <span className="text-gray-600">
            ¥
            {price?.toLocaleString("zh-CN", {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
    {
      title: "数量",
      dataIndex: "quantity",
      key: "quantity",
      width: "15%",
      render: (quantity, record) => {
        const isEditing = record.key === editingKey;
        return isEditing ? (
          <Input
            type="number"
            value={quantity}
            onChange={(e) => {
              const newData = [...data];
              const targetService = newData.find(
                (item) => item.id === record.serviceId
              );
              const targetItem =
                targetService.attributes.sections[record.sectionIndex].items[
                  record.itemIndex
                ];
              targetItem.quantity = Number(e.target.value);
              setData(newData);
            }}
          />
        ) : (
          <span className="text-gray-600">{quantity}</span>
        );
      },
    },
    {
      title: "小计",
      key: "subtotal",
      width: "20%",
      render: (_, record) => (
        <span className="text-blue-600 font-medium">
          ¥
          {((record.price || 0) * (record.quantity || 0)).toLocaleString(
            "zh-CN",
            {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            }
          )}
        </span>
      ),
    },
    {
      title: "操作",
      key: "action",
      width: "150px",
      render: (_, record) => {
        const isEditing = record.key === editingKey;
        return isEditing ? (
          <Space>
            <Button
              type="link"
              size="small"
              className="text-green-600"
              onClick={() =>
                handleSaveItem(record, record.sectionIndex, record.itemIndex)
              }
            >
              保存
            </Button>
            <Button
              type="link"
              size="small"
              className="text-gray-600"
              onClick={() => setEditingKey("")}
            >
              取消
            </Button>
          </Space>
        ) : (
          <Space>
            <Button
              type="link"
              size="small"
              className="text-blue-600"
              disabled={editingKey !== ""}
              onClick={() => setEditingKey(record.key)}
            >
              编辑
            </Button>
            <Popconfirm
              title="删除确认"
              description="确定要删除这个项目吗？"
              okText="确定"
              cancelText="取消"
              okButtonProps={{ danger: true }}
              onConfirm={() => handleDeleteItem(record)}
            >
              <Button
                type="link"
                size="small"
                className="text-red-600"
                disabled={editingKey !== ""}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  // 修改 expandedRowRender 函数，确保 key 的唯一性
  const expandedRowRender = (record) => (
    <div className="bg-white dark:bg-gray-800 p-4 rounded-lg">
      {record.attributes.sections?.map((section, sectionIndex) => (
        <Card
          key={`${record.id}-section-${sectionIndex}`}
          className="mb-4 shadow-sm border-blue-100 dark:border-blue-900/30 hover:shadow-md transition-shadow duration-300"
          title={
            <div className="flex items-center justify-between py-2">
              <span className="text-lg font-medium text-blue-600 dark:text-blue-400">
                {section.sectionName || `服务类型 ${sectionIndex + 1}`}
              </span>
              <span className="text-blue-600 dark:text-blue-400 font-medium">
                总计: ¥
                {section.items
                  .reduce(
                    (total, item) =>
                      total +
                      (Number(item.price) || 0) * (Number(item.quantity) || 0),
                    0
                  )
                  .toLocaleString("zh-CN", {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  })}
              </span>
            </div>
          }
          headStyle={{
            background: "rgba(59, 130, 246, 0.05)",
            borderBottom: "1px solid rgba(59, 130, 246, 0.1)",
          }}
          style={{
            background: "rgba(59, 130, 246, 0.02)",
          }}
        >
          <Table
            columns={itemColumns}
            dataSource={section.items.map((item, itemIndex) => ({
              ...item,
              key: `${record.id}-${sectionIndex}-${itemIndex}`,
              serviceId: record.id,
              sectionIndex,
              itemIndex,
            }))}
            pagination={false}
            className="rounded-lg overflow-hidden"
            rowClassName="hover:bg-blue-50/50 dark:hover:bg-blue-900/20 transition-colors"
          />
        </Card>
      ))}
    </div>
  );

  useEffect(() => {
    fetchServices();
    fetchCategories();
  }, []);

  return (
    <div className="min-h-screen">
      <Card
        title={<span className="text-xl font-medium">服务模版管理</span>}
        className="h-full w-full overflow-auto"
        extra={
          <Space>
            <Sections />
            <UnitManagement />
            <CategoryDrawer />

            <Button
              type="primary"
              onClick={() => navigate("/company/serviceTemplateInfo")}
            >
              新建模版
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey="id"
          scroll={{ x: true }}
          expandable={{
            expandedRowRender,
            expandRowByClick: true,
            expandIcon: ({ expanded, onExpand, record }) => (
              <Button
                type="link"
                onClick={(e) => {
                  e.stopPropagation();
                  onExpand(record, e);
                }}
                icon={expanded ? <UpOutlined /> : <DownOutlined />}
                className={`
                  transition-all duration-300
                  ${
                    expanded
                      ? "text-blue-600"
                      : "text-gray-400 hover:text-blue-600"
                  }
                `}
              />
            ),
            rowExpandable: (record) => record.attributes.sections?.length > 0,
          }}
          className="rounded-lg overflow-hidden"
          rowClassName={(record, index) => `
            cursor-pointer transition-colors
            ${
              index % 2 === 0
                ? "bg-white dark:bg-gray-800"
                : "bg-gray-50 dark:bg-gray-750"
            }
            hover:bg-blue-50 dark:hover:bg-blue-900/20
          `}
          expandedRowClassName={() => "bg-blue-50/50 dark:bg-blue-900/10"}
        />
      </Card>
    </div>
  );
};

export default ServicePage;
