import {commonPopupConfig,} from "./config";
import {Button, Col, Row} from "antd";
import {isNil} from "../../../utils.js";
import {useGetRegions} from "../../../components/RegionSelect.jsx";
import {useSimulateAccident} from "../../../stores/useSimulateAccident.js";
import {useWeatherFilter} from "../../../dzkh-features/WeatherSlider/useWeatherFilter.js";
import {tempMapper} from "../../../config.js";

const dynamicFields = [
  {
    field: 'prob1',
    name: 'No heating in the building'
  },{
    field: 'prob2',
    name: 'Leaking pipes in the entrance'
  },{
    field: 'prob3',
    name: 'Apartment temperature below standard'
  },{
    field: 'prob4',
    name: 'Common area temperature below standard'
  },{
    field: 'prob5',
    name: 'Leak in the heating system'
  },{
    field: 'cooling_time',
    name: 'Cooling time (hours)'
  },{
    field: 'priority',
    name: 'Building priority'
  }
]

export const FeatureProperties = ({ feature }) => {
  const { data } = useGetRegions();
  const { setSelectedSourceConfig } = useSimulateAccident();
  const { value: temperature } = useWeatherFilter();

  const isSourcePoint = feature.properties.point_type === 'tp'
  const isDispatcherPoint = feature.properties.point_type === 'ods'

  const getConfig = () => {
    if (isDispatcherPoint) return commonPopupConfig

    if (isSourcePoint) {
      return [
        ...commonPopupConfig, {field: `prob6_${tempMapper[temperature]}`, name: 'TP failure'}
      ]
    }

    const additionalFields = dynamicFields.map((item) => {
      return {
        ...item,
        field: `${item.field}_${tempMapper[temperature]}`,
      }
    })
    return [...commonPopupConfig, ...additionalFields];
  };

  const getValue = ({ field, render, empty, type, fallbackField }) => {
    let value = feature.properties[field];

    if (type === "region") {
      value = value ? value : feature[fallbackField];
      value = render(value, data?.normalized);
    } else {
      value = render ? render(value) : value;
      value = isNil(value) && empty ? empty : value;
    }

    return value;
  };

  const simulateAccident = () => setSelectedSourceConfig({
      pointId: feature.properties.id,
      sourceId: feature.properties.tp_number,
      dispatcherNumber: feature.properties.ods_number
    });

  return (
    <div>
      {getConfig().map((row) => {
        return (
          <Row className={"p-1"} key={row.field}>
            <Col className={"font-semibold"} span={12}>
              {row.name}
            </Col>
            <Col span={12} className={'text-right'}>{getValue(row)}</Col>
          </Row>
        );
      })}
      {isSourcePoint ?
        <div className={'mt-3 text-center'}>
          <Button type={'primary'} onClick={simulateAccident}>Simulate failure</Button>
        </div>
        : null}
    </div>
  );
};
