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

import { User } from "@/store/models/User.model";
import { InfoRow } from "./InfoRow";
import { useAppSelector } from "@/store/hooks";
import { selectIsMobile } from "@/store/screen/screenSizeSlice";
import { useGetUserLogsQuery } from "@/store/api/usersApi";
import { formatDate, formatTimeWithSeconds } from "@/utils/dateUtils";
import { RiskIndicator } from "@/components/ui/RiskIndicator";
import { SizeEnum } from "@/constants/sizeEnum";
import { RiskEnum, RiskLabels } from "@/constants/riskEnum";
import { SecurityTypeLabels } from "@/constants/securityTypeEnum";

interface PersonalMetricsProps {
  user: User;
}

export const PersonalMetrics = ({ user }: PersonalMetricsProps) => {
  const isMobile = useAppSelector(selectIsMobile);
  const {
    data: logsData,
    isLoading: logsLoading,
    isError: logsError,
  } = useGetUserLogsQuery(
    { page: 1, limit: 1, search: user.email },
    { skip: !user?.email }
  );

  const lastLogItem = logsData?.items?.[0];
  const lastLoginAt = lastLogItem?.lastLoginAt;
  const activity = lastLogItem?.activity;

  const lastLoginDisplay = logsLoading
    ? "Loading..."
    : logsError
    ? "-"
    : lastLoginAt
    ? `${formatDate(lastLoginAt)} ${formatTimeWithSeconds(lastLoginAt)}`
    : "-";

  const lastPasswordChangeDisplay = logsLoading
    ? "Loading..."
    : logsError
    ? "-"
    : activity === "Password reset" && lastLoginAt
    ? `${formatDate(lastLoginAt)} ${formatTimeWithSeconds(lastLoginAt)}`
    : "-";

  return (
    <View className="bg-lightGray rounded-md">
      <View className={`gap-4 ${isMobile ? "flex-col" : "flex-row"}`}>
        <View className="flex-1 mt-4">
          <InfoRow label="Last Log-in" value={lastLoginDisplay} />
          <InfoRow
            label="Last Password Change"
            value={lastPasswordChangeDisplay}
          />
        </View>

        <View className="flex-1 mt-4">
          {user.riskStatus && (
            <InfoRow
              label="Risk Status"
              value={
                <View className="flex-row items-baseline gap-4">
                  <Text>
                    {user.riskStatus === RiskEnum.NO_RISK
                      ? RiskLabels[user.riskStatus]
                      : RiskLabels[user.riskStatus].split(" ")[0]}
                  </Text>
                  <RiskIndicator risk={user.riskStatus} size={SizeEnum.Small} />
                </View>
              }
            />
          )}
          <InfoRow
            label="Security Type"
            value={SecurityTypeLabels[user.securityType]}
          />
        </View>
      </View>
    </View>
  );
};
