<template>
  <div>
    <!-- Header -->
    <div class="d-flex justify-space-between align-center mb-6">
      <div>
        <h1 class="text-h4 font-weight-bold">Member Dashboard</h1>
        <p class="text-body-1 text-medium-emphasis">Welcome back, {{ firstName }}</p>
      </div>
      <v-btn
        color="error"
        variant="flat"
        prepend-icon="mdi-account-edit"
        @click="navigateTo('/member/profile')"
      >
        Edit Profile
      </v-btn>
    </div>

    <!-- Profile Info Card -->
    <v-card class="mb-6" elevation="2">
      <v-card-title class="d-flex align-center">
        <v-icon color="error" class="mr-2">mdi-account</v-icon>
        Profile Information
      </v-card-title>
      <v-card-text>
        <v-row>
          <v-col cols="auto">
            <ProfileAvatar
              :member-id="memberData?.member_id"
              :first-name="memberData?.first_name"
              :last-name="memberData?.last_name"
              size="large"
              :show-badge="false"
            />
          </v-col>
          <v-col>
            <div class="d-flex justify-space-between align-start mb-3">
              <div>
                <h3 class="text-h6 font-weight-bold">{{ fullName }}</h3>
                <p class="text-body-2 text-medium-emphasis">{{ email }}</p>
              </div>
              <div class="d-flex gap-2">
                <v-chip
                  color="error"
                  variant="tonal"
                  size="small"
                >
                  {{ membershipType }}
                </v-chip>
                <v-chip
                  variant="outlined"
                  color="error"
                  size="small"
                  prepend-icon="mdi-star"
                >
                  {{ memberLevel }}
                </v-chip>
              </div>
            </div>
            
            <v-row class="mt-4">
              <v-col cols="12" md="4">
                <div class="text-caption text-medium-emphasis">Member Since</div>
                <div class="font-weight-medium">{{ memberSince }}</div>
              </v-col>
              <v-col cols="12" md="4">
                <div class="text-caption text-medium-emphasis">Points</div>
                <div class="font-weight-medium">{{ memberPoints.toLocaleString() }}</div>
              </v-col>
              <v-col cols="12" md="4">
                <div class="text-caption text-medium-emphasis">Status</div>
                <div class="font-weight-medium text-success">Active</div>
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </v-card-text>
    </v-card>

    <v-row>
      <!-- Upcoming Events -->
      <v-col cols="12" lg="6">
        <v-card elevation="2" class="h-100">
          <v-card-title class="d-flex align-center">
            <v-icon color="error" class="mr-2">mdi-calendar</v-icon>
            Upcoming Events
          </v-card-title>
          <v-card-subtitle>Your registered events and activities</v-card-subtitle>
          <v-card-text>
            <v-list lines="three" class="pa-0">
              <template v-for="(event, index) in upcomingEvents" :key="event.id">
                <v-list-item class="px-0">
                  <v-card variant="outlined" class="w-100">
                    <v-card-text>
                      <div class="d-flex justify-space-between align-start mb-2">
                        <h4 class="text-body-1 font-weight-medium">{{ event.title }}</h4>
                        <v-chip
                          :color="event.status === 'confirmed' ? 'success' : 'warning'"
                          size="x-small"
                          variant="tonal"
                        >
                          <v-icon start size="x-small">
                            {{ event.status === 'confirmed' ? 'mdi-check-circle' : 'mdi-alert-circle' }}
                          </v-icon>
                          {{ event.status }}
                        </v-chip>
                      </div>
                      <div class="d-flex flex-wrap gap-3 text-caption text-medium-emphasis">
                        <div class="d-flex align-center">
                          <v-icon size="x-small" class="mr-1">mdi-calendar</v-icon>
                          {{ formatDate(event.date) }}
                        </div>
                        <div class="d-flex align-center">
                          <v-icon size="x-small" class="mr-1">mdi-clock-outline</v-icon>
                          {{ event.time }}
                        </div>
                        <div class="d-flex align-center">
                          <v-icon size="x-small" class="mr-1">mdi-map-marker</v-icon>
                          {{ event.location }}
                        </div>
                      </div>
                    </v-card-text>
                  </v-card>
                </v-list-item>
              </template>
            </v-list>
            
            <v-btn
              variant="outlined"
              color="error"
              block
              class="mt-4"
              @click="navigateTo('/member/events')"
            >
              View All Events
            </v-btn>
          </v-card-text>
        </v-card>
      </v-col>

      <!-- Payment Status -->
      <v-col cols="12" lg="6">
        <v-card elevation="2" class="h-100">
          <v-card-title class="d-flex align-center">
            <v-icon color="error" class="mr-2">mdi-credit-card</v-icon>
            Payment Status
          </v-card-title>
          <v-card-subtitle>Membership and payment information</v-card-subtitle>
          <v-card-text>
            <!-- Current Membership -->
            <v-card variant="outlined" class="mb-4">
              <v-card-text>
                <div class="d-flex justify-space-between align-center mb-3">
                  <h4 class="text-body-1 font-weight-medium">Current Membership</h4>
                  <v-chip
                    color="success"
                    size="x-small"
                    variant="tonal"
                  >
                    <v-icon start size="x-small">mdi-check-circle</v-icon>
                    Active
                  </v-chip>
                </div>
                <div class="text-body-2">
                  <div class="d-flex justify-space-between py-1">
                    <span class="text-medium-emphasis">Plan:</span>
                    <span class="font-weight-medium">{{ membershipType }}</span>
                  </div>
                  <div class="d-flex justify-space-between py-1">
                    <span class="text-medium-emphasis">Next Payment:</span>
                    <span class="font-weight-medium">{{ nextPaymentDate }}</span>
                  </div>
                  <div class="d-flex justify-space-between py-1">
                    <span class="text-medium-emphasis">Amount:</span>
                    <span class="font-weight-medium">${{ membershipAmount }}</span>
                  </div>
                </div>
              </v-card-text>
            </v-card>

            <!-- Payment History -->
            <v-card variant="outlined" class="mb-4">
              <v-card-text>
                <h4 class="text-body-1 font-weight-medium mb-3">Payment History</h4>
                <div class="text-body-2">
                  <div 
                    v-for="payment in paymentHistory" 
                    :key="payment.id"
                    class="d-flex justify-space-between align-center py-1"
                  >
                    <span class="text-medium-emphasis">{{ payment.date }}</span>
                    <div class="d-flex align-center gap-2">
                      <span class="font-weight-medium">${{ payment.amount }}</span>
                      <v-chip
                        color="success"
                        size="x-small"
                        variant="outlined"
                      >
                        Paid
                      </v-chip>
                    </div>
                  </div>
                </div>
              </v-card-text>
            </v-card>

            <v-btn
              color="error"
              variant="flat"
              block
              prepend-icon="mdi-credit-card"
              @click="navigateTo('/member/payments')"
            >
              Update Payment Method
            </v-btn>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- Recent Activity -->
    <v-card elevation="2" class="mt-6">
      <v-card-title class="d-flex align-center">
        <v-icon color="error" class="mr-2">mdi-history</v-icon>
        Recent Activity
      </v-card-title>
      <v-card-subtitle>Your latest actions and updates</v-card-subtitle>
      <v-card-text>
        <v-timeline side="end" density="compact">
          <v-timeline-item
            v-for="activity in recentActivity"
            :key="activity.id"
            :dot-color="activity.color"
            size="small"
          >
            <template v-slot:icon>
              <v-icon size="x-small">{{ activity.icon }}</v-icon>
            </template>
            <div>
              <div class="text-body-2 font-weight-medium">{{ activity.description }}</div>
              <div class="text-caption text-medium-emphasis">{{ activity.timestamp }}</div>
            </div>
          </v-timeline-item>
        </v-timeline>
        
        <v-btn
          variant="outlined"
          color="error"
          block
          class="mt-4"
          @click="navigateTo('/member/activity')"
        >
          View All Activity
        </v-btn>
      </v-card-text>
    </v-card>

    <!-- Quick Actions -->
    <v-row class="mt-6">
      <v-col cols="12">
        <h3 class="text-h6 mb-3">Quick Actions</h3>
      </v-col>
      <v-col cols="6" sm="3">
        <v-card 
          elevation="1" 
          class="text-center pa-4 cursor-pointer"
          hover
          @click="navigateTo('/member/events')"
        >
          <v-icon size="32" color="error" class="mb-2">mdi-calendar-plus</v-icon>
          <div class="text-body-2">Register for Event</div>
        </v-card>
      </v-col>
      <v-col cols="6" sm="3">
        <v-card 
          elevation="1" 
          class="text-center pa-4 cursor-pointer"
          hover
          @click="navigateTo('/member/directory')"
        >
          <v-icon size="32" color="error" class="mb-2">mdi-account-group</v-icon>
          <div class="text-body-2">Member Directory</div>
        </v-card>
      </v-col>
      <v-col cols="6" sm="3">
        <v-card 
          elevation="1" 
          class="text-center pa-4 cursor-pointer"
          hover
          @click="navigateTo('/member/resources')"
        >
          <v-icon size="32" color="error" class="mb-2">mdi-book-open-variant</v-icon>
          <div class="text-body-2">Resources</div>
        </v-card>
      </v-col>
      <v-col cols="6" sm="3">
        <v-card 
          elevation="1" 
          class="text-center pa-4 cursor-pointer"
          hover
          @click="navigateTo('/member/support')"
        >
          <v-icon size="32" color="error" class="mb-2">mdi-help-circle</v-icon>
          <div class="text-body-2">Get Support</div>
        </v-card>
      </v-col>
    </v-row>
  </div>
</template>

<script setup lang="ts">
import type { Member } from '~/utils/types';

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');

// 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"
  }
]);

// 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>
.cursor-pointer {
  cursor: pointer;
}

.gap-2 {
  gap: 0.5rem;
}

.gap-3 {
  gap: 0.75rem;
}

.h-100 {
  height: 100%;
}

.w-100 {
  width: 100%;
}
</style>
