import {
  Badge,
  Divider,
  HStack,
  Pressable,
  View,
  Text,
  useColorModeValue,
  Heading,
} from 'native-base';
import React, { Dispatch, SetStateAction, useState } from 'react';
import { HEAT_PUMP_STATE_MODES } from '../../constants';
import { Card, DotIcon, ErrorIcon, SuccessIcon, UnknownIcon, WarningIcon } from '../ui';
import { getErrors } from '../../utilities/helpers';
import { HeatPumpState } from '../../models/heatpump';
import ErrorsModal from './ErrorsModal';
import { FontAwesome5 } from '@expo/vector-icons';
import GeneralInfoRow from './GeneralInfoRow';
import { COLORS } from '../../theme';

type ShowDetailButtonProps = {
  showAdvancedInfo: boolean;
  setShowAdvancedDetails: Dispatch<SetStateAction<boolean>>;
};

const ShowDetailButton = ({ showAdvancedInfo, setShowAdvancedDetails }: ShowDetailButtonProps) => {
  const chevronColor = useColorModeValue(COLORS.gray[600], COLORS.white);
  const bgColor = useColorModeValue(COLORS.gray[100], COLORS.gray[600]);

  return (
    <Pressable className="my-1 ml-1.5" onPress={() => setShowAdvancedDetails(prev => !prev)}>
      <View
        bgColor={bgColor}
        className="flex flex-row items-center gap-x-1.5 self-start rounded-full p-[1px] pr-2"
      >
        <Text className="text-xs">{showAdvancedInfo ? 'Hide' : 'Show'} advanced info</Text>
        <FontAwesome5
          color={chevronColor}
          name={showAdvancedInfo ? 'chevron-up' : 'chevron-down'}
        />
      </View>
    </Pressable>
  );
};

type StatusProps = {
  isDown?: boolean;
  hasError: boolean;
  unknown: boolean;
};

const Status = ({ isDown, hasError, unknown }: StatusProps) => {
  const iconProps = {
    size: 17,
  };

  const bgColor = useColorModeValue(COLORS.gray[100], COLORS.gray[600]);

  let icon = <UnknownIcon {...iconProps} />;
  let text: string | undefined = 'Server is not available';

  if (!unknown && !hasError && !isDown) {
    icon = <SuccessIcon {...iconProps} />;
    text = undefined;
  }
  if (!unknown && hasError) {
    icon = <WarningIcon {...iconProps} />;
    text = undefined;
  }
  if (!unknown && isDown) {
    icon = <ErrorIcon {...iconProps} />;
    text = !hasError ? 'Heat pump connection is down' : undefined;
  }

  return (
    <>
      {icon}
      {text && (
        <Text bg={bgColor} className="ml-2 rounded-full p-[1px] px-1.5 text-xs">
          {text}
        </Text>
      )}
    </>
  );
};

type GeneralInfoProps = {
  state?: HeatPumpState;
};

const GeneralInfo = ({ state }: GeneralInfoProps) => {
  const [showAdvancedInfo, setShowAdvancedDetails] = useState(false);

  const errorTextColor = useColorModeValue(COLORS.white, COLORS.gray[900]);
  const downColor = useColorModeValue(COLORS.red[700], COLORS.red[400]);
  const errors = getErrors(state);
  const hasError = !!errors.length;

  const [showErrorsModal, setShowErrorsModal] = useState(false);
  const allowAdvancedInfo =
    state?.outdoor_coil_temperature !== undefined ||
    state?.compressor_frequency !== undefined ||
    state?.exhaust_gas_temperature !== undefined ||
    state?.machine_current_value !== undefined;

  return (
    <>
      <Card>
        <GeneralInfoRow
          label="Status"
          value={
            <HStack className="mb-[1px] items-center">
              <Status
                isDown={!state?.established_connection}
                hasError={hasError}
                unknown={!state}
              />
              {hasError && (
                <Pressable onPress={() => setShowErrorsModal(true)}>
                  <Badge className="ml-2 rounded-xl" bgColor={downColor}>
                    <Text className="text-xs font-medium" color={errorTextColor}>
                      {`${errors.length} failure${errors.length > 1 ? 's' : ''}`}
                    </Text>
                  </Badge>
                </Pressable>
              )}
            </HStack>
          }
        />
        {!!state && (
          <GeneralInfoRow label="Current mode" value={HEAT_PUMP_STATE_MODES[state.mode ?? 0]} />
        )}
        <Divider className="my-1 mt-2" />
        {state?.outdoor_ambient_temperature !== undefined && (
          <GeneralInfoRow
            label="Outdoor temperature"
            value={`${state.outdoor_ambient_temperature}°C`}
          />
        )}

        {state?.water_tank_temperature !== undefined && (
          <GeneralInfoRow
            label="Water tank temperature"
            value={`${state.water_tank_temperature}°C`}
          />
        )}
        {state?.machine_current_value !== undefined && (
          <GeneralInfoRow
            label="Electric power consumption"
            value={`${((state.machine_current_value * 230) / 1000).toFixed(2)} kWh`}
          />
        )}
        {allowAdvancedInfo && (
          <ShowDetailButton
            showAdvancedInfo={showAdvancedInfo}
            setShowAdvancedDetails={setShowAdvancedDetails}
          />
        )}
        {showAdvancedInfo && allowAdvancedInfo && (
          <>
            {!!state?.flags.status_1?.length && (
              <HStack className="mt-0.5 items-center gap-x-2">
                <Heading size="sm">Defrosting:</Heading>
                <DotIcon
                  size={14}
                  active={(state.flags.status_1?.includes(1) && state.mode !== 0) ?? false}
                />
              </HStack>
            )}

            {state?.compressor_frequency !== undefined && (
              <GeneralInfoRow
                label="Compressor frequency"
                value={`${state.compressor_frequency} Hz`}
              />
            )}
            {state?.return_air_temperature !== undefined && (
              <GeneralInfoRow
                label="Return air temperature"
                value={`${state.return_air_temperature}°C`}
              />
            )}
            {state?.exhaust_gas_temperature !== undefined && (
              <GeneralInfoRow
                label="Exhaust gas temperature"
                value={`${state.exhaust_gas_temperature}°C`}
              />
            )}
            {state?.water_temperature !== undefined && (
              <GeneralInfoRow
                label="Return water temperature"
                value={`${state.water_temperature}°C`}
              />
            )}
            {state?.outdoor_coil_temperature !== undefined && (
              <GeneralInfoRow
                label="Outdoor coil temperature"
                value={`${state.outdoor_coil_temperature}°C`}
              />
            )}
          </>
        )}
      </Card>
      <ErrorsModal
        isOpen={showErrorsModal}
        errors={errors}
        onClose={() => setShowErrorsModal(false)}
      />
    </>
  );
};

export default GeneralInfo;
