import { defineStore } from "pinia";
import { ref, reactive, readonly } from "vue";
import type {
  OdontogramData,
  ToothCondition
} from "~/types/apps/medical/odontogram";
import { OdontogramMode } from "~/types/apps/medical/odontogram";
import { useDataStorage } from "~/composables/apps/medical/useDataStorage";

export const useOdontogramStore = defineStore("odontogram", () => {
  const conditions = ref<ToothCondition[]>([]);
  const currentMode = ref<OdontogramMode>(OdontogramMode.DEFAULT);
  const metadata = ref<{ patientId: string; date: string; dentist: string }>({
    patientId: "",
    date: new Date().toISOString().split("T")[0],
    dentist: ""
  });

  const { saveData, loadData } = useDataStorage();

  const addCondition = (condition: ToothCondition) => {
    console.log("addCondition called with:", condition);
    // Remove existing condition for same tooth and surface
    const index = conditions.value.findIndex(
      (c) =>
        c.toothNumber === condition.toothNumber &&
        c.surface === condition.surface
    );

    if (index >= 0) {
      conditions.value.splice(index, 1);
    }

    conditions.value.push(condition);
    saveCurrentData();
  };

  const removeCondition = (toothNumber: string, surface?: string) => {
    const index = conditions.value.findIndex(
      (c) =>
        c.toothNumber === toothNumber && (!surface || c.surface === surface)
    );

    if (index >= 0) {
      conditions.value.splice(index, 1);
      saveCurrentData();
    }
  };

  const clearAllConditions = () => {
    conditions.value = [];
    saveCurrentData();
  };

  const setMode = (mode: OdontogramMode) => {
    currentMode.value = mode;
    saveCurrentData();
  };

  let isLoading = false;

  const saveCurrentData = () => {
    if (isLoading) {
      console.log("Skipping saveCurrentData during loading");
      return;
    }
    console.log("saveCurrentData called with conditions:", conditions.value);
    const data: OdontogramData = {
      conditions: conditions.value,
      metadata: metadata.value,
      currentMode: currentMode.value
    };
    saveData(data);
  };

  const loadStoredData = () => {
    isLoading = true;
    const data = loadData();
    console.log("Loading stored data:", data);
    if (data) {
      conditions.value = data.conditions || [];
      metadata.value = {
        patientId: data.metadata?.patientId ?? "",
        date: data.metadata?.date ?? new Date().toISOString().split("T")[0],
        dentist: data.metadata?.dentist ?? ""
      };
      if (data.currentMode !== undefined) {
        currentMode.value = data.currentMode;
      }
    }
    isLoading = false;
  };

  const exportCurrentData = () => {
    const data: OdontogramData = {
      conditions: conditions.value,
      metadata: {
        patientId: metadata.value.patientId ?? "",
        date: metadata.value.date,
        dentist: metadata.value.dentist ?? ""
      },
      currentMode: currentMode.value
    };
    return data;
  };

  const importData = (data: OdontogramData) => {
    conditions.value = data.conditions || [];
    metadata.value = {
      patientId: data.metadata?.patientId ?? "",
      date: data.metadata?.date ?? new Date().toISOString().split("T")[0],
      dentist: data.metadata?.dentist ?? ""
    };
    if (data.currentMode !== undefined) {
      currentMode.value = data.currentMode;
    }
    saveCurrentData();
  };

  function setConditions(newConditions: ToothCondition[]) {
    conditions.value = newConditions;
    saveCurrentData();
  }

  return {
    conditions: readonly(conditions),
    currentMode: readonly(currentMode),
    metadata,
    addCondition,
    removeCondition,
    clearAllConditions,
    setMode,
    saveCurrentData,
    loadStoredData,
    exportCurrentData,
    importData,
    setConditions,
  };
});
