<template>
  <div class="member-dashboard">
    <!-- Animated Header -->
    <div 
      v-motion
      :initial="{ opacity: 0, y: -20 }"
      :enter="{ 
        opacity: 1, 
        y: 0,
        transition: {
          duration: 600,
          type: 'spring'
        }
      }"
      class="dashboard-header"
    >
      <div class="header-content">
        <h1 class="dashboard-title">
          <span class="title-gradient">Welcome back,</span>
          <span class="title-name">{{ firstName }}</span>
        </h1>
        <p class="dashboard-subtitle">Here's what's happening with your account today</p>
      </div>
      <div class="header-actions">
        <v-btn
          color="white"
          variant="outlined"
          prepend-icon="mdi-bell"
          class="notification-btn"
        >
          <v-badge
            color="error"
            dot
            offset-x="-8"
            offset-y="-8"
          >
            Notifications
          </v-badge>
        </v-btn>
      </div>
    </div>

    <!-- Bento Grid Dashboard -->
    <BentoGrid gap="lg" class="dashboard-grid">
      <!-- Profile Card -->
      <div class="bento-item bento-item--medium bento-item--tall">
        <ProfileCard 
          :member="memberData"
          :member-points="memberPoints"
          :events-attended="12"
          :connections="48"
          @edit-profile="navigateTo('/member/profile')"
        />
      </div>

      <!-- Statistics Cards -->
      <div class="bento-item bento-item--small">
        <StatsCard
          label="Total Points"
          :value="memberPoints"
          icon="mdi-star"
          icon-color="warning"
          :icon-background="'linear-gradient(135deg, rgba(245, 158, 11, 0.1), rgba(245, 158, 11, 0.05))'"
          :change="12"
          suffix="pts"
          :delay="100"
          decoration-color="#f59e0b"
        />
      </div>

      <div class="bento-item bento-item--small">
        <StatsCard
          label="Events Attended"
          :value="upcomingEvents.length"
          icon="mdi-calendar-check"
          icon-color="success"
          :icon-background="'linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(34, 197, 94, 0.05))'"
          subtitle="This month"
          :delay="200"
          decoration-color="#22c55e"
        />
      </div>

      <div class="bento-item bento-item--small">
        <StatsCard
          label="Active Membership"
          :value="membershipDays"
          icon="mdi-crown"
          icon-color="error"
          :change="100"
          suffix="days"
          subtitle="Premium member"
          :delay="300"
        />
      </div>

      <!-- Upcoming Events Card -->
      <div class="bento-item bento-item--large">
        <EventsCard 
          :events="upcomingEvents"
          @view-all="navigateTo('/member/events')"
        />
      </div>

      <!-- Payment Status Card -->
      <div class="bento-item bento-item--medium">
        <PaymentCard
          :membership-type="membershipType"
          :next-payment-date="nextPaymentDate"
          :membership-amount="membershipAmount"
          :payment-history="paymentHistory"
          @update-payment="navigateTo('/member/payments')"
        />
      </div>

      <!-- Activity Timeline -->
      <div class="bento-item bento-item--medium bento-item--tall">
        <div class="glass-card activity-card">
          <div class="card-header">
            <v-icon color="error" size="20">mdi-history</v-icon>
            <h3 class="card-title">Recent Activity</h3>
          </div>
          <ActivityTimeline 
            :activities="formattedActivities"
            :max-items="5"
          />
          <v-btn
            variant="outlined"
            color="error"
            block
            class="mt-4"
            @click="navigateTo('/member/activity')"
          >
            View All Activity
          </v-btn>
        </div>
      </div>
    </BentoGrid>


    <!-- Quick Actions Section -->
    <div 
      v-motion
      :initial="{ opacity: 0, y: 20 }"
      :enter="{ 
        opacity: 1, 
        y: 0,
        transition: {
          delay: 800,
          duration: 600
        }
      }"
      class="quick-actions-section"
    >
      <h3 class="section-title">Quick Actions</h3>
      <div class="quick-actions-grid">
        <QuickActionCard
          v-for="(action, index) in quickActions"
          :key="action.title"
          :icon="action.icon"
          :title="action.title"
          :color="action.color"
          :delay="900 + (index * 100)"
          @click="navigateTo(action.route)"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Member } from '~/utils/types';
import BentoGrid from '~/components/dashboard/BentoGrid.vue';
import StatsCard from '~/components/dashboard/StatsCard.vue';
import ProfileCard from '~/components/dashboard/ProfileCard.vue';
import ActivityTimeline from '~/components/dashboard/ActivityTimeline.vue';
import EventsCard from '~/components/dashboard/EventsCard.vue';
import PaymentCard from '~/components/dashboard/PaymentCard.vue';
import QuickActionCard from '~/components/dashboard/QuickActionCard.vue';

definePageMeta({
  layout: 'member',
  middleware: 'member'
});

const { user } = useAuth();

// Fetch member data
const { data: sessionData } = await useFetch<{ success: boolean; member: Member | null }>('/api/auth/session', { 
  server: false
});

const memberData = computed<Member | null>(() => sessionData.value?.member || null);

// Computed properties
const firstName = computed(() => memberData.value?.first_name || user.value?.firstName || 'Member');
const fullName = computed(() => {
  if (memberData.value) {
    return `${memberData.value.first_name} ${memberData.value.last_name}`;
  }
  return user.value?.name || 'Member';
});
const email = computed(() => memberData.value?.email || user.value?.email || '');
const membershipType = computed(() => 'Premium');
const memberLevel = computed(() => 'Gold');
const memberSince = computed(() => {
  if (memberData.value?.join_date) {
    return new Date(memberData.value.join_date).toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
  }
  return 'January 2023';
});
const memberPoints = ref(2450);
const nextPaymentDate = ref('Feb 15, 2024');
const membershipAmount = ref('99.00');

