import { apiQueryCamera } from '@/services/master/MessageController';
import { apiGetThingDetail } from '@/services/master/ThingController';
import { wsClient } from '@/utils/wsClient';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { history, useModel, useParams } from '@umijs/max';
import { Button, Col, Row, Space, Spin } from 'antd';
import { useEffect, useState } from 'react';
import CameraFormModal from './components/CameraFormModal';
import CameraTable from './components/CameraTable';
import ConfigCameraV5 from './components/ConfigCameraV5';
import ConfigCameraV6 from './components/ConfigCameraV6';

const CameraConfigPage = () => {
  const { thingId } = useParams<{ thingId: string }>();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [loading, setLoading] = useState(true);
  const [cameraLoading, setCameraLoading] = useState(false);
  const [thing, setThing] = useState<MasterModel.Thing | null>(null);
  const [cameras, setCameras] = useState<MasterModel.Camera[] | null>([]);
  const [cameraConfig, setCameraConfig] = useState<MasterModel.CameraV6 | null>(
    null,
  );
  const { initialState } = useModel('@@initialState');

  useEffect(() => {
    wsClient.connect('/mqtt', false);
    const unsubscribe = wsClient.subscribe((data: any) => {
      console.log('Received WS data:', data);
    });

    return () => {
      unsubscribe();
    };
  }, []);

  // Fetch thing info on mount
  useEffect(() => {
    const fetchThingInfo = async () => {
      if (!thingId) return;

      try {
        setLoading(true);
        const thingData = await apiGetThingDetail(thingId);
        setThing(thingData);
      } catch (error) {
        console.error('Failed to fetch thing info:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchThingInfo();
  }, [thingId]);

  // Fetch camera config when thing data is available
  const fetchCameraConfig = async () => {
    if (
      !thing ||
      !initialState?.currentUserProfile?.metadata?.frontend_thing_key
    ) {
      return;
    }

    try {
      setCameraLoading(true);
      const resp = await apiQueryCamera(
        thing.metadata?.data_channel_id || '',
        initialState.currentUserProfile.metadata.frontend_thing_key,
        {
          offset: 0,
          limit: 1,
          subtopic: `config.${thing.metadata?.type}.cameras`,
        },
      );

      if (resp.messages!.length > 0) {
        setCameras(
          resp.messages![0].string_value_parsed?.cams as MasterModel.Camera[],
        );
        setCameraConfig(
          resp.messages![0].string_value_parsed as MasterModel.CameraV6,
        );
      }
    } catch (error) {
      console.error('Failed to fetch camera config:', error);
    } finally {
      setCameraLoading(false);
    }
  };

  useEffect(() => {
    fetchCameraConfig();
  }, [thing, initialState]);

  const handleOpenModal = () => {
    setIsModalVisible(true);
  };

  const handleCloseModal = () => {
    setIsModalVisible(false);
  };

  const handleSubmitCamera = (values: any) => {
    console.log('Camera values:', values);
    // TODO: Call API to create camera
    handleCloseModal();
  };

  // Helper function to determine which camera component to render
  const renderCameraRecordingComponent = () => {
    const thingType = thing?.metadata?.type;

    if (thingType === 'gmsv5') {
      return <ConfigCameraV5 thing={thing} />;
    }

    if (thingType === 'spole' || thingType === 'gmsv6') {
      return <ConfigCameraV6 thing={thing} cameraConfig={cameraConfig} />;
    }

    return <ConfigCameraV6 thing={thing} cameraConfig={cameraConfig} />;
  };

  return (
    <Spin spinning={loading}>
      <PageContainer
        header={{
          title: (
            <Space>
              <Button
                type="text"
                icon={<ArrowLeftOutlined />}
                onClick={() => history.push('/manager/devices')}
              />
              <span>{thing?.name || 'Loading...'}</span>
            </Space>
          ),
        }}
      >
        <Row gutter={24}>
          {/* Left Column - Camera Table */}
          <Col xs={24} md={10} lg={8}>
            <CameraTable
              cameraData={cameras}
              onCreateCamera={handleOpenModal}
              onReload={fetchCameraConfig}
              loading={cameraLoading}
            />
          </Col>

          {/* Right Column - Camera Recording Configuration */}
          <Col xs={24} md={14} lg={16}>
            {renderCameraRecordingComponent()}
          </Col>
        </Row>

        {/* Create Camera Modal */}
        <CameraFormModal
          open={isModalVisible}
          onCancel={handleCloseModal}
          onSubmit={handleSubmitCamera}
        />
      </PageContainer>
    </Spin>
  );
};

export default CameraConfigPage;
