<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useSpaceStore } from '@/stores/spaceStore';
import { useUserStore } from '@/stores/userStore';
import { useRecurrentsStore } from '@/stores/recurrent-store';
import { TransactionType, TransactionKind } from '@/models/enums';
import { Transaction, UpdateTransactionDTO } from '@/models/transaction';
import { TransactionFilters, TransactionService } from '@/services/transactions-service';
import { DashboardService } from '@/services/dashboard-service';
import StatsCard from './StatsCard.vue';
import RecentTransactions from './RecentTransactions.vue';
import DashboardCharts from './DashboardCharts.vue';
import UpcomingTransactions from './UpcomingTransactions.vue';
import { useToast, ProgressSpinner } from 'primevue';
import Button from 'primevue/button';
import { DashboardData } from '@/models/dashboard';


import dayjs from 'dayjs';

const toast = useToast()
const spaceStore = useSpaceStore();
const userStore = useUserStore();
const recurrentsStore = useRecurrentsStore();
const transactionService = TransactionService
const dashboardService = DashboardService


const dashboardData = ref<DashboardData>()
const isAiSummaryExpanded = ref(false)

const dashboardTransactions = ref<Transaction[]>([]);
const plannedTransactions = ref<Transaction[]>([]);

const currentBaseDate = ref(dayjs());

const displayMonth = computed(() => {
  const currentDay = currentBaseDate.value.date();

  // Если текущая дата от 1 до 9, период начинается с 10-го числа предыдущего месяца
  if (currentDay >= 1 && currentDay <= 9) {
    return currentBaseDate.value.subtract(1, 'month').format('MMMM YYYY');
  }

  return currentBaseDate.value.format('MMMM YYYY');
});

const prevMonth = () => {
  currentBaseDate.value = currentBaseDate.value.subtract(1, 'month');
  fetchDashboardData();
};

const nextMonth = () => {
  currentBaseDate.value = currentBaseDate.value.add(1, 'month');
  fetchDashboardData();
};

const currentStartDate = computed(() => {
  const currentDay = currentBaseDate.value.date();

  // Если текущая дата от 1 до 9, период начинается с 10-го числа предыдущего месяца
  if (currentDay >= 1 && currentDay <= 9) {
    return currentBaseDate.value.subtract(1, 'month').date(10).toDate();
  }

  // Если текущая дата от 10 до конца месяца, период начинается с 10-го числа текущего месяца
  return currentBaseDate.value.date(10).toDate();
});

const currentEndDate = computed(() => {
  const currentDay = currentBaseDate.value.date();

  // Если текущая дата от 1 до 9, период заканчивается 9-го числа текущего месяца
  if (currentDay >= 1 && currentDay <= 9) {
    return currentBaseDate.value.date(9).toDate();
  }

  // Если текущая дата от 10 до конца месяца, период заканчивается 9-го числа следующего месяца
  return currentBaseDate.value.add(1, 'month').date(9).toDate();
});

const fetchDashboardData = async () => {
  if (!spaceStore.selectedSpaceId) return;

  const currentDay = currentBaseDate.value.date();
  let startDate: Date;
  let endDate: Date;

  // Если текущая дата от 1 до 9, период: с 10-го предыдущего месяца до 9-го текущего месяца
  if (currentDay >= 1 && currentDay <= 9) {
    startDate = currentBaseDate.value.subtract(1, 'month').date(10).toDate();
    endDate = currentBaseDate.value.date(9).toDate();
  } else {
    // Если текущая дата от 10 до конца месяца, период: с 10-го текущего месяца до 9-го следующего месяца
    startDate = currentBaseDate.value.date(10).toDate();
    endDate = currentBaseDate.value.add(1, 'month').date(9).toDate();
  }

  try {
    dashboardData.value = await dashboardService.fetchDashboardData(spaceStore.selectedSpaceId, startDate, endDate)
    dashboardTransactions.value = dashboardData.value.recentTransactions
    plannedTransactions.value = dashboardData.value.upcomingTransactions
    // console.log(plannedTransactions.value)
    // console.log(dashboardTransactions.value)
    // Fetch transactions for charts and stats (Done transactions)
    // dashboardTransactions.value = await transactionService.getTransactions(spaceStore.selectedSpaceId, {
    //    kind: "INSTANT",
    //     limit: 10,
    //      sorts: [{ "sortBy": "t.date", "sortDirection": "DESC" }, { "sortBy": "t.id", "sortDirection": "DESC" }]
    //      } as TransactionFilters);

    // // Fetch planned transactions for Upcoming Payments
    // plannedTransactions.value = await TransactionService.getTransactions(spaceStore.selectedSpaceId, {
    //   kind: TransactionKind.PLANNING,
    //   isDone: false,
    //   offset: 0,
    //   limit: 5,

    // } as TransactionFilters);
  } catch (e) {
    console.error("Failed to fetch dashboard data", e);
  }
};

const setTransactionDone = async (transaction: Transaction): Promise<void> => {
  // console.log(transaction)
  const updateTransaction = {
    type: transaction.type,
    kind: transaction.kind,
    categoryId: transaction.category.id,
    comment: transaction.comment,
    amount: transaction.amount,
    fees: 0,
    isDone: !transaction.isDone,
    date: new Date(transaction.date),
  } as UpdateTransactionDTO
  // console.log(updateTransaction)
  try {
    await transactionService.updateTransaction(spaceStore.selectedSpaceId as number, transaction.id, updateTransaction)
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: 'Failed to update transactions.',
      detail: String(error),
      life: 3000,
    })
  }
}


