<script setup lang="ts">
  import { ref, onMounted } from "vue";
  import { useRouter } from "vue-router";
  import PageLayout from "@/components/PageLayout.vue";
  import {
    Card,
    CardHeader,
    CardTitle,
    CardContent,
    CardFooter,
  } from "@/components/ui/card";
  import { Button } from "@/components/ui/button";
  import { Input } from "@/components/ui/input";
  import { Label } from "@/components/ui/label";
  import { useTransactionsStore } from "@/stores/transactions";
  import { useCategoriesStore } from "@/stores/categories";

  // Initialize stores and router
  const router = useRouter();
  const transactionsStore = useTransactionsStore();
  const categoriesStore = useCategoriesStore();

  // Form data
  const transactionType = ref<"income" | "expense">("expense");
  const amount = ref<number>(0);
  const description = ref<string>("");
  const categoryId = ref<string>("");
  const date = ref<string>(new Date().toISOString().split("T")[0]);

  // Form state
  const isSubmitting = ref<boolean>(false);
  const errorMessage = ref<string>("");
  const successMessage = ref<string>("");

  // Load categories on mount
  onMounted(async () => {
    // Force refresh categories from server to ensure we have latest
    await categoriesStore.refreshCategories();

    // Set default category if available
    if (categoriesStore.categories.length > 0) {
      categoryId.value = categoriesStore.categories[0]._id || "";
    }
  });

  // Submit form
  const submitTransaction = async () => {
    // Validate form
    if (amount.value <= 0) {
      errorMessage.value = "Amount must be greater than zero";
      return;
    }

    if (!categoryId.value) {
      errorMessage.value = "Please select a category";
      return;
    }

    try {
      isSubmitting.value = true;
      errorMessage.value = "";
      successMessage.value = "";

      // Create transaction object
      const transaction = {
        amount: amount.value,
        type: transactionType.value,
        categoryId: categoryId.value,
        description: description.value,
        date: new Date(date.value).toISOString(),
      };

      // Add transaction
      await transactionsStore.addTransaction(transaction);

      // Check if there was an error during the transaction
      if (transactionsStore.error) {
        errorMessage.value = `Failed to sync transaction: ${transactionsStore.error}`;
        successMessage.value =
          "Transaction saved locally and will sync when online.";
      } else {
        // Show success message
        successMessage.value = "Transaction added successfully!";

        // Reset form after success
        setTimeout(() => {
          router.push("/transactions");
        }, 1500);
      }
    } catch (error: any) {
      errorMessage.value = `Failed to add transaction: ${error.message}`;
      console.error("Error adding transaction:", error);
    } finally {
      isSubmitting.value = false;
    }
  };
</script>

<template>
  <PageLayout header="Add Transaction">
    <div class="max-w-2xl mx-auto">
      <Card>
        <CardHeader>
          <CardTitle>New Transaction</CardTitle>
        </CardHeader>
        <CardContent>
          <!-- Success/Error Messages -->
          <div
            v-if="successMessage"
            class="mb-4 p-3 bg-green-50 border border-green-200 text-green-700 rounded">
            {{ successMessage }}
          </div>
          <div
            v-if="errorMessage"
            class="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded">
            {{ errorMessage }}
          </div>

          <form @submit.prevent="submitTransaction" class="space-y-4">
            <!-- Transaction Type -->
            <div class="grid grid-cols-2 gap-4">
              <Button
                type="button"
                :variant="transactionType === 'expense' ? 'default' : 'outline'"
                @click="transactionType = 'expense'"
                class="w-full"
                :disabled="isSubmitting">
                Expense
              </Button>
              <Button
                type="button"
                :variant="transactionType === 'income' ? 'default' : 'outline'"
                @click="transactionType = 'income'"
                class="w-full"
                :disabled="isSubmitting">
                Income
              </Button>
            </div>

            <!-- Amount -->
            <div class="space-y-2">
              <Label for="amount">Amount</Label>
              <Input
                id="amount"
                v-model.number="amount"
                type="number"
                min="0"
                step="0.01"
                placeholder="0.00"
                required
                :disabled="isSubmitting" />
            </div>

            <!-- Date -->
            <div class="space-y-2">
              <Label for="date">Date</Label>
              <Input
                id="date"
                v-model="date"
                type="date"
                required
                :disabled="isSubmitting" />
            </div>

            <!-- Category -->
            <div class="space-y-2">
              <Label for="category">Category</Label>
              <select
                id="category"
                v-model="categoryId"
                class="w-full rounded-md border border-gray-300 px-3 py-2"
                required
                :disabled="isSubmitting || categoriesStore.loading">
                <option
                  v-if="categoriesStore.loading"
                  disabled
                  value="">
                  Loading categories...
                </option>
                <option
                  v-else-if="categoriesStore.categories.length === 0"
                  disabled
                  value="">
                  No categories available
                </option>
                <option
                  v-for="category in categoriesStore.categories"
                  :key="category._id"
                  :value="category._id">
                  {{ category.name }} {{ category.icon ? category.icon : '' }}
                </option>
              </select>
              <div v-if="categoriesStore.categories.length === 0 && !categoriesStore.loading" 
                   class="mt-2 text-sm text-red-500">
                Please add categories in the Categories section first
              </div>
            </div>

            <!-- Description -->
            <div class="space-y-2">
              <Label for="description">Description (optional)</Label>
              <Input
                id="description"
                v-model="description"
                placeholder="Enter description"
                :disabled="isSubmitting" />
            </div>
          </form>
        </CardContent>
        <CardFooter class="flex justify-between">
          <Button
            variant="outline"
            @click="router.push('/transactions')"
            :disabled="isSubmitting">
            Cancel
          </Button>
          <Button @click="submitTransaction" :disabled="isSubmitting">
            {{ isSubmitting ? "Saving..." : "Save Transaction" }}
          </Button>
        </CardFooter>
      </Card>
    </div>
  </PageLayout>
</template>
