import { ApolloClient, gql, InMemoryCache, useApolloClient } from "@apollo/client";
import { HttpLink } from "@apollo/client/link/http"; //"apollo-link-http";
import { Button, Space, Table } from "antd";
import React, { useState } from "react";
import { LOCAL_DOESNOTUpsertEstimate } from "../../../ipc/ipc-estimate-utils";
import _ from "lodash";
import moment from "moment/moment";
import { dateSort } from "../../../util/sorters";

const httpLink = new HttpLink({
  uri: import.meta.env.VITE_APP_GRAPHQL_ENDPOINT,
  headers: {
    "x-hasura-admin-secret": `TOBEPOPULATED`
  }
});

const localCLient = new ApolloClient({ link: httpLink, cache: new InMemoryCache({}) });

const startingDate = "2024-06-01";

export default function AdminPage() {
  const client = useApolloClient();
  const clientToUse = client;

  const [wrongGroups, setWrongGroups] = useState([]);

  const handleQuery = async () => {
    //TODO: MAKE SURE THIS USES THE ADMIN SECRET INSTEAD.
    const {
      data: { jobs }
    } = await clientToUse.query({
      variables: {
        createdAtStart: startingDate,
        createdAtEnd: moment(startingDate).add(365, "days").format("YYYY-MM-DD")
      },
      query: gql`
        query ADMIN_GET_JOBS($createdAtStart: timestamptz, $createdAtEnd: timestamptz) {
          jobs(
            where: {
              _and: [
                { requires_reimport: { _eq: false } }
                { created_at: { _gte: $createdAtStart } }
                { created_at: { _lte: $createdAtEnd } }
                { _or: [{ close_date: { _is_null: true } }, { close_date: { _gte: "2024-09-01" } }] }
              ]
            }
          ) {
            ownr_ln
            ownr_fn
            ins_co_nm
            group
            group_verified
            clm_total
            clm_no
            bodyshopid
            close_date
            id
            loss_date
            updated_at
            created_at
            v_age
            v_makedesc
            v_model
            v_model_yr
            v_vin
            v_type
            requires_reimport
            v_mileage
          }
        }
      `
    });

    const NoDateSetJobs = jobs.filter((j) => !j.close_date);

    //For the jobs that DO have a date,  let's see their group.
    const JobsInWrongGroup = [];
    const AllJobResults = [];
    for (const job of jobs.filter((j) => true || j.close_date)) {
      const initialJob = { ...job };

      const calcedGroup = await LOCAL_DOESNOTUpsertEstimate(initialJob);
      AllJobResults.push({
        close_date: job.close_date,
        make: initialJob.v_makedesc,
        model: initialJob.v_model,
        type: initialJob.v_type,
        calced_v_type: calcedGroup.v_type,
        job_group: initialJob.group,
        calced_group: calcedGroup.group
      });
      if (initialJob.group !== calcedGroup.group) {
        JobsInWrongGroup.push({ ...job, calced_group: calcedGroup.group, calced_v_type: calcedGroup.v_type });
      }
      // break;
    }

    console.table(AllJobResults);
    console.log(`Found ${JobsInWrongGroup.length} jobs that are in the wrong group.`);
    console.table(JobsInWrongGroup.map((j) => _.pick(j, ["v_makedesc", "v_model", "group", "calced_group"])));
    setWrongGroups(JobsInWrongGroup);
    const jobsToMarkForReimport = [...NoDateSetJobs, ...JobsInWrongGroup];
  };

  const handleUpdate = async () => {
    //TODO: MAKE SURE THIS USES THE ADMIN SECRET INSTEAD.
    const data = await clientToUse.mutate({
      variables: {
        jobs: wrongGroups.map((j) => j.id)
      },
      mutation: gql`
        mutation ADMIN_UPDATE_JOBS($jobs: [uuid!]!) {
          update_jobs(where: { id: { _in: $jobs } }, _set: { requires_reimport: true }) {
            affected_rows
          }
        }
      `
    });

    console.log("Updated Rows", data);
  };
  return (
    <div style={{ height: "100%" }}>
      <Space>
        <Button onClick={handleQuery}>Run the query</Button>
        <Button danger onClick={handleUpdate}>
          UPDATE THE GROUPS {wrongGroups.length}
        </Button>
      </Space>
      <Table
        title={() => "Jobs with the wrong group set."}
        dataSource={wrongGroups}
        columns={[
          { key: "bodyshopid", dataIndex: "bodyshopid", title: "Shop ID" },
          { key: "id", dataIndex: "id", title: "job ID" },
          {
            key: "created_at",
            dataIndex: "created_at",
            title: "Created",
            sorter: (a, b) => dateSort(a.created_at, b.created_at),
            render: (record) => moment(record).format("YYYY-MM-DD")
          },
          {
            key: "close_date",
            dataIndex: "close_date",
            title: "Close Date",
            sorter: (a, b) => dateSort(a.close_date, b.close_date)
          },
          { key: "clm_no", dataIndex: "clm_no", title: "Claim" },
          { key: "v_makedesc", dataIndex: "v_makedesc", title: "Make" },
          { key: "v_model", dataIndex: "v_model", title: "Model" },
          { key: "v_age", dataIndex: "v_age", title: "Age" },
          { key: "v_type", dataIndex: "v_type", title: "Type" },
          { key: "calced_v_type", dataIndex: "calced_v_type", title: "CALCED Type" },
          { key: "group", dataIndex: "group", title: "Group" },
          { key: "calced_group", dataIndex: "calced_group", title: "CALCED Group" }
        ]}
        pagination={{ pageSize: 20 }}
        rowKey={"id"}
      />
    </div>
  );
}
