<template>
  <AppLayout :breadcrumbs="breadcrumbs">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-semibold text-gray-900 dark:text-gray-100">Guardian Dashboard</h1>
          <p class="text-sm text-gray-600 dark:text-gray-400">
            Welcome back, {{ guardian?.user?.name || 'Guardian' }}
          </p>
        </div>
        <div class="text-sm text-gray-500 dark:text-gray-400">
          Academic Year: {{ currentAcademicYear?.name || 'No active academic year' }}
        </div>
      </div>

      <!-- Error State -->
      <div v-if="error" class="bg-red-50 border border-red-200 rounded-md p-4">
        <div class="flex">
          <div class="ml-3">
            <h3 class="text-sm font-medium text-red-800">Error</h3>
            <div class="mt-2 text-sm text-red-700">
              {{ error }}
            </div>
          </div>
        </div>
      </div>

      <!-- Overall Statistics -->
      <div v-if="!error" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div class="bg-white dark:bg-gray-800 overflow-hidden shadow rounded-lg">
          <div class="p-5">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <div class="w-8 h-8 bg-blue-500 rounded-md flex items-center justify-center">
                  <span class="text-white text-sm font-medium">👨‍👩‍👧‍👦</span>
                </div>
              </div>
              <div class="ml-5 w-0 flex-1">
                <dl>
                  <dt class="text-sm font-medium text-gray-500 dark:text-gray-400 truncate">Total Children</dt>
                  <dd class="text-lg font-medium text-gray-900 dark:text-gray-100">{{ overallStats?.total_children || 0 }}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>

        <div class="bg-white dark:bg-gray-800 overflow-hidden shadow rounded-lg">
          <div class="p-5">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <div class="w-8 h-8 bg-green-500 rounded-md flex items-center justify-center">
                  <span class="text-white text-sm font-medium">🎓</span>
                </div>
              </div>
              <div class="ml-5 w-0 flex-1">
                <dl>
                  <dt class="text-sm font-medium text-gray-500 dark:text-gray-400 truncate">Enrolled Children</dt>
                  <dd class="text-lg font-medium text-gray-900 dark:text-gray-100">{{ overallStats?.enrolled_children || 0 }}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>

        <div class="bg-white dark:bg-gray-800 overflow-hidden shadow rounded-lg">
          <div class="p-5">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <div class="w-8 h-8 bg-yellow-500 rounded-md flex items-center justify-center">
                  <span class="text-white text-sm font-medium">📊</span>
                </div>
              </div>
              <div class="ml-5 w-0 flex-1">
                <dl>
                  <dt class="text-sm font-medium text-gray-500 dark:text-gray-400 truncate">Average Performance</dt>
                  <dd class="text-lg font-medium text-gray-900 dark:text-gray-100">{{ averagePerformance }}%</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>

        <div class="bg-white dark:bg-gray-800 overflow-hidden shadow rounded-lg">
          <div class="p-5">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <div class="w-8 h-8 bg-purple-500 rounded-md flex items-center justify-center">
                  <span class="text-white text-sm font-medium">📚</span>
                </div>
              </div>
              <div class="ml-5 w-0 flex-1">
                <dl>
                  <dt class="text-sm font-medium text-gray-500 dark:text-gray-400 truncate">Active Classrooms</dt>
                  <dd class="text-lg font-medium text-gray-900 dark:text-gray-100">{{ activeClassrooms }}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Children Performance -->
      <div v-if="!error && students && students.length > 0" class="bg-white dark:bg-gray-800 shadow rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">Children's Performance</h3>
        </div>
        <div class="p-6">
          <div class="space-y-6">
            <div v-for="studentData in students" :key="studentData.student.id" class="border border-gray-200 dark:border-gray-600 rounded-lg p-4">
              <!-- Student Header -->
              <div class="flex items-center justify-between mb-4">
                <div class="flex items-center">
                  <div class="w-10 h-10 bg-gray-300 rounded-full flex items-center justify-center">
                    <span class="text-sm font-medium text-gray-700">
                      {{ getInitials(studentData.student.user?.name) }}
                    </span>
                  </div>
                  <div class="ml-3">
                    <h4 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                      {{ studentData.student.user?.name || 'Unknown Student' }}
                    </h4>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                      {{ studentData.enrollment?.classroom?.name || 'Not enrolled' }}
                    </p>
                  </div>
                </div>
                <div v-if="studentData.summary" class="text-right">
                  <div class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                    {{ studentData.summary.average_marks || 0 }}%
                  </div>
                  <div class="text-sm text-gray-500 dark:text-gray-400">
                    {{ studentData.summary.division || 'No division' }}
                  </div>
                </div>
              </div>

              <!-- Performance Summary -->
              <div v-if="studentData.summary" class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
                <div class="text-center">
                  <div class="text-2xl font-bold text-blue-600 dark:text-blue-400">
                    {{ studentData.summary.total_marks || 0 }}
                  </div>
                  <div class="text-xs text-gray-500 dark:text-gray-400">Total Marks</div>
                </div>
                <div class="text-center">
                  <div class="text-2xl font-bold text-green-600 dark:text-green-400">
                    {{ studentData.summary.average_marks || 0 }}%
                  </div>
                  <div class="text-xs text-gray-500 dark:text-gray-400">Average</div>
                </div>
                <div class="text-center">
                  <div class="text-2xl font-bold text-purple-600 dark:text-purple-400">
                    {{ studentData.summary.rank || 'N/A' }}
                  </div>
                  <div class="text-xs text-gray-500 dark:text-gray-400">Class Rank</div>
                </div>
                <div class="text-center">
                  <div class="text-2xl font-bold text-orange-600 dark:text-orange-400">
                    {{ studentData.summary.division || 'N/A' }}
                  </div>
                  <div class="text-xs text-gray-500 dark:text-gray-400">Division</div>
                </div>
              </div>

              <!-- Recent Results -->
              <div v-if="studentData.recent_results && studentData.recent_results.length > 0">
                <h5 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-2">Recent Results</h5>
                <div class="overflow-x-auto">
                  <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                    <thead class="bg-gray-50 dark:bg-gray-700">
                      <tr>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Subject</th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Exam</th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Marks</th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Grade</th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Date</th>
                      </tr>
                    </thead>
                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-600">
                      <tr v-for="result in studentData.recent_results" :key="result.id">
                        <td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                          {{ result.subject?.name || 'N/A' }}
                        </td>
                        <td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                          {{ result.exam_type?.name || 'N/A' }}
                        </td>
                        <td class="px-3 py-2 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">
                          {{ result.marks }}
                        </td>
                        <td class="px-3 py-2 whitespace-nowrap">
                          <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100">
                            {{ result.grade }}
                          </span>
                        </td>
                        <td class="px-3 py-2 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                          {{ formatDate(result.entered_at) }}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              <!-- No Results Message -->
              <div v-else class="text-center py-4">
                <p class="text-sm text-gray-500 dark:text-gray-400">No recent results available</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- No Children Message -->
      <div v-else-if="!error && (!students || students.length === 0)" class="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
        <div class="text-center">
          <div class="w-12 h-12 mx-auto bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center">
            <span class="text-2xl">👨‍👩‍👧‍👦</span>
          </div>
          <h3 class="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">No Children Found</h3>
          <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            You don't have any children associated with your account yet.
          </p>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import AppLayout from '@/layouts/AppLayout.vue'

// Props from controller
const props = defineProps({
  guardian: Object,
  students: Array,
  overallStats: Object,
  currentAcademicYear: Object,
  error: String,
})

// Breadcrumbs
const breadcrumbs = [
  { name: 'Dashboard', href: route('dashboard'), current: true },
]

// Computed properties
const averagePerformance = computed(() => {
  if (!props.students || props.students.length === 0) return 0
  
  const totalMarks = props.students.reduce((sum, studentData) => {
    return sum + (studentData.summary?.average_marks || 0)
  }, 0)
  
  return Math.round(totalMarks / props.students.length)
})

const activeClassrooms = computed(() => {
  if (!props.students || props.students.length === 0) return 0
  
  const classrooms = new Set()
  props.students.forEach(studentData => {
    if (studentData.enrollment?.classroom?.id) {
      classrooms.add(studentData.enrollment.classroom.id)
    }
  })
  
  return classrooms.size
})

// Methods
const getInitials = (name: string) => {
  if (!name) return '?'
  return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)
}

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