import dayjs from "dayjs";
import { FlatList, Text, TouchableOpacity, View } from "react-native";

type AlarmItem = {
  name: string;
  t: number;
  level: number;
  id: string;
};

type AlarmProp = {
  alarmsData: AlarmItem[];
  onPress?: (alarm: AlarmItem) => void;
};

const AlarmList = ({ alarmsData, onPress }: AlarmProp) => {
  const sortedAlarmsData = [...alarmsData].sort((a, b) => b.level - a.level);
  return (
    <FlatList
      data={sortedAlarmsData}
      renderItem={({ item }) => (
        <TouchableOpacity
          onPress={() => onPress?.(item)}
          className="flex flex-row gap-5 p-3 justify-start items-baseline w-full"
        >
          <View
            className={`flex-none h-3 w-3 rounded-full ${getBackgroundColorByLevel(
              item.level
            )}`}
          ></View>
          <View className="flex">
            <Text className={`grow text-lg ${getTextColorByLevel(item.level)}`}>
              {item.name}
            </Text>
            <Text className="grow text-md text-gray-400">
              {formatTimestamp(item.t)}
            </Text>
          </View>
        </TouchableOpacity>
      )}
      keyExtractor={(item) => item.id}
    />
  );
};

const getBackgroundColorByLevel = (level: number) => {
  switch (level) {
    case 1:
      return "bg-yellow-500";
    case 2:
      return "bg-orange-500";
    case 3:
      return "bg-red-500";
    default:
      return "bg-gray-500";
  }
};

const getTextColorByLevel = (level: number) => {
  switch (level) {
    case 1:
      return "text-yellow-600";
    case 2:
      return "text-orange-600";
    case 3:
      return "text-red-600";
    default:
      return "text-gray-600";
  }
};

const formatTimestamp = (timestamp: number) => {
  return dayjs.unix(timestamp).format("DD/MM/YYYY HH:mm:ss");
};

export default AlarmList;
