<script setup lang="ts">
  import { ref, onMounted, computed } from "vue";
  import { useRouter, useRoute } 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";
  import { Save, Loader2, ArrowLeft } from "lucide-vue-next";

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

  // Get transaction ID from route params
  const transactionId = route.params.id as string;

  // 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]);
  const originalTransaction = ref<any>(null);

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

  // Filter categories based on transaction type
  const filteredCategories = computed(() => {
    return categoriesStore.categories;
  });

  // Load transaction data and categories on mount
  onMounted(async () => {
    isLoading.value = true;

    try {
      // Fetch categories if not already loaded
      if (categoriesStore.categories.length === 0) {
        await categoriesStore.fetchCategories();
      }

      // Fetch transactions if not already loaded
      if (transactionsStore.transactions.length === 0) {
        await transactionsStore.fetchTransactions();
      }

      // Find the transaction by ID
      const transaction = transactionsStore.transactions.find(
        (t) => t._id === transactionId,
      );

      if (!transaction) {
        errorMessage.value = "Transaction not found";
        return;
      }

      // Populate form with transaction data
      originalTransaction.value = { ...transaction };
      transactionType.value = transaction.type;
      amount.value = transaction.amount;
      description.value = transaction.description || "";
      categoryId.value = transaction.categoryId;
      date.value = new Date(transaction.date).toISOString().split("T")[0];
    } catch (error) {
      console.error("Error loading transaction:", error);
      errorMessage.value = "Failed to load transaction data";
    } finally {
      isLoading.value = false;
    }
  });

  // Update transaction
  const updateTransaction = async () => {
    if (!amount.value) {
      errorMessage.value = "Please enter an amount";
      return;
    }

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

    if (!date.value) {
      errorMessage.value = "Please enter a date";
      return;
    }

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

    try {
      const updatedTransaction = {
        _id: transactionId,
        amount: amount.value,
        type: transactionType.value,
        categoryId: categoryId.value,
        description: description.value,
        date: date.value,
      };

      const success =
        await transactionsStore.updateTransaction(updatedTransaction);

      if (success) {
        successMessage.value = "Transaction updated successfully";
        setTimeout(() => {
          router.push("/transactions");
        }, 1500);
      } else {
        errorMessage.value = "Failed to update transaction";
      }
    } catch (error) {
      console.error("Error updating transaction:", error);
      errorMessage.value = "An unexpected error occurred";
    } finally {
      isSubmitting.value = false;
    }
  };

  // Cancel and go back
  const cancelEdit = () => {
    router.go(-1);
  };
</script>

<template>
  <PageLayout header="Edit Transaction">
    <div class="max-w-md mx-auto">
      <Card>
        <CardHeader>
          <CardTitle class="text-lg">Edit Transaction</CardTitle>
        </CardHeader>

        <CardContent>
          <div v-if="isLoading" class="py-8 text-center">
            <Loader2 class="h-8 w-8 mx-auto animate-spin text-primary" />
            <p class="mt-2 text-gray-500">Loading transaction data...</p>
          </div>

          <div
            v-else-if="errorMessage && !originalTransaction"
            class="py-8 text-center">
            <p class="text-red-500">{{ errorMessage }}</p>
            <Button
              variant="outline"
              class="mt-4"
              @click="router.push('/transactions')">
              <ArrowLeft class="mr-2 h-4 w-4" />
              Back to Transactions
            </Button>
          </div>

          <form v-else @submit.prevent="updateTransaction" class="space-y-4">
            <!-- Success message -->
            <div
              v-if="successMessage"
              class="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded text-sm">
              {{ successMessage }}
            </div>

            <!-- Error message -->
            <div
              v-if="errorMessage"
              class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded text-sm">
              {{ errorMessage }}
            </div>

            <!-- Transaction type -->
            <div class="space-y-2">
              <Label>Transaction Type</Label>
              <div class="flex gap-4">
                <div class="flex items-center">
                  <input
                    type="radio"
                    id="expense"
                    value="expense"
                    v-model="transactionType"
                    name="transactionType"
                    class="h-4 w-4 text-primary border-gray-300 mr-2" />
                  <Label for="expense" class="text-sm cursor-pointer"
                    >Expense</Label
                  >
                </div>
                <div class="flex items-center">
                  <input
                    type="radio"
                    id="income"
                    value="income"
                    v-model="transactionType"
                    name="transactionType"
                    class="h-4 w-4 text-primary border-gray-300 mr-2" />
                  <Label for="income" class="text-sm cursor-pointer"
                    >Income</Label
                  >
                </div>
              </div>
            </div>

            <!-- Amount -->
            <div class="space-y-2">
              <Label for="amount">Amount</Label>
              <Input
                id="amount"
                type="number"
                step="0.01"
                min="0.01"
                v-model="amount"
                required />
            </div>

            <!-- Category -->
            <div class="space-y-2">
              <Label for="category">Category</Label>
              <select
                id="category"
                v-model="categoryId"
                required
                class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-input">
                <option value="" disabled>Select a category</option>
                <option
                  v-for="category in filteredCategories"
                  :key="category._id"
                  :value="category._id">
                  {{ category.name }}
                </option>
              </select>
            </div>

            <!-- Description -->
            <div class="space-y-2">
              <Label for="description">Description (optional)</Label>
              <Input
                id="description"
                type="text"
                v-model="description"
                placeholder="Enter a description" />
            </div>

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

        <CardFooter class="flex justify-between">
          <Button
            variant="outline"
            @click="cancelEdit"
            :disabled="isSubmitting">
            Cancel
          </Button>
          <Button
            variant="default"
            @click="updateTransaction"
            :disabled="isSubmitting"
            class="ml-2">
            <Loader2 v-if="isSubmitting" class="mr-2 h-4 w-4 animate-spin" />
            <Save v-else class="mr-2 h-4 w-4" />
            Save Changes
          </Button>
        </CardFooter>
      </Card>
    </div>
  </PageLayout>
</template>
