import { defineStore } from "pinia";
import { ref } from "vue";

export const useRegistrationFlowStore = defineStore("registrationFlow", () => {
  const email = ref("");
  const phone = ref("");
  const code = ref("");
  const document = ref("");
  const name = ref("");

  const initialLat = ref(null);
  const initialLng = ref(null);

  const confirmedLat = ref(null);
  const confirmedLng = ref(null);
  const confirmedAddress = ref("");
  const confirmedNumber = ref("");
  const confirmedDistrict = ref("");
  const confirmedCity = ref("");
  const confirmedState = ref("");
  const confirmedZipCode = ref("");

  const setCredentials = (e, p, c) => {
    email.value = e;
    phone.value = p;
    code.value = c;
  };

  const setInitialLocation = (lat, lng) => {
    initialLat.value = lat;
    initialLng.value = lng;
  };

  const setRegistrationData = (data) => {
    document.value = data.document ?? "";
    name.value = data.name ?? "";
    phone.value = data.phone ?? phone.value;
  };

  const setConfirmedLocation = (data) => {
    confirmedLat.value = data.lat;
    confirmedLng.value = data.lng;
    confirmedAddress.value = data.address ?? "";
    confirmedNumber.value = data.number ?? "";
    confirmedDistrict.value = data.district ?? "";
    confirmedCity.value = data.city ?? "";
    confirmedState.value = data.state ?? "";
    confirmedZipCode.value = data.zip_code ?? "";
  };

  const clear = () => {
    email.value = "";
    phone.value = "";
    code.value = "";
    document.value = "";
    name.value = "";
    initialLat.value = null;
    initialLng.value = null;
    confirmedLat.value = null;
    confirmedLng.value = null;
    confirmedAddress.value = "";
    confirmedNumber.value = "";
    confirmedDistrict.value = "";
    confirmedCity.value = "";
    confirmedState.value = "";
    confirmedZipCode.value = "";
  };

  const hasCredentials = () => !!(email.value || phone.value) && !!code.value;
  const hasInitialLocation = () =>
    initialLat.value !== null && initialLng.value !== null;
  const hasConfirmedLocation = () =>
    confirmedLat.value !== null && confirmedLng.value !== null;

  return {
    email,
    phone,
    code,
    document,
    name,
    initialLat,
    initialLng,
    confirmedLat,
    confirmedLng,
    confirmedAddress,
    confirmedNumber,
    confirmedDistrict,
    confirmedCity,
    confirmedState,
    confirmedZipCode,
    setCredentials,
    setInitialLocation,
    setRegistrationData,
    setConfirmedLocation,
    clear,
    hasCredentials,
    hasInitialLocation,
    hasConfirmedLocation,
  };
});
