import React, { useCallback, useEffect, useState, useRef } from "react";

/*
  ____          _              ____  _        _            
 |  _ \ ___  __| |_   ___  __ / ___|| |_ __ _| |_ ___  ___ 
 | |_) / _ \/ _` | | | \ \/ / \___ \| __/ _` | __/ _ \/ __|
 |  _ <  __/ (_| | |_| |>  <   ___) | || (_| | ||  __/\__ \
 |_| \_\___|\__,_|\__,_/_/\_\ |____/ \__\__,_|\__\___||___/
                                                           
*/
import { useDispatch, useSelector } from "react-redux";
import { updateBrowserSupported, updateUsbDeviceList,updateCurrentBackend } from "../states/global";
import { AppState } from "../states/global";

/*
     _          _   ____  
    / \   _ __ | |_|  _ \ 
   / _ \ | '_ \| __| | | |
  / ___ \| | | | |_| |_| |
 /_/   \_\_| |_|\__|____/ 
                           
*/
import { Layout, Space, Typography, Col, Row } from "antd";
import { notification } from "antd";

/*
 __        __   _       _    ____  ____  
 \ \      / /__| |__   / \  |  _ \| __ ) 
  \ \ /\ / / _ \ '_ \ / _ \ | | | |  _ \ 
   \ V  V /  __/ |_) / ___ \| |_| | |_) |
    \_/\_/ \___|_.__/_/   \_\____/|____/ 
                                         
*/
import { AdbDaemonDevice } from "@yume-chan/adb";
import { AdbDaemonWebUsbDeviceManager } from "@yume-chan/adb-daemon-webusb";

/*
   ____                                             _       
  / ___|___  _ __ ___  _ __   ___  _ __   ___ _ __ | |_ ___ 
 | |   / _ \| '_ ` _ \| '_ \ / _ \| '_ \ / _ \ '_ \| __/ __|
 | |__| (_) | | | | | | |_) | (_) | | | |  __/ | | | |_\__ \
  \____\___/|_| |_| |_| .__/ \___/|_| |_|\___|_| |_|\__|___/
                      |_|                                   
*/
import AddDevice from "../components/deviceOperations/AddDevice";
import DeviceConnection from "../components/deviceOperations/DeviceConnection";
import SelectDevice from "../components/deviceOperations/SelectDevice";
import DeviceInfo from "../components/deviceOperations/DeviceInfo";
import Terminal from "../components/terminal/Terminal";
import TerminalHide from "../components/terminal/TerminalHide";
import ExitTerminal from "../components/terminal/ExitTerminal";
import ResetTerminal from "../components/terminal/ResetTerminal";
import RunCommandShell from "../components/terminal/RunCommandShell";
import FileManager from "../components/fileManager/FileManager";
import FileManagerReadFile from "../components/fileManager/ReadFile";
import Reboot from "../components/deviceOperations/Reboot";
import FileManagerUpload from "../components/fileManager/Upload";
import HeaderLeft from "../components/header/headerLeft";
import HeaderRight from "../components/header/headerRight";
import BlocklyHome from "../components/blockly/BlocklyIndex";
import ContentRightHeader from "../components/contentRightHeader";
import PrintData from "../components/fileManager/printData";
import UpdateLog from "../components/footer/updateLog";
import AdbHeader from "../components/deviceOperations/AdbHeader";

const { Header, Content, Footer } = Layout;
const { Text } = Typography;

// Define the content style of the page
const contentStyle: React.CSSProperties = {
  textAlign: "center",
  height: "calc(100vh - 105px)",
};
const headerStyle: React.CSSProperties = {
  backgroundColor: "#2c4fcd",
  padding: "0",
  display: "flex",
  color: "#fff",
  justifyContent: "space-between",
  alignItems: "center",
};
const footerStyle: React.CSSProperties = {
  backgroundColor: "#2c4fcd",
  padding: "10px",
  display: "flex",
  color: "#fff",
  justifyContent: "space-between",
  alignItems: "center",
};

const footerRightStyle: React.CSSProperties = {
  display: "flex",
  color: "#fff",
  justifyContent: "end",
  alignItems: "center",
  fontWeight: "bold",
  fontSize: "16px",
};
// Define the tab item interface
interface tabItem {
  label: React.ReactNode;
  key: string;
  children: React.ReactNode;
  style?: React.CSSProperties;
}

