import { apiQueryUserById } from '@/services/master/UserController';
import { apiGetPhoto } from '@/services/slave/sgw/PhotoController';
import { apiViewShip } from '@/services/slave/sgw/ShipController';
import { apiGetZoneById } from '@/services/slave/sgw/ZoneController';
import {
  convertWKTLineStringToLatLngArray,
  convertWKTPointToLatLng,
  convertWKTtoLatLngString,
  getAlarmTypeName,
  getCircleRadius,
} from '@/utils/slave/sgw/geomUtils';
import { ArrowRightOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { ProSkeleton } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useModel } from '@umijs/max';
import { Button, Space, Tabs, Tooltip } from 'antd';
import { MessageInstance } from 'antd/lib/message/interface';
import { useEffect, useState } from 'react';
import {
  BaseMap,
  DATA_LAYER,
  GPSParseResult,
  ShipDetailData,
  TEMPORARY_LAYER,
  ZoneAlarmParse,
} from '../type';
import ShipBasicInfo from './ShipBasicInfo';
import { ShipSpecificationTab, ShipTripInfoTab } from './ShipTabs';
import ShipWarningList from './ShipWarningList';

const ShipDetail = ({
  thing,
  messageApi,
  mapController,
}: {
  thing: SgwModel.SgwThing;
  messageApi: MessageInstance;
  mapController: BaseMap | null;
}) => {
  const [ship, setShip] = useState<ShipDetailData | null>(null);
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const [isLoading, setIsLoading] = useState(true);
  const [shipImage, setShipImage] = useState<string>('');
  const [selectedZoneId, setSelectedZoneId] = useState<string | null>(null);
  const getShipDetail = async () => {
    try {
      let zone_entered_alarm_list: ZoneAlarmParse[] = [];
      if (thing.metadata?.zone_entered_alarm_list !== '') {
        zone_entered_alarm_list = JSON.parse(
          thing.metadata?.zone_entered_alarm_list || '[]',
        );
      }
      let zone_approaching_alarm_list: ZoneAlarmParse[] = [];
      if (thing.metadata?.zone_approaching_alarm_list !== '') {
        zone_approaching_alarm_list = JSON.parse(
          thing.metadata?.zone_approaching_alarm_list || '[]',
        );
      }
      const gpsData: GPSParseResult = JSON.parse(thing.metadata?.gps || '{}');
      const resp = await apiViewShip(thing.id || '');

      let shipOwner:
        | MasterModel.UserResponse
        | MasterModel.UserResponse
        | null = null;
      if (resp?.owner_id) {
        if (initialState?.currentUserProfile?.metadata?.user_type === 'admin') {
          shipOwner = await apiQueryUserById(resp.owner_id);
        } else {
          shipOwner = initialState?.currentUserProfile || null;
        }
      }

      try {
        const photoResponse = await apiGetPhoto('ship', resp.id || '');
        const blob = new Blob([photoResponse.data], { type: 'image/jpeg' });
        const url = URL.createObjectURL(blob);
        setShipImage(url);
      } catch (e) {
        setShipImage('https://1.semantic-ui.com/images/wireframe/image.png');
      }
      setShip({
        ship: resp,
        owner: shipOwner || null,
        zone_entered_alarm_list: zone_entered_alarm_list,
        zone_approaching_alarm_list: zone_approaching_alarm_list,
        gps: gpsData,
        trip_id: resp?.metadata?.trip_id,
      });
      setIsLoading(false);
    } catch (error) {
      console.error('Error fetching ship details:', error);
      messageApi.error('Không thể lấy thông tin tàu.');
    }
  };
  useEffect(() => {
    try {
      getShipDetail();
    } catch (error) {
      console.error('Cannot get ShipDetail: ', error);
    }
  }, [thing.id]);
  console.log();
  const handleClickZoneButton = async (zone: ZoneAlarmParse) => {
    if (mapController === null) {
      return;
    }
    mapController.toggleLayer(DATA_LAYER, false);
    if (zone.zone_id === selectedZoneId) {
      mapController.clearFeatures(TEMPORARY_LAYER);
      mapController.toggleLayer(DATA_LAYER, true);
      setSelectedZoneId(null);
      return;
    }
    if (selectedZoneId) {
    }
    try {
      const resp = await apiGetZoneById(zone.zone_id || '');
      if (resp) {
        const text = `Tàu: ${ship?.ship?.name || '-'}\nThời gian ${new Date(
          zone.gps_time! * 1000,
        ).toLocaleTimeString()}\nTốc độ: ${zone.s} km/h\nHướng: ${
          zone.h
        }°\n Lý do: ${zone.message}`;
        mapController.addPoint(
          TEMPORARY_LAYER,
          [zone?.lon || 0, zone?.lat || 0],
          {
            thing: thing,
            description: text,
            type: 'main-point',
          },
        );

        const zone_geom: SgwModel.Geom = JSON.parse(resp.geometry || '{}');
        if (zone_geom.geom_type === 1) {
          const polygon = convertWKTtoLatLngString(zone_geom.geom_poly || '');
          mapController.addPolygon(TEMPORARY_LAYER, polygon, {
            type: getAlarmTypeName(thing.metadata?.state_level || 0),
            zone: resp,
            message: zone.zone_name,
          });
        } else if (zone_geom.geom_type === 2) {
          const polyline = convertWKTLineStringToLatLngArray(
            zone_geom.geom_lines || '',
          );
          mapController.addPolyline(TEMPORARY_LAYER, polyline, {
            type: getAlarmTypeName(thing.metadata?.state_level || 0),
            zone: resp,
            message: zone.zone_name,
          });
        } else {
          const center = convertWKTPointToLatLng(zone_geom.geom_point || '');

          mapController.addCircle(
            TEMPORARY_LAYER,
            center!,
            getCircleRadius(zone_geom.geom_radius || 0),
            {
              type: getAlarmTypeName(thing.metadata?.state_level || 0),
              zone: resp,
              message: zone.zone_name,
            },
          );
        }
        mapController.zoomToFeaturesInLayer(TEMPORARY_LAYER);
        setSelectedZoneId(zone.zone_id || null);
      }
    } catch (error) {
      console.error('Error with get Zone: ', error);
    }
  };
  return isLoading ? (
    <ProSkeleton type="list" statistic={false} list={1} />
  ) : (
    <>
      <ShipBasicInfo ship={ship} shipImage={shipImage} thing={thing} />
      <Tabs
        defaultActiveKey="1"
        centered
        items={[
          {
            key: '1',
            label: (
              <FormattedMessage
                id="map.ship_detail.specifications"
                defaultMessage="Specifications"
              />
            ),
            children: <ShipSpecificationTab ship={ship} />,
          },
          {
            key: '2',
            label: (
              <Tooltip
                title={intl.formatMessage({
                  id: 'map.ship_detail.trip_information_tooltip',
                  defaultMessage: 'Nearest Trip Information',
                })}
              >
                {intl.formatMessage({
                  id: 'map.ship_detail.trip_information',
                  defaultMessage: 'Trip Information',
                })}
              </Tooltip>
            ),
            children: <ShipTripInfoTab ship={ship} />,
          },
          {
            key: '3',
            label: intl.formatMessage({
              id: 'map.filter.ship_warning',
              defaultMessage: 'Warning',
            }),
            disabled:
              ship?.zone_approaching_alarm_list.length === 0 &&
              ship?.zone_entered_alarm_list.length === 0,
            children: (
              <ShipWarningList
                zoneEnteredList={ship?.zone_entered_alarm_list || []}
                zoneApproachingList={ship?.zone_approaching_alarm_list || []}
                selectedZoneId={selectedZoneId}
                onZoneButtonClick={handleClickZoneButton}
              />
            ),
          },
        ]}
      ></Tabs>
    </>
  );
};

