<script setup lang="ts">
import { ref, onMounted } from "vue";
import { load } from "@tauri-apps/plugin-store";
import { open } from "@tauri-apps/plugin-dialog";
import { convertFileSrc, invoke } from "@tauri-apps/api/core";
import { FolderOpen, Settings, Play, Pause, Maximize2, X } from "lucide-vue-next";

const isSetupComplete = ref(false);
const savePath = ref("");
const isPaused = ref(false);

const currentDate = ref(new Date().toISOString().split("T")[0]); // YYYY-MM-DD
const timelineImages = ref<{ time: string; path: string }[]>([]);
const selectedImage = ref<{ time: string; path: string } | null>(null);
const isFullscreen = ref(false);
const isSettingsOpen = ref(false);
const mergeScreens = ref(false);
const retainDays = ref(30);

let store: any = null;

onMounted(async () => {
  store = await load("config.json");
  const path = await store.get("savePath");
  if (path) {
    savePath.value = path as string;
    isSetupComplete.value = true;
    mergeScreens.value = (await store.get("mergeScreens")) as boolean || false;
    retainDays.value = (await store.get("retainDays")) as number || 30;
    isPaused.value = await invoke("get_pause_state");
    await loadTimeline();
  }
});

const selectFolder = async () => {
  const selected = await open({
    directory: true,
    multiple: false,
  });
  if (selected && typeof selected === "string") {
    savePath.value = selected;
    await store.set("savePath", selected);
    await store.save();
    isSetupComplete.value = true;
    await loadTimeline();
  }
};

const updateSettings = async () => {
  await store.set("mergeScreens", mergeScreens.value);
  await store.set("retainDays", retainDays.value);
  await store.save();
};

const togglePauseState = async () => {
  isPaused.value = await invoke("toggle_pause");
};

const loadTimeline = async () => {
  if (!savePath.value) return;
  const dateStr = currentDate.value;
  // Rust is joining paths, Tauri FS plugin has a resolve function or we can use string concat.
  // Wait, readDir with an absolute path requires specific permissions in Tauri v2, or we need to use Rust to list files.
  // Actually, standard `readDir` supports absolute paths if we configure scope in capabilities.
  // We didn't allow `$fs:allow-read-all` or similar, we only added `fs:default`.
  // The simplest way to fetch timeline is a custom Rust command since we already manage the paths there!
  // It's safer to read files from Rust and return a list of { time, absolute_path }.
  timelineImages.value = await invoke("get_timeline", { date: dateStr, baseDir: savePath.value });
};

const refresh = async () => {
  await loadTimeline();
};

const selectImage = (img: { time: string; path: string }) => {
  selectedImage.value = img;
};

const getSrc = (path: string) => {
  return convertFileSrc(path);
};

</script>

