import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";

import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { api } from "@/services/api";
import { ruleEngineService, type RuleEngineListParams } from "@/services/ruleEngine/ruleEngine.service";
import { RULE_ENGINE_SELECT_NONE } from "@/pages/ruleEngine/config/resources";
import type {
  RuleEngineRecord,
  RuleEngineResourceSlug,
} from "@/types/rule-engine";
import {
  invalidateRuleEngineList,
  patchRuleEngineListRecord,
} from "@/utils/queryInvalidation";

const CARGO_TYPE_PARENT_PAGE_SIZE = 500;
const CONTAINER_TYPE_OPTIONS_PAGE_SIZE = 500;

export const useRuleEngineList = (
  resource: RuleEngineResourceSlug,
  params: RuleEngineListParams,
) =>
  useQuery({
    queryKey: QUERY_KEYS.RULE_ENGINE.list(resource, params),
    queryFn: () => ruleEngineService.list(resource, params),
  });

const ORDER_LIST_PAGE_SIZE = 500;

export const useRuleEngineOrderList = (
  resource: RuleEngineResourceSlug,
  enabled: boolean,
  sortBy?: string,
) =>
  useQuery({
    queryKey: QUERY_KEYS.RULE_ENGINE.orderList(resource),
    queryFn: () =>
      ruleEngineService.list(resource, {
        page: 1,
        pageSize: ORDER_LIST_PAGE_SIZE,
        sortBy,
        sortOrder: "ASC",
      }),
    enabled,
  });

export const useRuleEngineOrderMutations = (resource: RuleEngineResourceSlug) => {
  const qc = useQueryClient();

  const reorder = useMutation({
    mutationFn: (payload: { ids: string[]; requiresDirectorApproval?: boolean }) =>
      ruleEngineService.reorder(resource, payload),
    onSuccess: async () => {
      toast.success("Order updated");
      await invalidateRuleEngineList(qc, resource);
      await qc.invalidateQueries({ queryKey: QUERY_KEYS.RULE_ENGINE.orderList(resource) });
    },
    onError: () => toast.error("Failed to update order"),
  });

  const moveOrder = useMutation({
    mutationFn: ({ id, direction }: { id: string; direction: "up" | "down" }) =>
      ruleEngineService.moveOrder(resource, id, direction),
    onSuccess: async () => {
      await invalidateRuleEngineList(qc, resource);
      await qc.invalidateQueries({ queryKey: QUERY_KEYS.RULE_ENGINE.orderList(resource) });
    },
    onError: () => toast.error("Cannot move item further in that direction"),
  });

  return { reorder, moveOrder };
};

export const useCargoTypeParentOptions = (excludeId?: string, enabled = true) =>
  useQuery({
    queryKey: QUERY_KEYS.RULE_ENGINE.selectOptions("cargo-types"),
    queryFn: () =>
      ruleEngineService.list<RuleEngineRecord>("cargo-types", {
        page: 1,
        pageSize: CARGO_TYPE_PARENT_PAGE_SIZE,
      }),
    enabled,
    select: (result) => {
      const noneOption = { label: "None", value: RULE_ENGINE_SELECT_NONE };
      const parents = (result.data ?? [])
        .filter((row) => row.id && String(row.id) !== excludeId)
        .map((row) => {
          const name = String(row.cargoTypeName ?? "").trim();
          const code = String(row.code ?? "").trim();
          const label =
            name && code ? `${name} (${code})` : name || code || String(row.id);
          return { label, value: String(row.id) };
        });
      return [noneOption, ...parents];
    },
  });

/**
 * Cargo-type options restricted to LEAF nodes (actual commodities, not parent
 * groups). A node is a leaf when no other cargo type names it as parent. Used
 * by the Rate form's "Bulk cargo type" picker.
 */
export const useCargoLeafOptions = (enabled = true) =>
  useQuery({
    queryKey: QUERY_KEYS.RULE_ENGINE.selectOptions("cargo-types", { leafOnly: true }),
    queryFn: () =>
      ruleEngineService.list<RuleEngineRecord>("cargo-types", {
        page: 1,
        pageSize: CARGO_TYPE_PARENT_PAGE_SIZE,
      }),
    enabled,
    select: (result) => {
      const rows = result.data ?? [];
      const parentIds = new Set(
        rows
          .map((row) => row.parentGroupId)
          .filter((id): id is string => Boolean(id))
          .map((id) => String(id)),
      );
      return rows
        .filter((row) => row.id && !parentIds.has(String(row.id)))
        .map((row) => {
          const name = String(row.cargoTypeName ?? "").trim();
          const code = String(row.code ?? "").trim();
          const label =
            name && code ? `${name} (${code})` : name || code || String(row.id);
          return { label, value: String(row.id) };
        });
    },
  });

