import DeviceAlarmList from '@/components/shared/DeviceAlarmList';
import TooltipIconFontButton from '@/components/shared/TooltipIconFontButton';
import { ROUTER_HOME } from '@/constants/routes';
import { apiQueryNodeConfigMessage } from '@/services/master/MessageController';
import { apiGetThingDetail } from '@/services/master/ThingController';
import {
  EditOutlined,
  EllipsisOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { history, useIntl, useModel, useParams } from '@umijs/max';
import { Divider, Flex, Grid } from 'antd';
import { useEffect, useState } from 'react';
import BinarySensors from './components/BinarySensors';
import ChartComponent from './components/Chart';
import ThingTitle from './components/ThingTitle';

const DetailDevicePage = () => {
  const { thingId } = useParams();
  const [thing, setThing] = useState<MasterModel.Thing | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  const { useBreakpoint } = Grid;
  const screens = useBreakpoint();
  const intl = useIntl();
  const [nodeConfigs, setNodeConfigs] = useState<MasterModel.NodeConfig[]>([]);
  const getThingDetail = async () => {
    setIsLoading(true);
    try {
      const thing = await apiGetThingDetail(thingId || '');
      setThing(thing);
    } catch (error) {
      console.error('Error when get Thing: ', error);
    } finally {
      setIsLoading(false);
    }
  };
  const getDeviceConfig = async () => {
    try {
      const resp = await apiQueryNodeConfigMessage(
        thing?.metadata?.data_channel_id || '',
        initialState?.currentUserProfile?.metadata?.frontend_thing_key || '',
        {
          offset: 0,
          limit: 1,
          subtopic: `config.${thing?.metadata?.type}.node`,
        },
      );
      if (resp.messages && resp.messages.length > 0) {
        console.log('Node Configs: ', resp.messages[0].string_value_parsed);

        setNodeConfigs(resp.messages[0].string_value_parsed ?? []);
      }
    } catch (error) {}
  };
  useEffect(() => {
    if (thingId) {
      getThingDetail();
    }
  }, [thingId]);
  useEffect(() => {
    if (thing) {
      getDeviceConfig();
    }
  }, [thing]);

  return (
    <PageContainer
      title={isLoading ? 'Loading...' : <ThingTitle thing={thing} />}
      header={{
        onBack: () => history.push(ROUTER_HOME),
        breadcrumb: undefined,
      }}
      extra={[
        <TooltipIconFontButton
          key="logs"
          tooltip="Nhật ký"
          iconFontName="icon-system-diary"
          shape="circle"
          size="middle"
          onClick={() => {}}
        />,
        <TooltipIconFontButton
          key="notifications"
          tooltip="Thông báo"
          iconFontName="icon-bell"
          shape="circle"
          size="middle"
          onClick={() => {}}
        />,
        <TooltipIconFontButton
          key="settings"
          tooltip="Cài đặt"
          iconFontName="icon-setting-device"
          shape="circle"
          size="middle"
          onClick={() => {}}
        />,
      ]}
    >
      <ProCard split={screens.md ? 'vertical' : 'horizontal'}>
        <ProCard
          bodyStyle={{
            paddingInline: 12,
            paddingBlock: 8,
          }}
          title={intl.formatMessage({
            id: 'master.thing.detail.alarmList.title',
          })}
          colSpan={{ xs: 24, sm: 24, md: 24, lg: 6, xl: 6 }}
          bordered
        >
          <DeviceAlarmList key="thing-alarms-key" thingId={thingId || ''} />
        </ProCard>
        <ProCard colSpan={{ xs: 24, sm: 24, md: 24, lg: 18, xl: 18 }}>
          <Flex wrap gap="small">
            <Divider orientation="left">Cảm biến</Divider>
            <BinarySensors nodeConfigs={nodeConfigs} />
            <Divider orientation="left">Trạng thái</Divider>
            <ProCard
              title="Mẫu 1"
              bordered
              style={{ maxWidth: 600 }}
              actions={[
                <SettingOutlined key="setting" />,
                <EditOutlined key="edit" />,
                <EllipsisOutlined key="ellipsis" />,
              ]}
            >
              <ChartComponent />
            </ProCard>
          </Flex>
        </ProCard>
      </ProCard>
    </PageContainer>
  );
};

export default DetailDevicePage;
