import {ActivityIndicator, StyleSheet, View} from 'react-native';
import Container from '../components/Container';
import Header from '../components/Header';
import {Text} from 'react-native';
import useDevices, {Status} from '../../infraestructure/hooks/useDevices';
import Banner from '../components/Banner';
import {useEffect, useState} from 'react';
import remoteConfig from '@react-native-firebase/remote-config';
import RemoteConfigKeys from '../../utils/RemoteConfigKeys';

export interface Line {
  lineNumber: string;
  lineLetter: string;
  letterColor: string;
  backgroundColor: string;
  estimatedArrivalTimeInMinutes: string;
  lineDescription: string;
}

interface TableProps {
  data: Line[];
}

const Table = ({data}: TableProps) => {
  const rows = 7;
  const columns = 3;

  const baseTableData: Line[][] = Array.from({length: rows}, () =>
    new Array(columns).fill({
      lineNumber: '',
      lineLetter: '',
      letterColor: '',
      backgroundColor: '',
      estimatedArrivalTimeInMinutes: '',
    }),
  );

  data.map((item, index) => {
    const row = Math.floor(index / columns);
    const column = index % columns;
    baseTableData[row][column] = item;
  });

  return (
    <View style={tableStyles.table}>
      {baseTableData.map((row, rowIndex) => (
        <View key={rowIndex} style={tableStyles.row}>
          {row.map((cell, cellIndex) => {
            if (cell.lineNumber === '') {
              return <View style={tableStyles.cell} key={cellIndex} />;
            }

            const [first, second] = cell.lineDescription.split('-');

            return (
              <View style={[tableStyles.cell]} key={cellIndex}>
                <View style={tableStyles.lineInformationContainer}>
                  <Text style={tableStyles.lineNumber}>{cell.lineNumber}</Text>
                  <View
                    style={[
                      tableStyles.letterContainer,
                      {backgroundColor: `#${cell.backgroundColor}` || 'grey'},
                    ]}>
                    <Text style={tableStyles.lineLetter}>
                      {cell.lineLetter}
                    </Text>
                  </View>
                </View>
                <View
                  style={[
                    tableStyles.timeContainer,
                    {backgroundColor: `#${cell.backgroundColor}` || 'grey'},
                  ]}>
                  <Text style={tableStyles.time} numberOfLines={1}>
                    {first}
                  </Text>
                  <Text style={tableStyles.time} numberOfLines={1}>
                    {second}
                  </Text>
                  <Text style={tableStyles.time}>
                    {cell.estimatedArrivalTimeInMinutes}
                  </Text>
                </View>
              </View>
            );
          })}
        </View>
      ))}
    </View>
  );
};

const BusStopInfoScreen = () => {
  const {
    state: {status, displayedLines, stopName},
  } = useDevices();
  const [isLoading, setIsLoading] = useState(true);
  const image = remoteConfig().getString(RemoteConfigKeys.HEADER_IMAGE_URL);

  useEffect(() => {
    const init = async () => {
      await remoteConfig().setConfigSettings({
        minimumFetchIntervalMillis: 3600000,
      });

      await remoteConfig().setDefaults({
        BASE_URL: '',
        HEADER_IMAGE_URL: '',
        UPDATE_INTERVAL: 0,
        USER: '',
        PASS: '',
      });

      const isActivated = await remoteConfig().fetchAndActivate();

      if (isActivated) {
        setIsLoading(false);
      }
    };

    init();
  }, []);

  const splitStopName = stopName.split('-');
  let title = splitStopName[0] ? `${splitStopName[0].trim()}` : '';
  const subTitle = splitStopName[1] ? `${splitStopName[1].trim()}` : '';

  if (isLoading) {
    return (
      <Container style={styles.container}>
        <ActivityIndicator />
      </Container>
    );
  }

  return (
    <Container style={styles.container}>
      <Header
        style={styles.headerContainer}
        subTitle={subTitle}
        title={title}
        image={image}
      />
      <Banner
        style={styles.bannerContainer}
        text="Buses que se detienen en esta parada"
      />

      <View style={styles.bodyContainer}>
        {status === Status.LOADING ? (
          <ActivityIndicator />
        ) : (
          <Table data={displayedLines} />
        )}
      </View>
      <View style={styles.footerContainer}>
        {/* {TODO implement footer} */}
      </View>
    </Container>
  );
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
  },
  headerContainer: {
    flex: 1.5,
    backgroundColor: 'orange',
  },
  bannerContainer: {
    flex: 0.5,
    backgroundColor: 'grey',
  },
  bodyContainer: {
    flex: 10,
    justifyContent: 'center',
  },
  busContainer: {
    backgroundColor: 'brown',
    flexDirection: 'column',
  },
  footerContainer: {
    flex: 1,
    backgroundColor: 'grey',
  },
});

const tableStyles = StyleSheet.create({
  table: {
    flex: 1,
    backgroundColor: 'white',
  },
  row: {
    flex: 1,
    flexDirection: 'row',
  },
  cell: {
    flex: 1,
    borderWidth: 1,
    flexDirection: 'column',
    borderColor: 'grey',
  },
  lineInformationContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  timeContainer: {
    alignItems: 'center',
    backgroundColor: 'blue',
  },
  lineNumber: {
    fontSize: 20,
    marginRight: 8,
    fontWeight: 'bold',
    color: 'grey',
  },
  lineLetter: {
    fontSize: 14,
    color: 'white',
    fontWeight: 'bold',
  },
  letterContainer: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 50,
  },
  time: {
    fontSize: 12,
    fontWeight: 'bold',
    color: 'white',
  },
  lineDescription: {
    fontSize: 12,
    fontWeight: 'bold',
    color: 'white',
  },
});

export default BusStopInfoScreen;
