import { Table, Tag, Button, Badge, Divider, Modal } from "antd";
import { useParams } from "react-router-dom";
import { LineChartOutlined, ProfileOutlined } from "@ant-design/icons";
import { useState, useEffect } from "react";
import {
  makeTextColumn,
  makeNumericColumnPlanFact,
  calcAndUpdateStatsBySections,
} from "../../components/Table";

const filtersMinMax = [
  {
    text: "min",
    value: "min",
  },
  {
    text: "max",
    value: "max",
  },
];

const filtersSectionsType = [];

const ModalWindowButton = ({
  buttonIcon,
  buttonText,
  modalTitle,
  modalContent,
}) => {
  const [isModalVisible, setIsModalVisible] = useState(false);

  let content =
    typeof modalContent === "string" ? (
      <img src={modalContent} alt="" style={{ width: "100%" }} />
    ) : (
      modalContent
    );

  return (
    <>
      <Button
        type="secondary"
        onClick={() => setIsModalVisible(true)}
        icon={buttonIcon}
      >
        {buttonText}
      </Button>
      <Modal
        title={modalTitle}
        centered
        visible={isModalVisible}
        onOk={() => setIsModalVisible(false)}
        onCancel={() => setIsModalVisible(false)}
        width={1400}
      >
        {content}
      </Modal>
    </>
  );
};

const columns = [
  makeTextColumn("скв №", "caption"),
  makeTextColumn("Секция", "sectionType", filtersSectionsType),
  makeNumericColumnPlanFact("Глубина", "sectionWellDepth", filtersMinMax),
  makeNumericColumnPlanFact(
    "Продолжительность",
    "sectionBuildDays",
    filtersMinMax
  ), //Цикл строительства
  makeNumericColumnPlanFact("МСП", "sectionRateOfPenetration", filtersMinMax),
  makeNumericColumnPlanFact(
    "Рейсовая скорость",
    "sectionRouteSpeed",
    filtersMinMax
  ),
  makeNumericColumnPlanFact("Спуск КНБК", "sectionBhaDownSpeed", filtersMinMax), //Скорость спуска КНБК
  makeNumericColumnPlanFact("Подъем КНБК", "sectionBhaUpSpeed", filtersMinMax), //Скорость подъема КНБК
  makeNumericColumnPlanFact(
    "Скорость спуска ОК",
    "sectionCasingDownSpeed",
    filtersMinMax
  ),
  makeNumericColumnPlanFact(
    "НПВ, сут",
    "nonProductiveTime",
    filtersMinMax,
    "70px"
  ),
  {
    title: "TVD",
    render: (_, record) => (
      <ModalWindowButton
        buttonIcon={<LineChartOutlined />}
        modalTitle={`График по скв.:${record.caption}`}
      />
    ),
    //modalContent = {resources['Chart' + record.caption]}/>,
  },
  {
    title: "Операции",
    render: (_, record) => (
      <ModalWindowButton
        buttonIcon={<ProfileOutlined />}
        modalTitle={`Операции по скв.:${record.caption}`}
      />
    ),
    //modalContent = {resources['Table' + record.caption]},
  },
  {
    title: "Подрядчики",
    dataIndex: "companies",
    render: (item) =>
      item?.map((company) => <Tag color="blue">{company.caption}</Tag>),
  },
];

export default function ClusterSections({ clusterData }) {
  let { id } = useParams();
  const [wellsStat, setWellsStat] = useState([]);
  const [selectedWells, setSelectedWells] = useState([]);
  const [selectedWellsKeys, setSelectedWellsKeys] = useState([]);

  calcAndUpdateStatsBySections(wellsStat ?? [], [
    "sectionWellDepthPlan",
    "sectionWellDepthFact",
    "sectionBuildDaysPlan",
    "sectionBuildDaysFact",
    "sectionRateOfPenetrationPlan",
    "sectionRateOfPenetrationFact",
    "sectionRouteSpeedPlan",
    "sectionRouteSpeedFact",
    "sectionBhaDownSpeedPlan",
    "sectionBhaDownSpeedFact",
    "sectionBhaUpSpeedPlan",
    "sectionBhaUpSpeedFact",
    "sectionCasingDownSpeedPlan",
    "sectionCasingDownSpeedFact",
    "nonProductiveTimePlan",
    "nonProductiveTimeFact",
  ]);

  useEffect(() => {
    let rows = [];

    clusterData.statsWells?.forEach((el) => {
      el.sections.forEach((section) => {
        let row = {
          key: el.caption + section.id,
          id: el.caption + section.id,
          caption: el.caption,
          sectionType: section.caption,
          sectionWellDepthPlan: section.plan.wellDepthEnd,
          sectionWellDepthFact: section.fact.wellDepthEnd,
          sectionBuildDaysPlan: (
            Math.abs(
              new Date(section.plan.start) - new Date(section.plan.end)
            ) /
            (1000 * 60 * 60 * 24)
          ).toFixed(2),
          sectionBuildDaysFact: (
            Math.abs(
              new Date(section.fact.start) - new Date(section.fact.end)
            ) /
            (1000 * 60 * 60 * 24)
          ).toFixed(2),
          sectionRateOfPenetrationPlan: section.plan.rop.toFixed(2),
          sectionRateOfPenetrationFact: section.fact.rop.toFixed(2),
          sectionRouteSpeedPlan: section.plan.routeSpeed.toFixed(2),
          sectionRouteSpeedFact: section.fact.routeSpeed.toFixed(2),
          sectionBhaDownSpeedPlan: section.plan.bhaDownSpeed.toFixed(2),
          sectionBhaDownSpeedFact: section.fact.bhaDownSpeed.toFixed(2),
          sectionBhaUpSpeedPlan: section.plan.bhaUpSpeed.toFixed(2),
          sectionBhaUpSpeedFact: section.fact.bhaUpSpeed.toFixed(2),
          sectionCasingDownSpeedPlan: section.plan.casingDownSpeed.toFixed(2),
          sectionCasingDownSpeedFact: section.fact.casingDownSpeed.toFixed(2),
          nonProductiveTimePlan: section.plan.nonProductiveHours.toFixed(2),
          nonProductiveTimeFact: section.fact.nonProductiveHours.toFixed(2),
          companies: el.companies,
        };

        rows.push(row);

        if (!filtersSectionsType.some((el) => el.text === section.caption))
          filtersSectionsType.push({
            text: section.caption,
            value: section.caption,
          });
      });
    });

    setWellsStat(rows);
  }, [id, clusterData]);

  const rowSelection = {
    selectedRowKeys: selectedWellsKeys,
    onChange: (keys, items) => {
      setSelectedWells(items);
      setSelectedWellsKeys(keys);
    },
  };

  return (
    <>
      <Table
        columns={columns}
        dataSource={wellsStat}
        size={"small"}
        bordered
        scroll={{ x: true, y: 620 }}
        rowSelection={rowSelection}
        pagination={false}
      />
      <Divider />
      <Badge.Ribbon text="комбинированная скважина" color="gray">
        <h3>
          Выбранные секции<></>
        </h3>
      </Badge.Ribbon>
      <Table
        columns={columns}
        dataSource={selectedWells}
        rowSelection={rowSelection}
        size={"small"}
        bordered
        scroll={{ x: true }}
        pagination={false}
      />
    </>
  );
}
