<template>
  <div class="space-y-6">
    <!-- Header Banner -->
    <div class="glass-panel rounded-3xl p-6 border border-slate-700/50 bg-gradient-to-r from-slate-900 via-slate-900/90 to-amber-950/30 flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
      <div>
        <div class="flex items-center space-x-2 text-xs font-semibold text-amber-400 uppercase tracking-wider mb-1">
          <Calendar class="w-4 h-4" />
          <span>Week {{ currentWeekDisplay }} Overview</span>
        </div>
        <h1 class="text-2xl md:text-3xl font-extrabold text-slate-100">
          Welcome back, <span class="bg-gradient-to-r from-amber-400 to-emerald-400 bg-clip-text text-transparent">{{ authStore.user?.name }}</span>! ✨
        </h1>
        <p class="text-slate-400 text-sm mt-1">Here is how your family is progressing on household chores this week.</p>
      </div>

      <router-link
        to="/chores"
        class="bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-400 hover:to-amber-500 text-slate-950 font-bold px-5 py-3 rounded-2xl flex items-center space-x-2 shadow-lg shadow-amber-500/25 transition-all duration-200"
      >
        <PlusCircle class="w-5 h-5" />
        <span>Complete a Chore</span>
      </router-link>
    </div>

    <!-- Quick Stats Cards Grid -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
      <!-- My Weekly Quota Progress -->
      <div class="glass-card rounded-2xl p-5 border border-slate-700/50">
        <div class="flex justify-between items-start mb-3">
          <div>
            <span class="text-xs font-semibold text-slate-400 uppercase">My Weekly Progress</span>
            <h2 class="text-2xl font-black text-amber-400 mt-1">
              {{ myProgress?.stars_earned || 0 }} <span class="text-sm font-medium text-slate-400">/ {{ authStore.user?.weekly_star_quota }} Stars</span>
            </h2>
          </div>
          <div class="p-3 rounded-xl bg-amber-500/10 text-amber-400 border border-amber-500/20">
            <Star class="w-6 h-6 fill-amber-400" />
          </div>
        </div>
        <div class="w-full bg-slate-800 rounded-full h-3 mb-2 overflow-hidden">
          <div
            class="bg-gradient-to-r from-amber-500 to-emerald-400 h-3 rounded-full transition-all duration-500"
            :style="{ width: `${myProgressPercentage}%` }"
          ></div>
        </div>
        <p class="text-xs text-slate-400 flex justify-between">
          <span>{{ myProgressPercentage }}% quota completed</span>
          <span class="text-amber-400 font-semibold">{{ myStarsRemaining }} stars remaining</span>
        </p>
      </div>

      <!-- Family Total Stars -->
      <div class="glass-card rounded-2xl p-5 border border-slate-700/50">
        <div class="flex justify-between items-start mb-3">
          <div>
            <span class="text-xs font-semibold text-slate-400 uppercase">Family Team Score</span>
            <h2 class="text-2xl font-black text-emerald-400 mt-1">
              {{ choresStore.weeklyReport?.total_stars_earned || 0 }} <span class="text-sm font-medium text-slate-400">Stars</span>
            </h2>
          </div>
          <div class="p-3 rounded-xl bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
            <Trophy class="w-6 h-6" />
          </div>
        </div>
        <p class="text-xs text-slate-400 mt-4">
          Total of <span class="text-slate-200 font-bold">{{ choresStore.weeklyReport?.total_completions || 0 }}</span> chores completed by family members this week!
        </p>
      </div>

      <!-- Weekly Leader -->
      <div class="glass-card rounded-2xl p-5 border border-slate-700/50 sm:col-span-2 lg:col-span-1">
        <div class="flex justify-between items-start mb-3">
          <div>
            <span class="text-xs font-semibold text-slate-400 uppercase">Weekly Chore Champ</span>
            <h2 class="text-xl font-bold text-slate-100 mt-1 flex items-center space-x-2">
              <span>{{ topPerformer?.name || 'No Activity Yet' }}</span>
              <span v-if="topPerformer" class="text-xs px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-300 font-medium">1st Place 🏆</span>
            </h2>
          </div>
          <div class="w-10 h-10 rounded-full border border-amber-400/40 overflow-hidden bg-slate-800">
            <img :src="topPerformer?.avatar_url || defaultAvatar" class="w-full h-full object-cover" />
          </div>
        </div>
        <p class="text-xs text-slate-400 mt-4">
          Leading with <span class="text-amber-400 font-bold">{{ topPerformer?.stars_earned || 0 }} stars</span> logged!
        </p>
      </div>
    </div>

    <!-- Family Member Completion Progress Bars -->
    <div class="glass-panel rounded-3xl p-6 border border-slate-700/50">
      <div class="flex items-center justify-between mb-6">
        <div>
          <h2 class="text-lg font-bold text-slate-100 flex items-center space-x-2">
            <Users class="w-5 h-5 text-amber-400" />
            <span>Family Progress Dashboard</span>
          </h2>
          <p class="text-xs text-slate-400">Chore completion status for each family member</p>
        </div>
        <router-link to="/reports" class="text-xs font-semibold text-amber-400 hover:underline">
          View Detailed Reports &rarr;
        </router-link>
      </div>

      <div class="space-y-4">
        <div
          v-for="u in choresStore.weeklyReport?.user_progress || []"
          :key="u.user_id"
          class="glass-card rounded-2xl p-4 border border-slate-700/40 hover:border-slate-600 transition-all"
        >
          <div class="flex items-center justify-between mb-2">
            <div class="flex items-center space-x-3">
              <img :src="u.avatar_url || defaultAvatar" class="w-10 h-10 rounded-full bg-slate-800 border border-slate-600 object-cover" />
              <div>
                <div class="flex items-center space-x-2">
                  <span class="font-bold text-sm text-slate-100">{{ u.name }}</span>
                  <span v-if="u.user_id === authStore.user?.id" class="text-[10px] bg-amber-500/20 text-amber-300 font-medium px-2 py-0.5 rounded-full">You</span>
                  <span v-if="u.role === 'admin'" class="text-[10px] bg-emerald-500/20 text-emerald-300 font-medium px-2 py-0.5 rounded-full">Admin</span>
                </div>
                <span class="text-xs text-slate-400">{{ u.completions_count }} chores logged</span>
              </div>
            </div>
            <div class="text-right">
              <div class="text-sm font-extrabold text-amber-400 flex items-center justify-end space-x-1">
                <span>{{ u.stars_earned }} / {{ u.weekly_star_quota }}</span>
                <Star class="w-4 h-4 fill-amber-400 text-amber-400" />
              </div>
              <span class="text-xs text-slate-400">{{ u.percentage }}%</span>
            </div>
          </div>

          <!-- Progress Bar -->
          <div class="w-full bg-slate-800 rounded-full h-2.5 overflow-hidden">
            <div
              class="h-2.5 rounded-full transition-all duration-500"
              :class="u.percentage >= 100 ? 'bg-gradient-to-r from-emerald-500 to-teal-400' : 'bg-gradient-to-r from-amber-500 to-amber-400'"
              :style="{ width: `${Math.min(100, u.percentage)}%` }"
            ></div>
          </div>
        </div>
      </div>
    </div>

    <!-- Recent Completed Chores Stream -->
    <div class="glass-panel rounded-3xl p-6 border border-slate-700/50">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-lg font-bold text-slate-100 flex items-center space-x-2">
          <Sparkles class="w-5 h-5 text-emerald-400" />
          <span>Recent Family Activity</span>
        </h2>
        <span class="text-xs text-slate-400">Live Activity Feed</span>
      </div>

      <div v-if="choresStore.recentCompletions.length === 0" class="text-center py-8 text-slate-400 text-sm">
        No chores logged yet this week. Be the first to earn stars!
      </div>

      <div class="space-y-3">
        <div
          v-for="c in choresStore.recentCompletions.slice(0, 5)"
          :key="c.id"
          class="glass-card rounded-xl p-3 flex items-center justify-between border border-slate-800"
        >
          <div class="flex items-center space-x-3">
            <div class="w-10 h-10 rounded-xl bg-amber-500/10 border border-amber-500/20 flex items-center justify-center text-amber-400">
              <ChoreIcon :name="c.chore_icon" class="w-5 h-5" />
            </div>
            <div>
              <p class="text-sm font-semibold text-slate-200">{{ c.chore_title }}</p>
              <p class="text-xs text-slate-400">Completed by <span class="text-slate-300 font-medium">{{ c.user_name }}</span> &bull; {{ formatDate(c.completed_at) }}</p>
              <p v-if="c.notes" class="text-xs text-slate-400 italic mt-0.5">"{{ c.notes }}"</p>
            </div>
          </div>
          <div class="flex items-center space-x-1 bg-amber-500/15 border border-amber-500/30 text-amber-300 text-xs font-bold px-2.5 py-1 rounded-full">
            <span>+{{ c.stars_earned }}</span>
            <Star class="w-3.5 h-3.5 fill-amber-300" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, computed } from 'vue';