const Home: React.FC = () => {
  const year = new Date().getFullYear();
  const [generatedCode, setGeneratedCode] = useState('');
  // Define the notification api
  const [api, contextHolder] = notification.useNotification();

  // Define the mounted state
  // this state is used to check if the component is mounted or not
  const [mounted, setMounted] = useState(false);

  // Load the global states
  const currentBackend = useSelector((state: AppState) => state.currentBackend);
  const usbDeviceList = useSelector((state: AppState) => state.usbDeviceList);
  const browserSupported = useSelector(
    (state: AppState) => state.browserSupported,
  );
  // Define the dispatch function to be used to update the global states
  const dispatch = useDispatch();

  // handleUsbDeviceListUpdate() is used here when the this page is first mounted
  const handleUsbDeviceListUpdate = useCallback(async () => {
    // Add the current device to usbDeviceList
    const devices: AdbDaemonDevice[] =
      await AdbDaemonWebUsbDeviceManager.BROWSER!.getDevices();
    dispatch(updateUsbDeviceList(devices));
    if(devices.length > 0){
      dispatch(updateCurrentBackend(devices[0]));
    }
    console.log("devices", devices);
  }, [usbDeviceList]);

  useEffect(() => {
    console.log("Home component mounted/changed");

    if (!mounted) {
      // console.log("Home component first mounted");

      // Checks if the browser supports WebUSB, only at the first mount
      if (!AdbDaemonWebUsbDeviceManager.BROWSER) {
        // browser not supported
        dispatch(updateBrowserSupported(false));
        console.log("browser not supported");
        return;
      }

      handleUsbDeviceListUpdate();
      dispatch(updateBrowserSupported(true));
      setMounted(true);
    }

    return () => {
      console.log("Home component unmounted/changed");
    };
  }, [mounted]);

  // Define the bottom left area ref
  // We need this to get the height and width of the bottom left area
  // for the Terminal component
  const handleBottomLeftAreaRef = useRef<HTMLDivElement>(null);
  const [bottomLeftAreaHeight, setBottomLeftAreaHeight] = useState<number>(0);
  const [bottomLeftAreaWidth, setBottomLeftAreaWidth] = useState<number>(0);
  const [contentRightTopShow, setContentRightTopShow] = useState<number>(1)

  useEffect(() => {
    const handleBottomLeftAreaResize = () => {
      if (handleBottomLeftAreaRef.current) {
        const { height, width } =
          handleBottomLeftAreaRef.current.getBoundingClientRect();

        console.log("Bottom Left Area Height: ", height, "\tWidth: ", width);
        setBottomLeftAreaHeight(height);
        setBottomLeftAreaWidth(width);
      }
    };

    handleBottomLeftAreaResize(); // Initialize the height value on page load

    // Attach the resize event listener
    window.addEventListener("resize", handleBottomLeftAreaResize);

    return () => {
      // Cleanup: Remove the resize event listener when the component unmounts
      window.removeEventListener("resize", handleBottomLeftAreaResize);
    };
  }, [bottomLeftAreaHeight, bottomLeftAreaWidth]);
  const getChildValue = (value: number) => {
    setContentRightTopShow(value)
  }

  const [editableValue, setEditableValue] = useState(false);
  const editable = (value: boolean) => {
    setEditableValue(value)
  }
  return (
    <>
      {/* {contextHolder} */}
      <Space
        direction="vertical"
        style={{
          width: "100%",
        }}
      >
        <Layout
          style={{
            overflow: "hidden",
          }}
        >
          <Header style={headerStyle}>
            <HeaderLeft />
            <HeaderRight />
          </Header>
          <Content style={contentStyle}>
            <Row gutter={20} style={{ height: "100%" }}>
              <Col span={17}>
                <BlocklyHome />
              </Col>
              <Col span={7} style={{width: "100%",paddingLeft:0}}>
                <Row style={{ height: "calc(100% - 175px)" }}
                  gutter={20}>
                  <Col span={24}>
                    <Row>
                      <Col span={24}>
                        <ContentRightHeader hangdEditable={editable} handleChildValue={getChildValue} />
                      </Col>
                    </Row>
                    <Row style={{ height: "calc(100% - 60px)" }}>
                      {contentRightTopShow === 0 ? <Col span={24} style={{ height: "100%" }}><PrintData /></Col> : ""}
                      {contentRightTopShow === 1 ? <Col span={24} style={{ height: "100%" }}> 
                        <FileManagerReadFile setEditable={editableValue} />
                      </Col> : ""}
                      {contentRightTopShow === 2 ? <Col span={24} style={{ height: "100%" }} ref={handleBottomLeftAreaRef}>
                        <Terminal
                          height={"100%"}
                          width={bottomLeftAreaWidth - 70}
                          needCardWrapper={true}
                        />
                      </Col> : ""}
                      <Col style={{ display: "none" }} span={24} ref={handleBottomLeftAreaRef}>
                        <TerminalHide
                          height={280}
                          width={bottomLeftAreaWidth - 70}
                          needCardWrapper={true}
                          style={{
                            width: bottomLeftAreaWidth - 20,
                          }}
                        />
                      </Col>
                    </Row>
                  </Col>

                </Row>
                <Row
                  style={{
                    marginTop: 20,
                    backgroundColor:"#f8f8f8",paddingRight:10
                  }}
                  gutter={20}>
                  <Col span={24}> 
                    <AdbHeader  />
                  </Col>
                  <Col className="run-reboot" span={24}>
                    {/* <SelectDevice /> */}
                    <DeviceConnection style={{ width: "59%", }} />
                    <AddDevice style={{ width: "39%" }} />
                  </Col>
                  <Col className="run-reboot" span={24} style={{ marginTop: 20 }}>
                    <RunCommandShell />
                    <Reboot />
                  </Col>
                </Row>
              </Col>
            </Row>

          </Content>
          <Footer style={footerStyle} >
            <Col span={8}>
              可可乐博（深圳）科技有线公司 © {year} 版权所有
            </Col>
            <Col span={16} style={footerRightStyle}>
              <UpdateLog />
              <span>CocoBlockly Pi</span>
            </Col>
          </Footer>
        </Layout>
      </Space>
    </>
  );
};

export default Home;
