import { DateFormatter, getLocalTimeZone, today } from '@internationalized/date'
import type { CasoActivoResponse, CasoActivo } from '~/types/Caso';
import type {
  ActividadReponse,
  Actividad,
  TipoactividadResponse,
  Tipoactividad,
  NuevaActividad,
  NuevaActividadReponse,
  CerrarCasoResponse
} from '~/types/ActividaCaso';
import { useCasoStore } from "~/store/casos";

export const useCasos = () => {

  const { swal } = useSweetAlert();
  const casoStore = useCasoStore();
  const casos = ref<CasoActivo[]>([]);
  const caso = ref<CasoActivo>();
  const search = ref("");
  const endpoint = ref("");
  const loading = ref(false);
  const modalActividad = ref(false);
  const modalNuevaActividad = ref(false);
  const tipoActividades = ref<Tipoactividad[]>([]);
  const actividades = ref<Actividad[]>([]);
  // Calendar 
  const df = new DateFormatter('es-ES', { dateStyle: 'medium' })
  const tz = getLocalTimeZone()
  const initialEnd = today(tz)
  const fecha = ref({
    start: initialEnd,
    end: initialEnd
  })

  const label = computed(() => {
    const { start, end } = fecha.value
    if (!start) return 'Seleccionar una fecha'
    if (!end) return df.format(start.toDate(tz))
    return `${df.format(start.toDate(tz))} - ${df.format(end.toDate(tz))}`
  })
  // Ejecutar metodo al seleccionar rango de fechas
  watch(
    () => fecha.value,
    (newRange, oldRange) => {
      if (newRange?.start && newRange?.end) {
        const dias = validacionRangoFechas(newRange)
        if (dias) {
          console.log(newRange?.start.toString(), newRange?.end.toString())
          obtenerCasos(newRange?.start.toString(), newRange?.end.toString())
        } else {

        }
        console.log('DATA-DIAS', dias)
      }
    }
  )
  // ::::::::::::::  Validacion de dias seleccionados  ::::::::::::::
  const validacionRangoFechas = (newRange: any,) => {
    const inicio = newRange.start.toDate(getLocalTimeZone())
    const fin = newRange.end.toDate(getLocalTimeZone())
    const dias = Math.floor(
      (fin.getTime() - inicio.getTime()) / (1000 * 60 * 60 * 24)
    ) + 1
    const result = dias >= 32 ? false : true
    return result
  }

  // ::::::::::::::   Obtener los datos iniciales para el modal de nuevo caso ::::::::::::::
  const obtenerCasos = async (fecha_inicio = '', fecha_fin = '', cliente_id: number | null = null) => {
    try {
      console.log('Endpoint', endpoint.value)
      loading.value = true
      const body: Record<string, any> = {
        "action": "index",
        fecha_inicio,
        fecha_fin
      }
      if (cliente_id !== null) {
        body.cliente_id = cliente_id
      }
      const { data, success, message } = await useApiFetch<CasoActivoResponse>(
        endpoint.value,
        {
          method: "POST",
          body,
        },
      );
      casos.value = success ? data : []
    } catch (err: any) {
      swal.fire({
        title: "Ocurrió un error inesperado",
        text: err.message || "Ocurrió un error inesperado",
        icon: "error",
      });
    } finally {
      loading.value = false
    }
  }

  // ::::::::::::::   Obtener el listado de tipo de actividades  ::::::::::::::
  const obtenerTipoActividades = async (endpoint: string) => {
    try {
      loading.value = true
      modalNuevaActividad.value = true
      const actividades = casoStore.tipo_actividades.length
      if (actividades <= 0) {
        const { data, success, message } = await useApiFetch<TipoactividadResponse>(
          endpoint,
          {
            method: "POST",
            body: {
              "action": "tipo_actividades"
            }
          },
        );
        if (success) {
          tipoActividades.value = data ?? []
          casoStore.tipo_actividades = data
        }
      } else {
        tipoActividades.value = casoStore.tipo_actividades
      }
    } catch (err: any) {
      swal.fire({
        title: "Ocurrió un error inesperado",
        text: err.message || "Ocurrió un error inesperado",
        icon: "error",
      });
    } finally {
      loading.value = false
    }
  }

  // ::::::::::::::   Obtener el listado de actividades por caso especifico  ::::::::::::::
  const obtenerActividades = async (caso_id: string | number, endpoint: string) => {
    try {
      loading.value = true
      actividades.value = []
      const body = {
        "action": "actividades",
        "caso_id": caso_id
      }
      const { data, success, message } = await useApiFetch<ActividadReponse>(
        endpoint,
        {
          method: "POST",
          body
        },
      );
      if (success) {
        actividades.value = data ?? []

      }

    } catch (err: any) {
      swal.fire({
        title: "Ocurrió un error inesperado",
        text: err.message || "Ocurrió un error inesperado",
        icon: "error",
      });
    } finally {
      loading.value = false
    }
  }

  // ::::::::::::::   Crear una nueva actividad de un caso  ::::::::::::::
  const crearActividad = async (actividad: NuevaActividad, onReset: () => void) => {
    try {
      loading.value = true
      const { data, success, message } = await useApiFetch<NuevaActividadReponse>(
        actividad.endpoint,
        {
          method: "POST",
          body: actividad
        },
      );
      if (success) {
        onReset()
        actividades.value = [data, ...actividades.value];
      }
      swal.fire({
        title: "Crear nueva actividad",
        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",
        showConfirmButton: false,
        timer: 1500
      });
    } finally {
      loading.value = false
    }
  }

  // ::::::::::::::   Resolver caso  ::::::::::::::
  const resolverCaso = async (casoId: string | number,
    descripcion: string, endpoint: string, onReset?: () => void) => {
    try {
      loading.value = true
      const { data, success, message } = await useApiFetch<CerrarCasoResponse>(
        endpoint,
        {
          method: "POST",
          body: {
            action: "cerrar_caso",
            caso_id: casoId,
            resolucion_caso: descripcion
          }
        },
      );

      if (success) {
        const index = casos.value.findIndex(caso => caso.id === data.id);
        if (casos.value[index]) {
          casos.value[index].activo = data.activo
          caso.value!.resolucion_caso = data.resolucion_caso
          caso.value!.usuario_caso_cerrado = data.usuario_caso_cerrado
          caso.value!.updated_at = data.updated_at
        }
        onReset?.()
      }
      swal.fire({
        title: "Cerrar actividad",
        text: message,
        icon: success ? 'success' : 'error',
      });
    } catch (err: any) {
      swal.fire({
        title: "Ocurrió un error inesperado",
        text: err.message || "Ocurrió un error inesperado",
        icon: "error",
      });
    } finally {
      loading.value = false
    }
  }
  return {
    endpoint,
    obtenerCasos,
    obtenerTipoActividades,
    obtenerActividades,
    crearActividad,
    resolverCaso,
    casos,
    caso,
    search,
    loading,
    modalActividad,
    modalNuevaActividad,
    tipoActividades,
    actividades,
    label,
    fecha
  }
}