import { GET_JOB_LINES } from "@/graphql/jobs.queries";
import { useQuery } from "@apollo/client";
import { useGlobalSearchParams } from "expo-router";
import React from "react";
import { useTranslation } from "react-i18next";
import { ScrollView, useWindowDimensions } from "react-native";
import { ActivityIndicator, DataTable, useTheme } from "react-native-paper";
import ErrorDisplay from "../error/error-display";

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

  const { loading, error, data, refetch } = useQuery(GET_JOB_LINES, {
    variables: {
      id: jobId,
    },
    skip: !jobId,
  });
  const { width, height } = useWindowDimensions();
  const isLandscape = width > height;
  const theme = useTheme();
  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)} />;
  }

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

  const job = data.jobs_by_pk;
  return (
    <ScrollView style={{ flex: 1, marginHorizontal: isLandscape ? 48 : 12 }}>
      <DataTable>
        <DataTable.Header>
          <DataTable.Title style={{ flex: 4 }}>
            {t("jobdetail.labels.lines_desc")}
          </DataTable.Title>
          <DataTable.Title style={{ flex: 2 }}>
            {t("jobdetail.labels.lines_lbr_ty")}
          </DataTable.Title>
          <DataTable.Title style={{ flex: 1 }}>
            {t("jobdetail.labels.lines_lb_hrs")}
          </DataTable.Title>
          <DataTable.Title style={{ flex: 2 }}>
            {t("jobdetail.labels.lines_part_type")}
          </DataTable.Title>
          <DataTable.Title style={{ flex: 1 }}>
            {t("jobdetail.labels.lines_qty")}
          </DataTable.Title>
        </DataTable.Header>

        {job.joblines.map((item, index) => (
          <DataTable.Row
            key={item.id}
            style={{
              backgroundColor: index % 2 === 0 && theme.colors.surface,
            }}
          >
            <DataTable.Cell style={{ flex: 4 }}>
              {item.line_desc}
            </DataTable.Cell>
            <DataTable.Cell style={{ flex: 2 }}>
              {item.mod_lbr_ty && t(`jobdetail.lbr_types.${item.mod_lbr_ty}`)}
            </DataTable.Cell>
            <DataTable.Cell style={{ flex: 1 }}>
              {item.mod_lb_hrs}
            </DataTable.Cell>
            <DataTable.Cell style={{ flex: 2 }}>
              {item.part_type && t(`jobdetail.part_types.${item.part_type}`)}
            </DataTable.Cell>
            <DataTable.Cell style={{ flex: 1 }}>{item.part_qty}</DataTable.Cell>
          </DataTable.Row>
        ))}
      </DataTable>
    </ScrollView>
  );
}
