import {
  Alert,
  Image,
  Platform,
  StyleSheet,
  Switch,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import React, { useCallback, useEffect, useState, useRef } from 'react';
import ActionSheet from 'react-native-actions-sheet';
import Matrics from './helpers/Matrics';
import {
  checkBluetoothPermission,
  managePermission,
} from './helpers/bluetoothPermissionHelper';
import { RESULTS } from 'react-native-permissions';

interface Device {
  device_type: string;
  title: string;
}

const DeviceList: Device[] = [
  {
    // image: Images.GoodFlipBcaDevice,
    device_type: 'GoodFlip',
    title: 'GoodFlip device',
  },
];

const colors = {
  gun_powder: '#49454F',
  mountain_meadow: '#12B76A',
  solitude: '#E4E7EC',
  royal_blue_goodflip: '#444CE7',
  alice_blue: '#EEF4FF',
  auro_metal_saurus: '#667085',
  anti_flash_white: '#F2F4F7',
  illuminating_emerald: '#299D6B',
  aero_blue: '#CBF0E0',
  honeydew: '#E6FAF1',
  sea_green: '#2A805A',
  dark_jungle_green: '#101828',
  cosmic_cobalt: '#2D3282',
  brunswick_green: '#1D4D38',
};

const BcaDeviceListSheet = ({ sheetId, payload }: {
  sheetId: string;
  payload: {
    onPressConnectSmartScaleBtn: (deviceType: Device) => void;
  };
}) => {
  const { onPressConnectSmartScaleBtn } = payload;

  const [devices, setDevices] = useState<Device[]>([]);
  const [closeOnTouchBackdrop, setCloseOnTouchBackdrop] = useState(false);
  const [bluetoothIsEnable, setBluetoothIsEnable] = useState(false);
  const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
  const actionSheetRef = useRef<any>(null);

  useEffect(() => {
    checkBleEnable();
    //   handlePageViewEvent(Constants.SCREEN_NAME.BCABluetoothToggle);
  }, []);

  useEffect(() => {
    checkDeviceIsAvailable();
  }, []);

  const onChange = (position: number) => {
    if (position == 0) {
      setCloseOnTouchBackdrop(true);
    }
  };

  const checkDeviceIsAvailable = () => {
    const tempDevideList: Device[] = [];
    tempDevideList.push(DeviceList[0]);
    setDevices(tempDevideList);
  };

  const checkBleEnable = async () => {
    const permission = await checkBluetoothPermission();
    if (permission.status !== RESULTS.GRANTED) {
      setBluetoothIsEnable(false);
    }
  };

  const onPressSwitch = async (value) => {
    if (value) {
      const permission = await checkBluetoothPermission();
      await managePermission(permission, value, () => {
        setBluetoothIsEnable(true);
      });
    } else {
      setBluetoothIsEnable(false);
    }
  };

  const renderHeader = useCallback(() => {
    return (
      <View style={styles.headerContainer}>
        <Text style={styles.syncSmartScaleTxt}>Sync Smart Scale</Text>
        <TouchableOpacity
          activeOpacity={0.8}
          onPress={() => actionSheetRef.current?.hide()}
        >
          {/* Remove or properly implement the icon component */}
        </TouchableOpacity>
      </View>
    );
  }, []);

  const renderRightContainer = useCallback(() => {
    return (
      <View
        style={[
          styles.rightContainer,
          {
            paddingLeft: Matrics.s((devices ?? []).length ? 15 : 0),
          },
        ]}
      >
        {renderStep2Container()}
      </View>
    );
  }, [selectedDevice, bluetoothIsEnable, devices]);

  const renderStep2Container = useCallback(() => {
    return (
      <View>
        <Text style={styles.inOrderToConnectTxt}>
          In order to connect with the GoodFlip smart scale, you need to turn on
          the Bluetooth on your device
        </Text>

        <View style={styles.switchButtonContainer}>
          <Text style={styles.turnOnBluetoothTxt}>Turn on Bluetooth</Text>
          <Switch
            trackColor={{
              false: '#F2F4F7',
              true: '#299D6B',
            }}
            thumbColor={'white'}
            ios_backgroundColor={'#F2F4F7'}
            onValueChange={onPressSwitch}
            value={bluetoothIsEnable}
          />
        </View>
      </View>
    );
  }, [bluetoothIsEnable, devices]);

  const renderBottomBtn = useCallback(() => {
    return (
      <TouchableOpacity
        onPress={() => {
          if (selectedDevice) {
            onPressConnectSmartScaleBtn(selectedDevice);
          }
        }}
        activeOpacity={0.8}
        disabled={!bluetoothIsEnable || !selectedDevice}
        style={[
          styles.connectWithSmartSmartScaleButtonContainer,
          {
            backgroundColor:
              !bluetoothIsEnable || !selectedDevice
                ? colors.aero_blue
                : colors.illuminating_emerald,
            shadowColor:
              !bluetoothIsEnable || !selectedDevice
                ? colors.honeydew
                : colors.sea_green,
          },
        ]}
      >
        <Text style={styles.connectWithSmartScaleTxt}>
          Connect With Smart Scale
        </Text>
      </TouchableOpacity>
    );
  }, [selectedDevice, bluetoothIsEnable]);

  return (
    <ActionSheet
      id={sheetId}
      ref={actionSheetRef}
      containerStyle={styles.sheet}
      onChange={onChange}
      isModal={true}
      snapPoints={[100]}
      initialSnapIndex={0}
      useBottomSafeAreaPadding={
        Platform.OS === 'ios' ? !closeOnTouchBackdrop : true
      }
      gestureEnabled={false}
      drawUnderStatusBar={false}
      defaultOverlayOpacity={0.3}
      closeOnTouchBackdrop={closeOnTouchBackdrop}
    >
      <View style={styles.smallHeight}>
        <View style={styles.mainContainer}>
          {renderHeader()}
          <View style={{ flexDirection: 'row' }}>{renderRightContainer()}</View>
        </View>
        {renderBottomBtn()}
      </View>
    </ActionSheet>
  );
};

export default BcaDeviceListSheet;

const styles = StyleSheet.create({
  sheet: {
    borderTopRightRadius: 20,
    borderTopLeftRadius: 20,
    paddingBottom: Matrics.vs(Platform.OS === 'android' ? 20 : 5),
  },
  smallHeight: {
    paddingHorizontal: Matrics.s(15),
    paddingVertical: Matrics.s(15),
  },
  mainContainer: {
    marginBottom: Matrics.vs(40),
  },
  headerContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: Matrics.vs(20),
  },
  syncSmartScaleTxt: {
    // fontFamily: Fonts.ROBOTO_SEMI_BOLD,
    fontSize: Matrics.mvs(18),
    color: '#101828',
  },
  mainStepContainer: {
    backgroundColor: 'E4E7EC',
    borderRadius: Matrics.mvs(100),
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: Matrics.vs(15),
    overflow: 'hidden',
  },
  gradientContainer: {
    height: Matrics.vs(30),
    alignItems: 'center',
  },
  stepContainer: {
    height: Matrics.mvs(14),
    width: Matrics.mvs(14),
    backgroundColor: 'white',
    borderRadius: Matrics.mvs(100),
    marginHorizontal: Matrics.s(1),
  },
  rightContainer: {
    flex: 1,
    paddingLeft: Matrics.s(15),
  },
  step1Container: {
    gap: 15,
    paddingBottom: Matrics.vs(30),
  },
  stepHeaderTxt: {
    // fontFamily: Fonts.ROBOTO_REGULAR,
    fontSize: Matrics.mvs(12),
    color: '#101828',
  },
  selectYourSmartScaleTxt: {
    // fontFamily: Fonts.ROBOTO_SEMI_BOLD,
    fontSize: Matrics.mvs(16),
    color: '#101828',
  },
  deviceItemContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    borderWidth: 1,
    borderRadius: Matrics.mvs(8),
    paddingVertical: Matrics.vs(10),
    paddingHorizontal: Matrics.s(13),
  },
  deviceItemDetailsContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 15,
  },
  deviceImageContainer: {
    height: Matrics.mvs(50),
    width: Matrics.mvs(50),
    resizeMode: 'contain',
  },
  deviceNameTxt: {
    // fontFamily: Fonts.ROBOTO_BOLD,
    fontSize: Matrics.mvs(16),
    color: '#101828',
  },
  switchButtonContainer: {
    borderWidth: 1,
    borderRadius: Matrics.mvs(16),
    paddingVertical: Matrics.vs(10),
    paddingHorizontal: Matrics.s(13),
    borderColor: '#E4E7EC',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  turnOnBluetoothTxt: {
    // fontFamily: Fonts.ROBOTO_SEMI_BOLD,
    fontSize: Matrics.mvs(16),
    color: '#2D3282',
  },
  connectWithSmartSmartScaleButtonContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',

    borderRadius: Matrics.mvs(8),
    paddingVertical: Matrics.vs(15),
    shadowOffset: { height: 12, width: 0 },
    shadowOpacity: 1,
    shadowRadius: 1,
    gap: 15,
    elevation: 8,
  },
  connectWithSmartScaleTxt: {
    fontSize: Matrics.mvs(16),
    // fontFamily: Fonts.ROBOTO_BOLD,
    color: 'white',
  },
  inOrderToConnectTxt: {
    // fontFamily: Fonts.ROBOTO_REGULAR,
    fontSize: Matrics.mvs(14),
    color: '#667085',
    marginBottom: Matrics.vs(25),
  },
});
