<script setup lang="ts">
  import { ref, onMounted } from "vue";
  import PageLayout from "@/components/PageLayout.vue";
  import {
    Card,
    CardHeader,
    CardTitle,
    CardContent,
    CardFooter,
  } from "@/components/ui/card";
  import { Button } from "@/components/ui/button";
  import { Label } from "@/components/ui/label";
  import { Input } from "@/components/ui/input";
  import {
    Bell,
    Database,
    Wifi,
    WifiOff,
    Moon,
    Sun,
    Smartphone,
    AlertCircle,
  } from "lucide-vue-next";
  import { useAuthStore } from "@/stores/auth";
  import { 
    requestNotificationPermission,
    registerServiceWorker,
    subscribeToPushNotifications 
  } from "@/lib/pwa-utils";

  // Initialize store
  const authStore = useAuthStore();

  // Settings state
  const notificationsEnabled = ref(
    localStorage.getItem("notificationsEnabled") === "true",
  );
  const darkMode = ref(localStorage.getItem("darkMode") === "true");
  const offlineMode = ref(localStorage.getItem("offlineMode") === "true");
  const budgetAlertThreshold = ref(
    parseInt(localStorage.getItem("budgetAlertThreshold") || "80"),
  );

  // PWA status
  const isPWAInstalled = ref(false);
  const isOnline = ref(navigator.onLine);
  const serviceWorkerRegistered = ref(false);
  const pushPermission = ref("default");
  const pushSubscribed = ref(false);
  const isSubscribing = ref(false);
  const subscriptionError = ref("");

  // Check if PWA is installed
  onMounted(async () => {
    // Check network status
    isOnline.value = navigator.onLine;
    window.addEventListener("online", () => {
      isOnline.value = true;
    });
    window.addEventListener("offline", () => {
      isOnline.value = false;
    });

    // Check if the app is installed as PWA
    if (window.matchMedia("(display-mode: standalone)").matches) {
      isPWAInstalled.value = true;
    }

    // Check if push notifications are supported and permission status
    if ("Notification" in window) {
      pushPermission.value = Notification.permission;
    }

    // Check if service worker is registered
    if ("serviceWorker" in navigator) {
      try {
        const registrations = await navigator.serviceWorker.getRegistrations();
        serviceWorkerRegistered.value = registrations.length > 0;
        
        // Check if already subscribed to push
        if (serviceWorkerRegistered.value) {
          const registration = await navigator.serviceWorker.ready;
          const subscription = await registration.pushManager.getSubscription();
          pushSubscribed.value = !!subscription;
        }
      } catch (error) {
        console.error("Error checking service worker:", error);
      }
    }
  });

  // Toggle notifications
  const toggleNotifications = async () => {
    if ("Notification" in window) {
      if (Notification.permission !== "granted") {
        const permission = await Notification.requestPermission();
        if (permission === "granted") {
          notificationsEnabled.value = true;
          pushPermission.value = "granted";
          
          // Subscribe to push notifications if permission granted
          subscribeToPushService();
        } else {
          notificationsEnabled.value = false;
          pushPermission.value = permission;
          return;
        }
      } else {
        notificationsEnabled.value = !notificationsEnabled.value;
        
        if (notificationsEnabled.value && !pushSubscribed.value) {
          subscribeToPushService();
        }
      }

      localStorage.setItem(
        "notificationsEnabled",
        notificationsEnabled.value.toString(),
      );
    }
  };
  
  // Subscribe to push notification service
  const subscribeToPushService = async () => {
    if (!authStore.isAuthenticated) {
      subscriptionError.value = "You must be signed in to receive notifications";
      return;
    }
    
    isSubscribing.value = true;
    subscriptionError.value = "";
    
    try {
      // Ensure service worker is registered
      if (!serviceWorkerRegistered.value) {
        await registerServiceWorker();
        serviceWorkerRegistered.value = true;
      }
      
      // Request permission if not already granted
      if (Notification.permission !== "granted") {
        const permission = await requestNotificationPermission();
        if (permission !== "granted") {
          pushPermission.value = permission;
          throw new Error("Notification permission denied");
        }
      }
      
      // Subscribe to push notifications
      const subscription = await subscribeToPushNotifications();
      if (subscription) {
        pushSubscribed.value = true;
        notificationsEnabled.value = true;
        localStorage.setItem("notificationsEnabled", "true");
      } else {
        throw new Error("Failed to subscribe to push notifications");
      }
    } catch (error) {
      console.error("Error subscribing to push notifications:", error);
      subscriptionError.value = (error as Error).message || "Failed to subscribe to push notifications";
    } finally {
      isSubscribing.value = false;
    }
  };

  // Toggle dark mode
  const toggleDarkMode = () => {
    darkMode.value = !darkMode.value;
    localStorage.setItem("darkMode", darkMode.value.toString());

    // Apply dark mode
    if (darkMode.value) {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  };

  // Toggle offline mode
  const toggleOfflineMode = () => {
    offlineMode.value = !offlineMode.value;
    localStorage.setItem("offlineMode", offlineMode.value.toString());
  };

  // Update budget threshold
  const updateBudgetThreshold = () => {
    localStorage.setItem(
      "budgetAlertThreshold",
      budgetAlertThreshold.value.toString(),
    );
  };

  // Clear all stored data
  const clearStoredData = () => {
    if (
      confirm(
        "Are you sure you want to clear all locally stored data? This action cannot be undone.",
      )
    ) {
      localStorage.removeItem("transactions");
      localStorage.removeItem("categories");
      // Keep settings and auth data
      alert("Local transaction and category data cleared.");
    }
  };
</script>

<template>
  <PageLayout header="Settings">
    <div class="max-w-4xl mx-auto space-y-6">
      <!-- App Settings -->
      <Card>
        <CardHeader>
          <CardTitle>Application Settings</CardTitle>
        </CardHeader>
        <CardContent class="space-y-4">
          <!-- Theme Toggle -->
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <Label>Theme</Label>
              <div class="text-sm text-gray-500 dark:text-gray-400">
                Choose between light and dark mode
              </div>
            </div>
            <Button
              @click="toggleDarkMode"
              variant="outline"
              size="sm"
              class="ml-auto">
              <Sun v-if="darkMode" class="h-4 w-4 mr-2" />
              <Moon v-else class="h-4 w-4 mr-2" />
              {{ darkMode ? "Light Mode" : "Dark Mode" }}
            </Button>
          </div>

          <!-- Notification Settings -->
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <Label>Push Notifications</Label>
              <div class="text-sm text-gray-500 dark:text-gray-400">
                Enable transaction alerts and reminders
              </div>
              <div
                v-if="pushPermission === 'denied'"
                class="text-xs text-red-500 mt-1">
                Permission denied. Please enable notifications in your browser
                settings.
              </div>
              <div
                v-if="subscriptionError"
                class="text-xs text-red-500 mt-1 flex items-center">
                <AlertCircle class="h-3 w-3 mr-1" />
                {{ subscriptionError }}
              </div>
              <div 
                v-if="pushSubscribed" 
                class="text-xs text-green-600 mt-1">
                Subscribed to transaction notifications
              </div>
            </div>
            <Button
              @click="toggleNotifications"
              variant="outline"
              size="sm"
              class="ml-auto"
              :disabled="pushPermission === 'denied' || isSubscribing"
              :loading="isSubscribing">
              <Bell class="h-4 w-4 mr-2" />
              {{ notificationsEnabled ? "Disable" : "Enable" }}
            </Button>
          </div>

          <!-- Budget Alert Threshold -->
          <div class="space-y-2">
            <Label for="threshold">Budget Alert Threshold (%)</Label>
            <div class="flex items-center gap-4">
              <Input
                id="threshold"
                type="number"
                min="1"
                max="100"
                v-model="budgetAlertThreshold"
                class="w-24" />
              <Button @click="updateBudgetThreshold" size="sm">Save</Button>
            </div>
            <p class="text-sm text-gray-500">
              Receive alerts when you've spent this percentage of your budget
            </p>
          </div>

          <!-- Offline Mode -->
          <div class="flex items-center justify-between">
            <div class="space-y-0.5">
              <Label>Offline Mode</Label>
              <div class="text-sm text-gray-500 dark:text-gray-400">
                Prioritize working offline when possible
              </div>
              <div
                class="text-xs"
                :class="isOnline ? 'text-green-600' : 'text-amber-600'">
                Status: {{ isOnline ? "Online" : "Offline" }}
              </div>
            </div>
            <Button
              @click="toggleOfflineMode"
              variant="outline"
              size="sm"
              class="ml-auto">
              <Wifi v-if="offlineMode" class="h-4 w-4 mr-2" />
              <WifiOff v-else class="h-4 w-4 mr-2" />
              {{ offlineMode ? "Disable" : "Enable" }}
            </Button>
          </div>
        </CardContent>
      </Card>

      <!-- PWA Information -->
      <Card>
        <CardHeader>
          <CardTitle>Progressive Web App</CardTitle>
        </CardHeader>
        <CardContent class="space-y-4">
          <div class="space-y-2">
            <div class="flex items-center justify-between">
              <p class="font-medium">Installation Status</p>
              <span
                :class="isPWAInstalled ? 'text-green-600' : 'text-gray-600'">
                {{ isPWAInstalled ? "Installed" : "Not Installed" }}
              </span>
            </div>

            <div class="flex items-center justify-between">
              <p class="font-medium">Service Worker</p>
              <span
                :class="
                  serviceWorkerRegistered ? 'text-green-600' : 'text-gray-600'
                ">
                {{ serviceWorkerRegistered ? "Registered" : "Not Registered" }}
              </span>
            </div>

            <div class="flex items-center justify-between">
              <p class="font-medium">Push Notifications</p>
              <span
                :class="
                  pushSubscribed ? 'text-green-600' : 'text-gray-600'
                ">
                {{ pushSubscribed ? "Subscribed" : "Not Subscribed" }}
              </span>
            </div>

            <div v-if="!isPWAInstalled" class="mt-4">
              <p class="text-sm text-gray-600 mb-2">
                Install this app on your device for better performance and
                offline access
              </p>
              <div class="flex items-center">
                <Smartphone class="h-4 w-4 mr-2 text-gray-600" />
                <span class="text-sm"
                  >Use your browser's "Add to Home Screen" option</span
                >
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Data Management -->
      <Card>
        <CardHeader>
          <CardTitle>Data Management</CardTitle>
        </CardHeader>
        <CardContent class="space-y-4">
          <div class="space-y-2">
            <Label>Local Data</Label>
            <div class="flex items-center justify-between">
              <div class="text-sm text-gray-500">
                Clear locally stored transaction and category data
              </div>
              <Button @click="clearStoredData" variant="destructive" size="sm">
                <Database class="h-4 w-4 mr-2" />
                Clear Data
              </Button>
            </div>
          </div>

          <div class="pt-4 mt-4 border-t border-gray-200 dark:border-gray-700">
            <p class="text-sm text-gray-500">
              Signed in as:
              <span class="font-medium">{{
                authStore.user?.username || "Guest"
              }}</span>
            </p>
            <p class="text-sm text-gray-500">
              Account type:
              <span class="font-medium">{{ authStore.userRole }}</span>
            </p>
            <Button
              v-if="authStore.isAuthenticated"
              @click="authStore.logout"
              variant="outline"
              class="mt-2"
              size="sm">
              Sign Out
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  </PageLayout>
</template>