onMounted(async () => {
  if (spaceStore.selectedSpaceId) {
    await Promise.all([
      fetchDashboardData(),
      // recurrentsStore.fetchRecurrents(spaceStore.selectedSpaceId)
    ]);
  }
});

watch(() => spaceStore.selectedSpaceId, async (newId) => {
  if (newId) {
    await Promise.all([
      fetchDashboardData(),
      // recurrentsStore.fetchRecurrents(newId)
    ]);
  }
});


const userName = computed(() => {
  return userStore.user?.firstName || 'User';
});
</script>

<template>
  <ProgressSpinner v-if="!dashboardData" />
  <div v-else class="flex flex-col gap-6 w-full pb-20">

    <!-- Header / Greeting -->
    <div class="flex flex-col gap-1 px-1">

      <h1 class="!text-2xl !font-semibold text-surface-900 dark:text-surface-0">
        Hello, {{ userName }}! 👋
      </h1>
      <p class="text-surface-500 dark:text-surface-400">
        Here is your financial overview.
      </p>
      <div class="flex items-center justify-between mb-4">
        <Button icon="pi pi-chevron-left" text rounded @click="prevMonth" />
        <span class="!text-lg !font-semibold !capitalize">{{ displayMonth }}</span>
        <Button icon="pi pi-chevron-right" text rounded @click="nextMonth" />
      </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-2 md:grid-cols-2 gap-4">
      <StatsCard title="Expense" :amount="dashboardData.totalExpense" icon="pi pi-arrow-up-right" color="red" />
      <StatsCard title="Income" :amount="dashboardData.totalIncome" icon="pi pi-arrow-down-left" color="green" />
      <div class="col-span-2">
        <StatsCard title="Total Balance" :amount="dashboardData.balance" icon="pi pi-wallet" color="blue" />
      </div>
    </div>
    <div class="flex flex-col card">
      <span class="text-xl !font-semibold pl-1 mb-2">AI Summary</span>
      <div v-if="dashboardData.analyzedText" class="ai-summary-wrapper">
        <div :class="['ai-summary-content', { 'expanded': isAiSummaryExpanded }]" class="">
          <div class="flex flex-col gap-0">
            <span class="text-lg bold">Общая оценка</span>
            <span class="!whitespace-pre-wrap" v-html="dashboardData.analyzedText.common" />
          </div>
          <div class="h-4" />
          <div class="flex flex-col gap-0">
            <span class="text-lg bold">Анализ категорий</span>
            <span class="!whitespace-pre-wrap" v-html="dashboardData.analyzedText.categoryAnalysis" />
          </div>
          <div class="h-4" />
          <div class="flex flex-col gap-0">
            <span class="text-lg bold">Ключевые инсайты</span>
            <span class="!whitespace-pre-wrap" v-html="dashboardData.analyzedText.keyInsights" />
          </div>
          <div class="h-4" />
          <div class="flex flex-col gap-0">
            <span class="text-lg bold">Рекомендации</span>
            <span class="!whitespace-pre-wrap" v-html="dashboardData.analyzedText.recommendations" />
          </div>
        </div>
        <div v-if="!isAiSummaryExpanded" class="ai-summary-fade"></div>
      </div>
      <div v-else
        class="flex flex-col items-center justify-center p-8 text-center bg-gray-50 dark:bg-gray-800 rounded-lg">
        <i class="pi pi-sparkles text-4xl text-blue-400 mb-3"></i>
        <span class="text-lg text-gray-500 font-medium">To see AI Analysis please add some comments to your transactions
        </span>
      </div>
      <Button v-if="dashboardData.analyzedText" :label="isAiSummaryExpanded ? 'Show less' : 'Show more'"
        :icon="isAiSummaryExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'" class="expand-button"
        @click="isAiSummaryExpanded = !isAiSummaryExpanded" />
    </div>
    <!-- Charts & Upcoming -->
    <div class="grid grid-cols-1 lg:grid-cols-1 gap-4">
      <!-- Charts -->
      <DashboardCharts :categories="dashboardData.categories" :transactions="dashboardTransactions"
        :weeks="dashboardData.weeks" :startDate="currentStartDate" :endDate="currentEndDate" />

      <!-- Upcoming Transactions -->
      <div class=" ">
        <UpcomingTransactions :transactions="plannedTransactions" @set-tx-done="setTransactionDone" />
      </div>
    </div>

    <!-- Recent Transactions -->
    <RecentTransactions :transactions="dashboardTransactions" />
  </div>
</template>

<style scoped>
.ai-summary-wrapper {
  position: relative;
}

.ai-summary-content {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  transition: all 0.3s ease;
  line-height: 1.6;
}

.ai-summary-content.expanded {
  display: block;
  -webkit-line-clamp: unset;
}

.ai-summary-fade {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3em;
  background: linear-gradient(to bottom,
      transparent 0%,
      rgba(255, 255, 255, 0.7) 50%,
      rgba(255, 255, 255, 0.95) 100%);
  pointer-events: none;
  transition: opacity 0.3s ease;
}

:global(.dark) .ai-summary-fade {
  background: linear-gradient(to bottom,
      transparent 0%,
      rgba(24, 24, 27, 0.7) 50%,
      rgba(24, 24, 27, 0.95) 100%);
}

.expand-button {
  margin-top: 1rem;
  align-self: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  color: white !important;
  padding: 0.625rem 1.5rem !important;
  border-radius: 2rem !important;
  font-weight: 500 !important;
  font-size: 0.875rem !important;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease !important;
}

.expand-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%) !important;
}

b {
  font-weight: bold !important;
}

.expand-button:active {
  transform: translateY(0);
}
</style>