import { ref } from "vue";
import type { OdontogramData } from "~/types/apps/medical/odontogram";

const STORAGE_KEY = "odontogramData";

const savedData = ref<OdontogramData | null>(null);

function saveData(data: OdontogramData) {
  try {
    // Convert reactive data to plain JS object before saving
    const plainData = JSON.parse(JSON.stringify(data));
    console.log("Saving odontogram data to localStorage (plain):", plainData);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(plainData));
    savedData.value = plainData;
  } catch (error) {
    console.error("Failed to save odontogram data:", error);
  }
}

function loadData(): OdontogramData | null {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    console.log("Loading odontogram data from localStorage:", data);
    if (data) {
      const parsed = JSON.parse(data);
      if (isOdontogramData(parsed)) {
        savedData.value = parsed;
        return parsed;
      }
    }
  } catch (error) {
    console.error("Failed to load odontogram data:", error);
  }
  return null;
}

const clearData = () => {
  try {
    localStorage.removeItem(STORAGE_KEY);
    savedData.value = null;
    return true;
  } catch (error) {
    console.error("Error clearing odontogram data:", error);
    return false;
  }
};

const exportData = (data: OdontogramData) => {
  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: "application/json"
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `odontogram_${new Date().toISOString().split("T")[0]}.json`;
  a.click();
  URL.revokeObjectURL(url);
};

const importData = (file: File): Promise<OdontogramData | null> => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target?.result as string);
        if (isOdontogramData(data)) {
          resolve(data);
        } else {
          console.error("Imported data is not valid OdontogramData");
          resolve(null);
        }
      } catch (error) {
        console.error("Error parsing imported data:", error);
        resolve(null);
      }
    };
    reader.readAsText(file);
  });
};

function isOdontogramData(data: any): data is OdontogramData {
  return (
    data &&
    typeof data === "object" &&
    Array.isArray(data.conditions) &&
    typeof data.metadata === "object" &&
    data.metadata !== null &&
    (data.currentMode === undefined || typeof data.currentMode === "number")
  );
}

export function useDataStorage() {
  return {
    saveData,
    loadData,
    clearData,
    exportData,
    importData,
    savedData
  };
}
