import { GET_JOB_BY_PK } from "@/graphql/jobs.queries";
import { useQuery } from "@apollo/client";
import { AntDesign } from "@expo/vector-icons";
import { useGlobalSearchParams } from "expo-router";
import { DateTime } from "luxon";
import React from "react";
import { useTranslation } from "react-i18next";
import { FlatList, RefreshControl, View } from "react-native";
import { ActivityIndicator, Card, Text } from "react-native-paper";
import ErrorDisplay from "../error/error-display";

export default function JobNotes() {
  const { jobId } = useGlobalSearchParams();

  const { loading, error, data, refetch } = useQuery(GET_JOB_BY_PK, {
    variables: {
      id: jobId,
    },
    skip: !jobId,
  });

  const { t } = useTranslation();
  const onRefresh = async () => {
    return refetch();
  };

  if (loading) {
    return <ActivityIndicator size="large" style={{ flex: 1 }} />;
  }
  if (error) {
    return <ErrorDisplay message={JSON.stringify(error?.message)} />;
  }

  if (!data?.jobs_by_pk) {
    return <ErrorDisplay errorMessage={"Job is not defined."} />;
  }
  const job = data.jobs_by_pk;

  if (job.notes.length === 0)
    return (
      <Card>
        <Card.Content>
          <Text>{t("jobdetail.labels.nojobnotes")}</Text>
        </Card.Content>
      </Card>
    );

  return (
    <FlatList
      refreshControl={
        <RefreshControl refreshing={loading} onRefresh={onRefresh} />
      }
      style={{ flex: 1 }}
      data={job.notes}
      renderItem={(object) => <NoteListItem item={object.item} />}
    />
  );
}

function NoteListItem({ item }) {
  return (
    <Card style={{ margin: 8 }}>
      <Card.Content>
        <View style={{ display: "flex", flex: 1 }}>
          <Text>{item.text}</Text>
          <View
            style={{
              flexDirection: "column",
              alignSelf: "flex-end",
              alignItems: "center",
            }}
          >
            {item.private && (
              <AntDesign
                name="eyeo"
                style={{ margin: 4 }}
                size={24}
                color="black"
              />
            )}
            {item.critical && (
              <AntDesign
                name="warning"
                style={{ margin: 4 }}
                size={24}
                color="tomato"
              />
            )}
            <Text style={{ fontSize: 12 }}>{item.created_by}</Text>
            <Text style={{ fontSize: 12 }}>
              {DateTime.fromISO(item.created_at).toLocaleString(
                DateTime.DATETIME_SHORT
              )}
            </Text>
          </View>
        </View>
      </Card.Content>
    </Card>
  );
}