// Calculate membership days
const membershipDays = computed(() => {
  if (memberData.value?.join_date) {
    const joinDate = new Date(memberData.value.join_date);
    const today = new Date();
    const diffTime = Math.abs(today.getTime() - joinDate.getTime());
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  }
  return 365;
});

// Mock data - replace with actual API calls
const upcomingEvents = ref([
  {
    id: "1",
    title: "Monthly Networking Event",
    date: "2024-01-15",
    time: "6:00 PM",
    location: "Conference Center",
    status: "confirmed"
  },
  {
    id: "2",
    title: "Workshop: Digital Marketing",
    date: "2024-01-22",
    time: "2:00 PM",
    location: "Training Room A",
    status: "pending"
  },
  {
    id: "3",
    title: "Annual Gala Dinner",
    date: "2024-02-05",
    time: "7:00 PM",
    location: "Grand Ballroom",
    status: "confirmed"
  }
]);

const paymentHistory = ref([
  { id: 1, date: 'Jan 15, 2024', amount: '99.00' },
  { id: 2, date: 'Dec 15, 2023', amount: '99.00' },
  { id: 3, date: 'Nov 15, 2023', amount: '99.00' }
]);

const recentActivity = ref([
  {
    id: "1",
    type: "event",
    description: "Attended Leadership Summit",
    timestamp: "2 days ago",
    icon: "mdi-account-group",
    color: "error"
  },
  {
    id: "2",
    type: "payment",
    description: "Membership renewal completed",
    timestamp: "1 week ago",
    icon: "mdi-credit-card",
    color: "success"
  },
  {
    id: "3",
    type: "achievement",
    description: "Earned Gold Level status",
    timestamp: "2 weeks ago",
    icon: "mdi-trophy",
    color: "warning"
  },
  {
    id: "4",
    type: "profile",
    description: "Updated profile information",
    timestamp: "3 weeks ago",
    icon: "mdi-account",
    color: "info"
  }
]);

// Format activities for the timeline component
const formattedActivities = computed(() => {
  return recentActivity.value.map(activity => ({
    ...activity,
    title: activity.description.split(' ').slice(0, 3).join(' '),
    description: activity.description
  }));
});

// Quick actions data
const quickActions = ref([
  {
    title: "View Events",
    icon: "mdi-calendar",
    color: "error",
    route: "/member/events"
  },
  {
    title: "Update Profile",
    icon: "mdi-account-edit",
    color: "primary",
    route: "/member/profile"
  },
  {
    title: "Payments",
    icon: "mdi-credit-card",
    color: "success",
    route: "/member/payments"
  },
  {
    title: "Resources",
    icon: "mdi-book-open-variant",
    color: "warning",
    route: "/member/resources"
  }
]);

// Helper functions
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('en-US', { 
    month: 'short', 
    day: 'numeric', 
    year: 'numeric' 
  });
};

// Load real data on mount
onMounted(async () => {
  // Load upcoming events
  try {
    const eventsRes = await $fetch('/api/member/events/upcoming');
    if (eventsRes?.success && eventsRes?.data) {
      // Map real events data
      console.log('Loaded upcoming events:', eventsRes.data);
    }
  } catch (error) {
    console.error('Error loading events:', error);
  }

  // Load payment information
  try {
    const paymentsRes = await $fetch('/api/member/payments/status');
    if (paymentsRes?.success && paymentsRes?.data) {
      // Update payment data
      console.log('Loaded payment status:', paymentsRes.data);
    }
  } catch (error) {
    console.error('Error loading payment status:', error);
  }
});
</script>

<style scoped lang="scss">
.member-dashboard {
  padding: 2rem;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f5f5 0%, #fafafa 100%);
  
  @media (max-width: 768px) {
    padding: 1rem;
  }
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2.5rem;
  padding: 2rem;
  background: linear-gradient(135deg, 
    rgba(255, 255, 255, 0.95),
    rgba(255, 255, 255, 0.85)
  );
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 1.25rem;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 
    0 20px 40px rgba(0, 0, 0, 0.08),
    inset 0 1px 0 rgba(255, 255, 255, 0.6);
  
  @media (max-width: 768px) {
    flex-direction: column;
    gap: 1.5rem;
    padding: 1.5rem;
  }
}

.header-content {
  flex: 1;
}

.dashboard-title {
  font-size: 2.5rem;
  font-weight: 800;
  margin: 0 0 0.5rem 0;
  line-height: 1.2;
  
  @media (max-width: 768px) {
    font-size: 2rem;
  }
}

.title-gradient {
  background: linear-gradient(135deg, #dc2626, #b91c1c);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.title-name {
  color: rgb(31, 41, 55);
}

.dashboard-subtitle {
  font-size: 1.125rem;
  color: rgb(107, 114, 128);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 1rem;
}

.notification-btn {
  text-transform: none;
  font-weight: 500;
}

.dashboard-grid {
  margin-bottom: 3rem;
}

// Glass card base styles
.glass-card {
  background: linear-gradient(135deg, 
    rgba(255, 255, 255, 0.9),
    rgba(255, 255, 255, 0.7)
  );
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 1rem;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.08),
    inset 0 1px 0 rgba(255, 255, 255, 0.5);
  padding: 1.5rem;
  height: 100%;
}

.activity-card {
  .card-header {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 1.25rem;
  }
  
  .card-title {
    font-size: 1.125rem;
    font-weight: 600;
    color: rgb(31, 41, 55);
    margin: 0;
  }
}

.quick-actions-section {
  margin-top: 2rem;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: rgb(31, 41, 55);
  margin-bottom: 1.5rem;
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.25rem;
  
  @media (max-width: 640px) {
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
  }
}
</style>