import { useAuthStore } from '../stores/auth';
import { useChoresStore } from '../stores/chores';
import ChoreIcon from '../components/ChoreIcon.vue';
import {
  Calendar,
  PlusCircle,
  Star,
  Trophy,
  Users,
  Sparkles
} from '@lucide/vue';

const authStore = useAuthStore();
const choresStore = useChoresStore();
const defaultAvatar = 'https://api.dicebear.com/7.x/bottts/svg?seed=DefaultUser';

onMounted(async () => {
  await choresStore.fetchWeeklyReport();
  await choresStore.fetchRecentCompletions();
});

const currentWeekDisplay = computed(() => {
  return choresStore.weeklyReport?.week_identifier || '';
});

const myProgress = computed(() => {
  return choresStore.weeklyReport?.user_progress.find(u => u.user_id === authStore.user?.id);
});

const myProgressPercentage = computed(() => {
  if (!myProgress.value) return 0;
  return myProgress.value.percentage;
});

const myStarsRemaining = computed(() => {
  const quota = authStore.user?.weekly_star_quota || 15;
  const earned = myProgress.value?.stars_earned || 0;
  return Math.max(0, quota - earned);
});

const topPerformer = computed(() => {
  if (!choresStore.weeklyReport?.user_progress?.length) return null;
  return choresStore.weeklyReport.user_progress[0];
});

function formatDate(isoStr) {
  if (!isoStr) return '';
  const d = new Date(isoStr);
  return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + ', ' + d.toLocaleDateString([], { month: 'short', day: 'numeric' });
}
</script>
