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, { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { FlatList, RefreshControl, View } from "react-native";
import { ActivityIndicator, Button, Card, Text } from "react-native-paper";
import ErrorDisplay from "../error/error-display";
import NewNoteModal from "./new-note-modal";

export default function JobNotes() {
  const { jobId } = useGlobalSearchParams();
  const [noteModalVisible, setNoteModalVisible] = useState(false);
  const showNoteModal = () => setNoteModalVisible(true);
  const hideNoteModal = () => setNoteModalVisible(false);

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

  const handleNoteCreated = useCallback(() => {
    hideNoteModal();
    refetch();
  }, [refetch]);

  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;

  return (
    <View style={{ flex: 1, display: "flex" }}>
      <Button
        icon="plus"
        mode="outlined"
        onPress={showNoteModal}
        style={{ margin: 8 }}
      >
        {t("jobdetail.actions.addnote")}
      </Button>
      {job.notes.length === 0 ? (
        <Card>
          <Card.Content>
            <Text>{t("jobdetail.labels.nojobnotes")}</Text>
          </Card.Content>
        </Card>
      ) : (
        <FlatList
          refreshControl={
            <RefreshControl refreshing={loading} onRefresh={onRefresh} />
          }
          style={{ flex: 1 }}
          data={job.notes}
          renderItem={(object) => <NoteListItem item={object.item} />}
        />
      )}
      <NewNoteModal
        jobId={jobId}
        visible={noteModalVisible}
        onDismiss={hideNoteModal}
        onCreated={handleNoteCreated}
        relatedRos={[]} // TODO: supply relatedRos list
      />
    </View>
  );
}

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="eye-invisible"
                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>
  );
}
