<script setup lang="ts">
import { ref, onMounted } from "vue";
import { invoke } from "@tauri-apps/api/core";

interface StorageConfig {
  folder_path: string;
  max_size_bytes: number;
  warn_at_percent: number;
  auto_cleanup_enabled: boolean;
}

interface FolderValidation {
  is_valid: boolean;
  error_message?: string;
  available_space_bytes: number;
  recommended_max_size: number;
  warnings: string[];
}

interface StorageStatus {
  used_bytes: number;
  total_allocated_bytes: number;
  usage_percent: number;
  chunks_count: number;
  disk_available_bytes: number;
  needs_attention: boolean;
}

const currentStep = ref(1);
const suggestions = ref<string[]>([]);
const selectedFolder = ref("");
const validation = ref<FolderValidation | null>(null);
const maxSizeGB = ref(10);
const isCreating = ref(false);
const status = ref<StorageStatus | null>(null);

const formatBytes = (bytes: number): string => {
  const units = ["B", "KB", "MB", "GB", "TB"];
  let size = bytes;
  let unitIndex = 0;

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  return unitIndex === 0
    ? `${Math.floor(size)} ${units[unitIndex]}`
    : `${size.toFixed(2)} ${units[unitIndex]}`;
};

const loadSuggestions = async () => {
  try {
    suggestions.value = await invoke("get_default_storage_suggestions");
    if (suggestions.value.length > 0) {
      selectedFolder.value = suggestions.value[0];
    }
  } catch (error) {
    console.error("Failed to load suggestions:", error);
  }
};

const validateFolder = async () => {
  if (!selectedFolder.value) return;

  try {
    validation.value = await invoke("validate_storage_folder", {
      folderPath: selectedFolder.value
    });
    if (validation.value?.is_valid) {
      maxSizeGB.value = Math.floor(validation.value.recommended_max_size / (1024 * 1024 * 1024));
    }
  } catch (error) {
    console.error("Failed to validate folder:", error);
  }
};

const createStorage = async () => {
  if (!selectedFolder.value || !validation.value?.is_valid) return;

  isCreating.value = true;
  try {
    const config: StorageConfig = {
      folder_path: selectedFolder.value,
      max_size_bytes: maxSizeGB.value * 1024 * 1024 * 1024,
      warn_at_percent: 80.0,
      auto_cleanup_enabled: true
    };

    await invoke("create_storage_folder", { config });
    currentStep.value = 3;
    loadStatus();
  } catch (error) {
    console.error("Failed to create storage:", error);
  } finally {
    isCreating.value = false;
  }
};

const loadStatus = async () => {
  if (!selectedFolder.value) return;

  try {
    status.value = await invoke("get_storage_status", {
      folderPath: selectedFolder.value
    });
  } catch (error) {
    console.error("Failed to load status:", error);
  }
};

onMounted(() => {
  loadSuggestions();
});
</script>

<template>
  <main class="container">
    <h1>ZephyrFS Storage Node Setup</h1>

    <!-- Step 1: Folder Selection -->
    <div v-if="currentStep === 1" class="step">
      <h2>Step 1: Choose Storage Location</h2>
      <p>Select a safe folder to store encrypted chunks from other users.</p>

      <div class="suggestions">
        <h3>Recommended locations:</h3>
        <div class="folder-options">
          <label v-for="suggestion in suggestions" :key="suggestion" class="folder-option">
            <input
              type="radio"
              v-model="selectedFolder"
              :value="suggestion"
              @change="validateFolder"
            />
            <span>{{ suggestion }}</span>
          </label>
        </div>
      </div>

      <div class="custom-folder">
        <label>
          Custom folder path:
          <input
            type="text"
            v-model="selectedFolder"
            @input="validateFolder"
            placeholder="Enter custom folder path..."
          />
        </label>
      </div>

      <div v-if="validation" class="validation">
        <div v-if="validation.is_valid" class="valid">
          ✓ Valid location
          <p>Available space: {{ formatBytes(validation.available_space_bytes) }}</p>
          <p>Recommended max: {{ formatBytes(validation.recommended_max_size) }}</p>
        </div>
        <div v-else class="invalid">
          ✗ {{ validation.error_message }}
        </div>

        <div v-if="validation.warnings.length > 0" class="warnings">
          <h4>Warnings:</h4>
          <ul>
            <li v-for="warning in validation.warnings" :key="warning">{{ warning }}</li>
          </ul>
        </div>
      </div>

      <button
        @click="currentStep = 2"
        :disabled="!validation?.is_valid"
        class="next-btn"
      >
        Next: Configure Storage
      </button>
    </div>

    <!-- Step 2: Storage Configuration -->
    <div v-if="currentStep === 2" class="step">
      <h2>Step 2: Configure Storage Allocation</h2>
      <p>Set how much space to dedicate to ZephyrFS storage.</p>

      <div class="config-section">
        <label>
          Maximum Storage (GB):
          <input
            type="number"
            v-model="maxSizeGB"
            min="1"
            :max="Math.floor((validation?.recommended_max_size || 0) / (1024 * 1024 * 1024))"
          />
        </label>
        <p class="size-info">{{ formatBytes(maxSizeGB * 1024 * 1024 * 1024) }}</p>
      </div>

      <div class="safety-info">
        <h3>Safety Guarantees:</h3>
        <ul>
          <li>✓ All stored data is encrypted and unreadable</li>
          <li>✓ No personal information is stored</li>
          <li>✓ You can safely delete this folder anytime</li>
          <li>✓ Storage is limited to your specified amount</li>
        </ul>
      </div>

      <div class="buttons">
        <button @click="currentStep = 1" class="back-btn">Back</button>
        <button
          @click="createStorage"
          :disabled="isCreating"
          class="create-btn"
        >
          {{ isCreating ? "Creating..." : "Create Storage Node" }}
        </button>
      </div>
    </div>

    <!-- Step 3: Success & Status -->
    <div v-if="currentStep === 3" class="step">
      <h2>✓ Storage Node Ready!</h2>
      <p>Your ZephyrFS storage node has been created successfully.</p>

      <div v-if="status" class="status-panel">
        <h3>Current Status:</h3>
        <div class="status-grid">
          <div class="status-item">
            <span class="label">Used Space:</span>
            <span class="value">{{ formatBytes(status.used_bytes) }}</span>
          </div>
          <div class="status-item">
            <span class="label">Total Allocated:</span>
            <span class="value">{{ formatBytes(status.total_allocated_bytes) }}</span>
          </div>
          <div class="status-item">
            <span class="label">Usage:</span>
            <span class="value">{{ status.usage_percent.toFixed(1) }}%</span>
          </div>
          <div class="status-item">
            <span class="label">Chunks Stored:</span>
            <span class="value">{{ status.chunks_count }}</span>
          </div>
        </div>

        <div class="progress-bar">
          <div
            class="progress-fill"
            :style="{ width: `${Math.min(status.usage_percent, 100)}%` }"
          ></div>
        </div>
      </div>

      <div class="next-steps">
        <h3>What's Next:</h3>
        <p>Your storage node will now participate in the ZephyrFS network, safely storing encrypted chunks from other users.</p>
        <p>Check the system tray for real-time status updates.</p>
      </div>
    </div>
  </main>
