import { Table, Tag, Button, Badge, Divider, Modal } from "antd";
import { useParams, Link } from "react-router-dom";
import { LineChartOutlined, ProfileOutlined } from "@ant-design/icons";
import { useState, useEffect } from "react";
import {
  makeTextColumn,
  makeNumericColumnPlanFact
} from "../../components/Table";
import { invokeWebApiWrapperAsync } from '../../components/factory';
import { WellOperationStatService } from '../../services/api';
import ChartDepthToDay from '../../components/charts/ChartDepthToDay';
import WellOperationsTable from './WellOperationsTable'
import { calcAndUpdateStatsBySections, makeFilterMinMaxFunction } from "./functions";


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

const filtersSectionsType = [];


export default function ClusterSections({ clusterData }) {
  let { id } = useParams();
  const [wellsStat, setWellsStat] = useState([]);
  const [selectedWells, setSelectedWells] = useState([]);
  const [selectedWellsKeys, setSelectedWellsKeys] = useState([]);
  const [selectedWellId, setSelectedWellId] = useState([]);
  const [isTVDModalVisible, setIsTVDModalVisible] = useState(false)
  const [isOpsModalVisible, setIsOpsModalVisible] = useState(false)
  const [tvdDataPlan, setTvdDataPlan] = useState([]);
  const [tvdDataFact, setTvdDataFact] = useState([]);
  const [tvdDataForecast, setTvdDataForecast] = useState([]);
  const [wellOperations, setWellOperations] = useState([]);

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

  useEffect(() => {
    if (selectedWellId > 0) {
      invokeWebApiWrapperAsync(
        async () => {
          const operations = await WellOperationStatService.getTvd(selectedWellId);
          
          setWellOperations(operations)

          const tvdPlanData = operations.map(el => { 
            return {key: el.plan?.id, depth: el.plan?.wellDepth, date: el.plan?.startDate}
          }).filter(el => el.key)
          
          setTvdDataPlan(tvdPlanData)
  
          const tvdFactData = operations.map(el => { 
            return {key: el.fact?.id, depth: el.fact?.wellDepth, date: el.fact?.startDate}
          }).filter(el => el.key)
  
          setTvdDataFact(tvdFactData)
  
          const tvdPredictData = operations.map(el => { 
            return {key: el.predict?.id, depth: el.predict?.wellDepth, date: el.predict?.startDate}
          }).filter(el => el.key)
  
          setTvdDataForecast(tvdPredictData)
        },
        null,
        `Не удалось загрузить операции по скважине "${selectedWellId}"`,
      );
    }
  }, [selectedWellId]);

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

    clusterData.statsWells?.forEach((well) => {
      well.sections.forEach((section) => {
        let row = {
          key: well.caption + section.id,
          id: well.id,
          caption: well.caption,
          sectionType: section.caption,
          sectionWellDepthPlan: section.plan?.wellDepthEnd,
          sectionWellDepthFact: section.fact?.wellDepthEnd,
          sectionBuildDaysPlan: (
            (new Date(section.plan?.end) - new Date(section.plan?.start)) /
              (1000 * 60 * 60 * 24)
          ),
          sectionBuildDaysFact: (
            (new Date(section.fact?.end) - new Date(section.fact?.start)) /
              (1000 * 60 * 60 * 24)
          ),
          sectionRateOfPenetrationPlan: section.plan?.rop,
          sectionRateOfPenetrationFact: section.fact?.rop,
          sectionRouteSpeedPlan: section.plan?.routeSpeed,
          sectionRouteSpeedFact: section.fact?.routeSpeed,
          sectionBhaDownSpeedPlan: section.plan?.bhaDownSpeed,
          sectionBhaDownSpeedFact: section.fact?.bhaDownSpeed,
          sectionBhaUpSpeedPlan: section.plan?.bhaUpSpeed,
          sectionBhaUpSpeedFact: section.fact?.bhaUpSpeed,
          sectionCasingDownSpeedPlan: section.plan?.casingDownSpeed,
          sectionCasingDownSpeedFact: section.fact?.casingDownSpeed,
          nonProductiveTimePlan: section.plan?.nonProductiveHours,
          nonProductiveTimeFact: section.fact?.nonProductiveHours,
          companies: well.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 columns = [
    makeTextColumn("скв №", "caption", null, null, 
      (_, item) => <Link to={`/well/${item.id}`}>{item.caption ?? '-'}</Link>
    ),
    makeTextColumn("Секция", "sectionType", filtersSectionsType, null, 
      (_, item) => _ ?? '-'
    ),
    makeNumericColumnPlanFact(
      "Глубина", 
      "sectionWellDepth", 
      filtersMinMax, 
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-', 
    ),
    makeNumericColumnPlanFact(
      "Продолжительность",
      "sectionBuildDays",
      filtersMinMax,
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-', 
    ),
    makeNumericColumnPlanFact(
      "МСП", 
      "sectionRateOfPenetration", 
      filtersMinMax, 
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-', 
    ),
    makeNumericColumnPlanFact(
      "Рейсовая скорость",
      "sectionRouteSpeed",
      filtersMinMax,
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-', 
    ),
    makeNumericColumnPlanFact(
      "Спуск КНБК", 
      "sectionBhaDownSpeed", 
      filtersMinMax, 
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-', 
    ),
    makeNumericColumnPlanFact(
      "Подъем КНБК", 
      "sectionBhaUpSpeed", 
      filtersMinMax, 
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-', 
    ),
    makeNumericColumnPlanFact(
      "Скорость спуска ОК",
      "sectionCasingDownSpeed",
      filtersMinMax,
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-',  
    ),
    makeNumericColumnPlanFact(
      "НПВ, сут",
      "nonProductiveTime",
      filtersMinMax,
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-', 
      "70px"
    ),
    {
      title: "TVD",
      render: (value) => <Button onClick={()=> {
        setSelectedWellId(value.id)
        setIsTVDModalVisible(true) 
      }}><LineChartOutlined /></Button>,
      align: 'center'
    },
    {
      title: "Операции",
      render: (value) => <Button onClick={()=> {
        setSelectedWellId(value.id)
        setIsOpsModalVisible(true) 
      }}><ProfileOutlined /></Button>,
      align: 'center'
    },
    {
      title: "Подрядчики",
      dataIndex: "companies",
      render: (item) =>
        item?.map((company) => <Tag color="blue">{company.caption}</Tag>),
    },
  ];

  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}
      />

      <Modal
        title='TVD'
        centered
        visible={isTVDModalVisible}
        onCancel={() => setIsTVDModalVisible(false)}
        width={1500}
        footer={null}
      >
        <ChartDepthToDay 
          dataPlan={tvdDataPlan} 
          dataFact={tvdDataFact} 
          dataForecast={tvdDataForecast} />
      </Modal>

      <Modal
        title='Операции'
        centered
        visible={isOpsModalVisible}
        onCancel={() => setIsOpsModalVisible(false)}
        width={1500}
        footer={null}
      >
        <WellOperationsTable 
          wellOperations={wellOperations}
        />
      </Modal>
    </>
  );
}
