import { Link } from "react-router-dom";
import { useState, useEffect } from "react";
import { Table, Tag, Button, Modal } from "antd";
import { LineChartOutlined, ProfileOutlined } from "@ant-design/icons";
import {
  makeTextColumn,
  makeGroupColumn,
  makeColumn,
  makeNumericColumnPlanFact,
  makeDateSorter
} from "../../components/Table";
import { calcAndUpdateStatsBySections, makeFilterMinMaxFunction } from "./functions";
import { invokeWebApiWrapperAsync } from '../../components/factory';
import ChartDepthToDay from '../../components/charts/ChartDepthToDay';
import WellOperationsTable from './WellOperationsTable'
import { getOperations } from "./functions";

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

const filtersWellsType = [];

export default function ClusterWells({clusterData}) {

  const [selectedWellId, setSelectedWellId] = useState(0)
  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([]);

useEffect(() => {
  if (selectedWellId > 0) {
    invokeWebApiWrapperAsync(
      async () => {
        const operations = await getOperations(selectedWellId);
        
        setWellOperations(operations.operations)
        
        setTvdDataPlan(operations.plan)

        setTvdDataFact(operations.fact)

        setTvdDataForecast(operations.predict)
      },
      null,
      `Не удалось загрузить операции по скважине "${selectedWellId}"`,
    );
  }
}, [selectedWellId]);

  let tableData = clusterData.statsWells?.map((well) => {
    
    if (!filtersWellsType.some((el) => el.text === well.wellType))
    filtersWellsType.push({
      text: well.wellType,
      value: well.wellType,
    });

    return {
      key: well.caption,
      id: well.id,
      caption: well.caption,
      wellType: well.wellType,
      factStart: well.total?.fact?.start,
      factEnd: well.total?.fact?.end,
      periodPlan: (
        (new Date(well.total?.plan?.end) - new Date(well.total?.plan?.start)) /
          (1000 * 60 * 60 * 24)
      ),
      periodFact: (
        (new Date(well.total?.fact?.end) - new Date(well.total?.fact?.start)) /
          (1000 * 60 * 60 * 24)
      ),
      rateOfPenetrationPlan: well.total?.plan?.rop,
      rateOfPenetrationFact: well.total?.fact?.rop,
      routeSpeedPlan: well.total?.plan?.routeSpeed,
      routeSpeedFact: well.total?.fact?.routeSpeed,
      notProductiveTimePlan: well.total?.plan?.nonProductiveHours,
      notProductiveTimeFact: well.total?.fact?.nonProductiveHours,
      companies: well.companies
    };
  });

  calcAndUpdateStatsBySections(tableData ?? [], [
    "factStart",
    "factEnd",
    "periodPlan",
    "periodFact",
    "rateOfPenetrationPlan",
    "rateOfPenetrationFact",
    "routeSpeedPlan",
    "routeSpeedFact",
    "notProductiveTime",
  ]);

  const columns = [
    makeTextColumn("скв №", "caption", null, null, 
      (_, item) => (<Link to={`/well/${item.id}`}>{item.caption ?? '-'}</Link>
    )),
    makeTextColumn("Тип скв.", "wellType", filtersWellsType, null,
      (text) => text ?? '-'
    ),
    makeGroupColumn("Фактические сроки", [
      makeColumn("начало", "factStart", 
        {
          sorter: makeDateSorter('factStart'),
          render: (dateString) => !Number.isNaN(new Date(dateString).getTime()) 
                                  ? new Date(dateString).toLocaleString() 
                                  : '-'
        }
      ),
      makeColumn("окончание", "factEnd", 
        {
          sorter: makeDateSorter('factEnd'),
          render: (dateString) => !Number.isNaN(new Date(dateString).getTime()) 
                                  ? new Date(dateString).toLocaleString() 
                                  : '-'
        }
      ),
    ]),
    makeNumericColumnPlanFact(
      "Продолжительность", 
      "period", 
      filtersMinMax, 
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-'),
    makeNumericColumnPlanFact(
      "МСП", 
      "rateOfPenetration", 
      filtersMinMax, 
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-'),
    makeNumericColumnPlanFact(
      "Рейсовая скорость", 
      "routeSpeed", 
      filtersMinMax, 
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-'),
    makeNumericColumnPlanFact(
      "НПВ, сут", 
      "notProductiveTime", 
      filtersMinMax, 
      makeFilterMinMaxFunction,
      (number) => (!Number.isNaN(number) && number !== undefined) 
                  ? number.toFixed(2) 
                  : '-'),
    {
      title: "TVD",
      key: "tvd",
      render: (value) => <Button onClick={()=> {
        setSelectedWellId(value.id)
        setIsTVDModalVisible(true) 
      }}><LineChartOutlined /></Button>,
      align: 'center'
    },
    {
      title: "Операции",
      key: "operations",
      render: (value) => <Button onClick={()=> {
        setSelectedWellId(value.id)
        setIsOpsModalVisible(true) 
      }}><ProfileOutlined /></Button>,
      align: 'center'
    },
    {
      title: "Подрядчики",
      key: "companies",
      dataIndex: "companies",
      render: (item) =>
        item?.map((company) => <Tag key={company.caption} color="blue">{company.caption}</Tag>) ?? '-',
    },
  ];

  return (
    <div>
      <Table
        columns={columns}
        dataSource={tableData}
        size={"small"}
        bordered
        pagination={false}
        rowKey={(record) => record.caption}
      />

      <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>
    </div>
  );
}