</template>

<style scoped>
.step {
  max-width: 600px;
  margin: 0 auto;
  padding: 2rem;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.suggestions {
  margin: 1.5rem 0;
}

.folder-options {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin: 1rem 0;
}

.folder-option {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.folder-option:hover {
  background-color: #f5f5f5;
}

.custom-folder {
  margin: 1.5rem 0;
}

.custom-folder input {
  width: 100%;
  margin-top: 0.5rem;
}

.validation {
  margin: 1.5rem 0;
  padding: 1rem;
  border-radius: 6px;
}

.valid {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.invalid {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.warnings {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
  border-radius: 6px;
}

.config-section {
  margin: 1.5rem 0;
}

.size-info {
  font-size: 0.9rem;
  color: #666;
  margin-top: 0.5rem;
}

.safety-info {
  margin: 2rem 0;
  padding: 1.5rem;
  background-color: #e8f5e8;
  border-radius: 8px;
}

.safety-info ul {
  list-style: none;
  padding: 0;
}

.safety-info li {
  margin: 0.5rem 0;
  padding-left: 1rem;
}

.buttons {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
}

.next-btn, .create-btn {
  background-color: #007bff;
  color: white;
}

.back-btn {
  background-color: #6c757d;
  color: white;
}

.next-btn:disabled, .create-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.status-panel {
  margin: 2rem 0;
  padding: 1.5rem;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin: 1rem 0;
}

.status-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem;
  background-color: white;
  border-radius: 4px;
}

.label {
  font-weight: 500;
}

.value {
  font-weight: 600;
  color: #007bff;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  margin: 1rem 0;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #28a745;
  transition: width 0.3s ease;
}

.next-steps {
  margin: 2rem 0;
  padding: 1.5rem;
  background-color: #e8f4fd;
  border-radius: 8px;
}

@media (prefers-color-scheme: dark) {
  .step {
    background-color: #2d2d2d;
    color: #f6f6f6;
  }

  .folder-option {
    border-color: #555;
    background-color: #333;
  }

  .folder-option:hover {
    background-color: #444;
  }

  .status-panel {
    background-color: #333;
  }

  .status-item {
    background-color: #444;
  }

  .safety-info {
    background-color: #2d4a2d;
  }

  .next-steps {
    background-color: #2d3a4a;
  }
}
</style>
<style>
:root {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  font-size: 16px;
  line-height: 24px;
  font-weight: 400;

  color: #0f0f0f;
  background-color: #f6f6f6;

  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-text-size-adjust: 100%;
}

.container {
  margin: 0;
  padding-top: 10vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: 0.75s;
}

.logo.tauri:hover {
  filter: drop-shadow(0 0 2em #24c8db);
}

.row {
  display: flex;
  justify-content: center;
}

a {
  font-weight: 500;
  color: #646cff;
  text-decoration: inherit;
}

a:hover {
  color: #535bf2;
}

h1 {
  text-align: center;
}

input,
button {
  border-radius: 8px;
  border: 1px solid transparent;
  padding: 0.6em 1.2em;
  font-size: 1em;
  font-weight: 500;
  font-family: inherit;
  color: #0f0f0f;
  background-color: #ffffff;
  transition: border-color 0.25s;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}

button {
  cursor: pointer;
}

button:hover {
  border-color: #396cd8;
}
button:active {
  border-color: #396cd8;
  background-color: #e8e8e8;
}

input,
button {
  outline: none;
}

#greet-input {
  margin-right: 5px;
}

@media (prefers-color-scheme: dark) {
  :root {
    color: #f6f6f6;
    background-color: #2f2f2f;
  }

  a:hover {
    color: #24c8db;
  }

  input,
  button {
    color: #ffffff;
    background-color: #0f0f0f98;
  }
  button:active {
    background-color: #0f0f0f69;
  }
}

</style>