<template>
  <div class="h-screen w-screen flex flex-col overflow-hidden text-main bg-light">
    <!-- Setup Wizard -->
    <div v-if="!isSetupComplete" class="flex-1 flex items-center justify-center">
      <div class="bg-white p-10 rounded-3xl shadow-[0_12px_30px_rgba(0,0,0,0.04)] max-w-md text-center">
        <h1 class="text-3xl font-semibold mb-4 text-main">Welcome to Chrono Snap</h1>
        <p class="text-sec mb-8">Please select a folder to save your screenshots.</p>
        <button 
          @click="selectFolder"
          class="bg-[#007AFF] text-white px-6 py-3 rounded-xl font-medium hover:bg-[#0063CC] transition shadow-[0_4px_12px_rgba(0,122,255,0.25)] flex items-center justify-center gap-2 w-full"
        >
          <FolderOpen :size="20" />
          Choose Folder
        </button>
      </div>
    </div>

    <!-- Main App -->
    <div v-else class="flex flex-1 overflow-hidden">
      <!-- Sidebar -->
      <div class="w-64 bg-sidebar border-r border-[#E5E5E7] flex flex-col">
        <div class="p-6 pb-2">
          <h2 class="text-xl font-semibold mb-4">Timeline</h2>
          <input 
            type="date" 
            v-model="currentDate" 
            @change="loadTimeline"
            class="w-full bg-white border border-[#E5E5E7] rounded-xl px-4 py-2 text-sm focus:outline-none focus:border-[#007AFF]"
          />
        </div>
        
        <div class="flex-1 overflow-y-auto px-4 py-2 space-y-2 no-scrollbar">
          <div 
            v-for="img in timelineImages" 
            :key="img.path"
            @click="selectImage(img)"
            class="p-3 rounded-xl cursor-pointer transition flex justify-between items-center"
            :class="selectedImage?.path === img.path ? 'bg-[#007AFF] text-white shadow-sm' : 'hover:bg-white text-sec hover:text-main'"
          >
            <span class="font-medium">{{ img.time }}</span>
          </div>
          <div v-if="timelineImages.length === 0" class="text-center text-sm text-sec mt-10">
            No records for this day.
          </div>
        </div>

        <div class="p-4 border-t border-[#E5E5E7] flex justify-between items-center bg-sidebar">
          <button 
            @click="togglePauseState"
            class="p-2 rounded-lg hover:bg-[#E5E5E7] transition text-sec"
            :title="isPaused ? 'Resume' : 'Pause'"
          >
            <Play v-if="isPaused" :size="20" />
            <Pause v-else :size="20" />
          </button>
          
          <button 
            @click="refresh"
            class="text-sm font-medium text-[#007AFF] px-3 py-1 rounded-lg hover:bg-white transition"
          >
            Refresh
          </button>
          
          <button 
            @click="isSettingsOpen = true"
            class="p-2 rounded-lg hover:bg-[#E5E5E7] transition text-sec"
            title="Settings"
          >
            <Settings :size="20" />
          </button>
        </div>
      </div>

      <!-- Content Area -->
      <div class="flex-1 bg-light flex flex-col relative">
        <div v-if="selectedImage" class="flex-1 p-10 flex items-center justify-center overflow-hidden">
          <div class="relative max-w-full max-h-full group">
            <img 
              :src="getSrc(selectedImage.path)" 
              class="max-w-full max-h-full object-contain rounded-2xl shadow-[0_12px_30px_rgba(0,0,0,0.08)]"
            />
            <button 
              @click="isFullscreen = true"
              class="absolute top-4 right-4 bg-black/50 text-white p-2 rounded-xl opacity-0 group-hover:opacity-100 transition backdrop-blur-md"
            >
              <Maximize2 :size="20" />
            </button>
          </div>
        </div>
        <div v-else class="flex-1 flex items-center justify-center text-sec">
          Select a point in the timeline to view.
        </div>
      </div>
    </div>

    <!-- Settings Modal -->
    <div 
      v-if="isSettingsOpen" 
      class="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-8 backdrop-blur-sm"
      @click.self="isSettingsOpen = false"
    >
      <div class="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden">
        <div class="p-6 border-b border-[#E5E5E7] flex justify-between items-center">
          <h2 class="text-xl font-semibold">Settings</h2>
          <button @click="isSettingsOpen = false" class="text-sec hover:text-main">
            <X :size="24" />
          </button>
        </div>
        <div class="p-8 space-y-6">
          <div class="space-y-2">
            <label class="text-sm font-medium text-sec">Save Path</label>
            <div class="flex gap-2">
              <input 
                type="text" 
                readonly 
                :value="savePath"
                class="flex-1 bg-sidebar border border-[#E5E5E7] rounded-xl px-4 py-2 text-sm text-sec outline-none"
              />
              <button 
                @click="selectFolder"
                class="bg-sidebar border border-[#E5E5E7] p-2 rounded-xl hover:bg-[#E5E5E7] transition"
              >
                <FolderOpen :size="18" />
              </button>
            </div>
          </div>

          <div class="flex items-center justify-between">
            <div>
              <div class="font-medium">Merge Screens</div>
              <div class="text-xs text-sec">Combine all monitors into one image</div>
            </div>
            <button 
              @click="mergeScreens = !mergeScreens; updateSettings()"
              class="w-12 h-6 rounded-full transition relative"
              :class="mergeScreens ? 'bg-[#007AFF]' : 'bg-[#E5E5E7]'"
            >
              <div 
                class="absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform"
                :style="{ transform: mergeScreens ? 'translateX(24px)' : 'translateX(0)' }"
              ></div>
            </button>
          </div>

          <div class="space-y-2">
            <div class="flex justify-between">
              <label class="text-sm font-medium">Retention Period</label>
              <span class="text-sm text-[#007AFF] font-semibold">{{ retainDays }} Days</span>
            </div>
            <input 
              type="range" 
              v-model.number="retainDays" 
              min="1" 
              max="90" 
              @change="updateSettings"
              class="w-full h-1.5 bg-[#E5E5E7] rounded-lg appearance-none cursor-pointer accent-[#007AFF]"
            />
          </div>
        </div>
        <div class="p-6 bg-sidebar border-t border-[#E5E5E7] text-center">
          <p class="text-xs text-sec">Changes are saved automatically.</p>
        </div>
      </div>
    </div>

    <!-- Fullscreen Modal -->
    <div 
      v-if="isFullscreen && selectedImage" 
      class="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-8 backdrop-blur-sm"
    >
      <button 
        @click="isFullscreen = false"
        class="absolute top-8 right-8 text-white/70 hover:text-white transition"
      >
        <X :size="32" />
      </button>
      <img 
        :src="getSrc(selectedImage.path)" 
        class="max-w-full max-h-full object-contain"
      />
    </div>
  </div>
</template>

<style>
/* Custom scrollbar for timeline */
.no-scrollbar::-webkit-scrollbar {
  width: 4px;
}
.no-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}
.no-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(0,0,0,0.1);
  border-radius: 20px;
}
</style>