export default ShipDetail;

export const ShipDetailMessageAction = () => {
  const intl = useIntl();
  //   const goToThingDetail = (trip_id: string) => {
  //     history.push(
  //       { pathname: `/trips/${trip_id}` },
  //       { thingId: trip_id }, // state
  //     );
  //   };

  return (
    <Space>
      <Button
        // type="link".
        variant="outlined"
        color="cyan"
        icon={<ArrowRightOutlined />}
        size="small"
        iconPosition="end"
        onClick={async () => {
          //   const ship = await viewShip(id);
          //   console.log("Ship Data for Trip Navigation:", shipData);
          //   goToThingDetail(shipData?.metadata?.trip_id);
        }}
      >
        {intl.formatMessage({
          id: 'map.ship_detail.trip_information',
          defaultMessage: 'Trip Information',
        })}
      </Button>
      <Button
        type="primary"
        size="small"
        iconPosition="end"
        icon={<InfoCircleOutlined />}
        onClick={() => {
          // console.log("Navigating to device detail:", id);
          //   const path = `/devices/${id}/vms`; // lấy id + type từ record
          //   history.push({ pathname: path });
        }}
      >
        {intl.formatMessage({
          id: 'map.ship_detail.detail',
          defaultMessage: 'Detail',
        })}
      </Button>
    </Space>
  );
};
