import { useParams } from "react-router-dom";
import { Link } from "react-router-dom";
import { useState, useEffect } from "react";
import { Table, Tag, Button, Modal } from "antd";
import {
  makeTextColumn,
  makeGroupColumn,
  makeNumericColumn,
  makeNumericColumnPlanFact
} from "../../components/Table";
import { calcAndUpdateStatsBySections, makeFilterMinMaxFunction } from "./functions";
import { invokeWebApiWrapperAsync } from '../../components/factory';
import { WellOperationStatService } from '../../services/api';
import ChartDepthToDay from '../../components/charts/ChartDepthToDay';
import WellOperationsTable from './WellOperationsTable'

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

const filtersWellsType = [
  {
    text: "Наклонно-направленная",
    value: "Наклонно-направленная",
  },
  {
    text: "Горизонтальная",
    value: "Горизонтальная",
  },
];

export default function ClusterWells({ clusterData }) {
  let { id } = useParams();
  const [wellsStat, setWellsStat] = 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([]);

  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]);

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

  useEffect(() => {
    let tableData = clusterData.statsWells?.map((well) => {
      return {
        key: well.id,
        id: well.id,
        caption: well.caption,
        wellType: well.wellType,
        factStart: new Date(well.total.fact.start).toLocaleString(),
        factEnd: new Date(well.total.fact.end).toLocaleString(),
        periodPlan: (
          (new Date(well.total.plan.end) - new Date(well.total.plan.start)) /
            (1000 * 60 * 60 * 24)
        ).toFixed(2),
        periodFact: (
          (new Date(well.total.fact.end) - new Date(well.total.fact.start)) /
            (1000 * 60 * 60 * 24)
        ).toFixed(2),
        rateOfPenetrationPlan: well.total.plan.rop.toFixed(2),
        rateOfPenetrationFact: well.total.fact.rop.toFixed(2),
        routeSpeedPlan: well.total.plan.routeSpeed.toFixed(2),
        routeSpeedFact: well.total.fact.routeSpeed.toFixed(2),
        notProductiveTimePlan: well.total.plan.nonProductiveHours.toFixed(2),
        notProductiveTimeFact: well.total.fact.nonProductiveHours.toFixed(2),
        companies: well.companies,
      };
    });

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

  const columns = [
    makeTextColumn("скв №", "caption", null, null, (_, item) => (
      <Link to={`/well/${item.id}`}>{item.caption}</Link>
    )),
    makeTextColumn("Тип скв.", "wellType", filtersWellsType),
    makeGroupColumn("Фактические сроки", [
      makeNumericColumn("начало", "factStart"),
      makeNumericColumn("окончание", "factEnd"),
    ]),
    makeNumericColumnPlanFact("Продолжительность", "period", filtersMinMax, makeFilterMinMaxFunction),
    makeNumericColumnPlanFact("МСП", "rateOfPenetration", filtersMinMax, makeFilterMinMaxFunction),
    makeNumericColumnPlanFact("Рейсовая скорость", "routeSpeed", filtersMinMax, makeFilterMinMaxFunction),
    makeNumericColumnPlanFact("НПВ, сут", "notProductiveTime", filtersMinMax, makeFilterMinMaxFunction),
    {
      title: "График глубина-день",
      render: (value) => <Button onClick={()=> {
        setSelectedWellId(value.id)
        setIsTVDModalVisible(true) 
      }}>Открыть</Button>,
    },
    {
      title: "Таблица по операциям",
      render: (value) => <Button onClick={()=> {
        setSelectedWellId(value.id)
        setIsOpsModalVisible(true) 
      }}>Открыть</Button>,
    },
    {
      title: "Подрядчики",
      key: "companies",
      dataIndex: "companies",
      render: (item) =>
        item.map((company) => <Tag color="blue">{company.caption}</Tag>),
    },
  ];

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

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