export function buildContainerTypeSelectOptions(
  rows: RuleEngineRecord[],
  includeNone: boolean,
): { label: string; value: string }[] {
  const options = rows
    .filter((row) => row.id)
    .map((row) => {
      const label = String(row.label ?? "").trim();
      const code = String(row.code ?? "").trim();
      const size = row.sizeFt ? `${String(row.sizeFt)}ft` : "";
      const parts = [label || code || String(row.id), size].filter(Boolean);
      return {
        label: parts.join(" - "),
        value: String(row.id),
      };
    });

  if (!includeNone) return options;
  return [{ label: "None", value: RULE_ENGINE_SELECT_NONE }, ...options];
}

export const useContainerTypeOptions = (
  includeNone = true,
  enabled = true,
) =>
  useQuery({
    queryKey: QUERY_KEYS.RULE_ENGINE.selectOptions('container-types', {
      page: 1,
      pageSize: CONTAINER_TYPE_OPTIONS_PAGE_SIZE,
      includeNone,
    }),
    queryFn: () =>
      api.ruleEngine.list.call({
        resource: "container-types",
        params: {
          page: 1,
          pageSize: CONTAINER_TYPE_OPTIONS_PAGE_SIZE,
        },
      }),
    enabled,
    select: (result) =>
      buildContainerTypeSelectOptions(result.data ?? [], includeNone),
  });

const LIVE_RATE_PAGE_SIZE = 500;

export const useLiveRateOptions = (enabled = true) =>
  useQuery({
    queryKey: QUERY_KEYS.RULE_ENGINE.selectOptions("rates", { status: "LIVE" }),
    queryFn: () =>
      ruleEngineService.list<RuleEngineRecord>("rates", {
        page: 1,
        pageSize: LIVE_RATE_PAGE_SIZE,
        status: "LIVE",
      }),
    enabled,
    select: (result) =>
      (result.data ?? [])
        .filter((row) => row.id)
        .map((row) => {
          const rateType = String(row.rateType ?? "").replace(/_/g, " ");
          const currency = String(row.currency ?? "");
          const value = row.rateValue != null ? String(row.rateValue) : "";
          const unit = row.rateUnit ? String(row.rateUnit).replace(/_/g, " ") : "";
          const parts = [rateType, currency, value, unit].filter(Boolean);
          return {
            label: parts.join(" · "),
            value: String(row.id),
          };
        }),
  });

export const useApprovalChain = (enabled: boolean) =>
  useQuery({
    queryKey: QUERY_KEYS.RULE_ENGINE.chain,
    queryFn: () => ruleEngineService.getApprovalChain(),
    enabled,
  });

export const useRuleEngineMutations = (resource: RuleEngineResourceSlug) => {
  const qc = useQueryClient();

  const create = useMutation({
    mutationFn: (payload: Record<string, unknown>) =>
      api.ruleEngine.create.call({ resource, payload }),
    onSuccess: async (created) => {
      toast.success("Created successfully");
      patchRuleEngineListRecord(qc, resource, created);
      await invalidateRuleEngineList(qc, resource);
    },
    onError: () => toast.error("Failed to create record"),
  });

  const update = useMutation({
    mutationFn: ({
      id,
      payload,
    }: {
      id: string;
      payload: Record<string, unknown>;
    }) => api.ruleEngine.update.call({ resource, id, payload }),
    onSuccess: async (updated) => {
      toast.success("Updated successfully");
      patchRuleEngineListRecord(qc, resource, updated);
      await invalidateRuleEngineList(qc, resource);
    },
    onError: () => toast.error("Failed to update record"),
  });

  const remove = useMutation({
    mutationFn: (id: string) =>
      api.ruleEngine.remove.call({ resource, id }),
    onSuccess: async () => {
      toast.success("Deleted successfully");
      await invalidateRuleEngineList(qc, resource);
    },
    onError: () => toast.error("Failed to delete record"),
  });

  return { create, update, remove };
};

export const useRateWorkflow = () => {
  const qc = useQueryClient();

  const submit = useMutation({
    mutationFn: (id: string) => api.ruleEngine.submitRate.call({ id }),
    onSuccess: async (updated) => {
      toast.success("Rate submitted for approval");
      patchRuleEngineListRecord(qc, "rates", updated);
      await invalidateRuleEngineList(qc, "rates");
    },
    onError: () => toast.error("Failed to submit rate"),
  });

  const approve = useMutation({
    mutationFn: (id: string) => api.ruleEngine.approveRate.call({ id }),
    onSuccess: async (updated) => {
      toast.success("Rate approved");
      patchRuleEngineListRecord(qc, "rates", updated);
      await invalidateRuleEngineList(qc, "rates");
    },
    onError: () => toast.error("Failed to approve rate"),
  });

  return { submit, approve };
};
