
import type { ResponseHistorialPedido, DataHistorial, ResponseDatosIniciales, DatosInicialesHistorialPedidos } from '~/types/HistorialPedidos';
import type { CasoPedidoResponse, Caso } from '~/types/Caso';
import { object, string } from "yup";
export const useHistorialPedidos = () => {

  const { swal } = useSweetAlert();
  const dataHistorial = ref<DataHistorial[]>([]);

  const search = ref("");
  const loading = ref(false);
  const modalNuevoCaso = ref(false);
  const modalHistorial = ref(false)
  const pedidoSeleccionado = ref();
  const datosIniciales = ref<DatosInicialesHistorialPedidos | {}>({});
  const historialCasos = ref<Caso[] | []>([]);
  const nuevoCasoEndPoint = ref("")
  const casoCreado = ref(false)

  // ::::::::::::::   Obtener el historial de pedidos por cliente  ::::::::::::::
  const obtenerHistorialPedidos = async ({
    endpoint = '',
    cliente_id = null,
    fecha_inicio = null,
    fecha_fin = null,
    all = false,
    limit = 12
  }: {
    endpoint?: string;
    cliente_id?: number | string | null;
    fecha_inicio?: string | null;
    fecha_fin?: string | null;
    all?: boolean;
    limit?: number;
  }) => {
    try {
      loading.value = true
      const body: Record<string, any> = {
        "action": "historial_pedidos",
        "cliente_id": cliente_id
      }
      if (fecha_inicio) {
        body.fecha_inicio = fecha_inicio
      }
      if (fecha_fin) {
        body.fecha_fin = fecha_fin
      }
      if (all) {
        body.all = true
      }
      if (limit) {
        body.limit = limit
      }

      const { data, success, message } = await useApiFetch<ResponseHistorialPedido>(
        endpoint,
        {
          method: "POST",
          body,
        },
      );
      if (success) {
        dataHistorial.value = data ?? []
      }
    } catch (err: any) {
      swal.fire({
        title: "Obteniendo historial de pedidos",
        text: err.message || "Ocurrió un error inesperado",
        icon: "error",
      });
    } finally {
      loading.value = false
    }
  }
  // ::::::::::::::   Obtener los datos iniciales para el modal de nuevo caso ::::::::::::::
  const obtenerDatosIniciales = async ({ endpoint = '' }) => {
    try {
      const { data, success, message } = await useApiFetch<ResponseDatosIniciales>(
        endpoint,
        {
          method: "POST",
          body: {
            "action": "datos_iniciales"
          },
        },
      );
      if (success) {
        return data ?? {}
      }
      return {}
    } catch (err: any) {
      swal.fire({
        title: "Ocurrió un error inesperado",
        text: err.message || "Ocurrió un error inesperado",
        icon: "error",
      });
      return {}
    }
  }
  // ::::::::::::::   Historia de casos por pedido ::::::::::::::

  // ::::::::::::::   Crear nuevo Caso ::::::::::::::
  // Peticion
  const crearNuevoCaso = async () => {
    try {
      const body = {
        "action": "store",
        "titulo": titulo.value,
        "asunto_caso_id": asunto_caso_id.value,
        "tipo_caso_id": tipo_caso_id.value,
        "tipo_origen_id": tipo_origen_id.value,
        "prioridad": prioridad.value,
        "pedido_id": pedido_id.value,
        "cliente_id": cliente_id.value,
        "cef_id": cef_id.value
      }
      const { data, success, message } = await useApiFetch<ResponseDatosIniciales>(
        nuevoCasoEndPoint.value,
        {
          method: "POST",
          body: body,
        },
      );
      if (success) {
        reset_caso_form()
        casoCreado.value = true
        modalNuevoCaso.value = false
      }
      swal.fire({
        title: "Crear nuevo caso",
        text: message,
        icon: success ? 'success' : "error",
        showConfirmButton: false,
        timer: 1500
      });
    } catch (err: any) {
      swal.fire({
        title: "Ocurrió un error inesperado",
        text: err.message || "Ocurrió un error inesperado",
        icon: "error",
      });

    }
  }
  //Validaciones 
  const schema = object({
    titulo: string().required("El campo título no puede estar vacío"),
    asunto_caso_id: string().required("Por favor, seleccionar un asunto."),
    tipo_caso_id: string().required("Por favor, seleccionar un caso."),
    tipo_origen_id: string().required("Por favor, seleccionar un origen."),
    prioridad: string().required("Por favor, seleccionar una prioridad."),
    pedido_id: string().nullable(),
    cliente_id: string().nullable(),
    cef_id: string().nullable(),

  });

  const { setValues, submit: nuevoCaso, errors: caso_errors, defineField, resetForm: reset_caso_form } = useFormValidation(
    schema,
    crearNuevoCaso,
  );
  const [titulo] = defineField("titulo");
  const [asunto_caso_id] = defineField("asunto_caso_id");
  const [tipo_caso_id] = defineField("tipo_caso_id");
  const [tipo_origen_id] = defineField("tipo_origen_id");
  const [prioridad] = defineField("prioridad");
  const [pedido_id] = defineField("pedido_id");
  const [cliente_id] = defineField("cliente_id");
  const [cef_id] = defineField("cef_id");

  // ::::::::::::::   Obtener el historial de casos por pedidos ::::::::::::::
  const historialCasosPorPedido = async (pedido: any, { endpoint = '' }) => {

    try {
      historialCasos.value = []
      loading.value = true
      const pedido_id = pedido.id
      const { data, success, message } = await useApiFetch<CasoPedidoResponse>(
        endpoint,
        {
          method: "POST",
          body: {
            "action": "casos_por_pedido",
            pedido_id
          },
        },
      );


      historialCasos.value = success ? data : []

      console.log(data, success, message)
    } catch (err: any) {
      swal.fire({
        title: "Obteniendo historial de pedidos",
        text: err.message || "Ocurrió un error inesperado",
        icon: "error",
        showConfirmButton: false,
        timer: 1500
      });
    } finally {
      loading.value = false
    }

  }

  return {
    obtenerHistorialPedidos,
    obtenerDatosIniciales,
    nuevoCaso,
    historialCasosPorPedido,
    historialCasos,
    nuevoCasoEndPoint,
    casoCreado,
    titulo,
    asunto_caso_id,
    tipo_caso_id,
    tipo_origen_id,
    prioridad,
    pedido_id,
    cliente_id,
    cef_id,
    caso_errors,
    loading,
    dataHistorial,
    search,
    modalNuevoCaso,
    modalHistorial,
    pedidoSeleccionado,
    datosIniciales
  }
}