<template>
  <div>
    <!-- Header -->
    <div class="mb-8">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">
            สวัสดี, {{ authStore.user?.firstName }} {{ authStore.user?.lastName || 'อาจารย์' }} 
          </h1>
          <p class="text-gray-600 mt-2">ยินดีต้อนรับกลับสู่ระบบ</p>
        </div>
        <div class="flex items-center gap-4">
          <div class="text-right">
            <div class="text-sm font-semibold text-gray-900">{{ authStore.user?.firstName }} {{ authStore.user?.lastName || 'อาจารย์ทดสอบ' }}</div>
            <div class="text-xs text-gray-500">{{ authStore.user?.role || 'INSTRUCTOR' }}</div>
          </div>
          <div 
            class="w-12 h-12 bg-primary-100 rounded-full flex items-center justify-center text-2xl cursor-pointer hover:bg-primary-200 transition overflow-hidden"
          >
            <img
              v-if="authStore.user?.avatarUrl"
              :src="authStore.user.avatarUrl"
              alt=""
              class="w-full h-full object-cover"
            />
            <q-icon v-else name="person" />
            <q-menu>
              <q-list style="min-width: 200px">
                <!-- User Info Header -->
                <q-item class="bg-primary-50">
                  <q-item-section>
                    <q-item-label class="text-weight-bold">{{ authStore.user?.firstName }} {{ authStore.user?.lastName }}</q-item-label>
                    <q-item-label caption>{{ authStore.user?.email }}</q-item-label>
                  </q-item-section>
                </q-item>

                <q-separator />

                <!-- Profile -->
                <q-item clickable v-close-popup @click="goToProfile">
                  <q-item-section avatar>
                    <q-icon name="person" />
                  </q-item-section>
                  <q-item-section>โปรไฟล์</q-item-section>
                </q-item>

                <q-separator />

                <!-- Logout -->
                <q-item clickable v-close-popup @click="handleLogout">
                  <q-item-section avatar>
                    <q-icon name="logout" color="negative" />
                  </q-item-section>
                  <q-item-section class="text-negative">ออกจากระบบ</q-item-section>
                </q-item>
              </q-list>
            </q-menu>
          </div>
        </div>
      </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
      <q-card class="p-6 text-center">
        <div class="text-4xl font-bold text-primary-600 mb-2">
          {{ stats.totalCourses }}
        </div>
        <div class="text-gray-600">หลักสูตรทั้งหมด</div>
      </q-card>

      <q-card class="p-6 text-center">
        <div class="text-4xl font-bold text-secondary-600 mb-2">
          {{ stats.totalStudents }}
        </div>
        <div class="text-gray-600">ผู้เรียนทั้งหมด</div>
      </q-card>

      <q-card class="p-6 text-center">
        <div class="text-4xl font-bold text-accent-600 mb-2">
          {{ stats.completedStudents }}
        </div>
        <div class="text-gray-600">เรียนจบแล้ว</div>
      </q-card>
    </div>

    <!-- Chart and Recent Courses -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
      <!-- Course Status Breakdown -->
      <q-card>
        <q-card-section>
          <h3 class="text-xl font-semibold mb-4">สถานะหลักสูตร</h3>
          <div class="space-y-3">
            <div class="flex items-center justify-between p-3 bg-green-50 rounded-lg">
              <div class="flex items-center gap-3">
                <q-icon name="check_circle" color="green" size="24px" />
                <span class="font-medium text-gray-700">เผยแพร่แล้ว</span>
              </div>
              <span class="text-2xl font-bold text-green-600">{{ courseStatusCounts.approved }}</span>
            </div>
            <div class="flex items-center justify-between p-3 bg-orange-50 rounded-lg">
              <div class="flex items-center gap-3">
                <q-icon name="hourglass_empty" color="orange" size="24px" />
                <span class="font-medium text-gray-700">รอตรวจสอบ</span>
              </div>
              <span class="text-2xl font-bold text-orange-600">{{ courseStatusCounts.pending }}</span>
            </div>
            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
              <div class="flex items-center gap-3">
                <q-icon name="edit_note" color="grey" size="24px" />
                <span class="font-medium text-gray-700">แบบร่าง</span>
              </div>
              <span class="text-2xl font-bold text-gray-600">{{ courseStatusCounts.draft }}</span>
            </div>
            <div v-if="courseStatusCounts.rejected > 0" class="flex items-center justify-between p-3 bg-red-50 rounded-lg">
              <div class="flex items-center gap-3">
                <q-icon name="cancel" color="red" size="24px" />
                <span class="font-medium text-gray-700">ถูกปฏิเสธ</span>
              </div>
              <span class="text-2xl font-bold text-red-600">{{ courseStatusCounts.rejected }}</span>
            </div>
          </div>
        </q-card-section>
      </q-card>

      <!-- Recent Courses -->
      <q-card>
        <q-card-section>
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-semibold"> หลักสูตร</h3>
            <q-btn
              flat
              color="primary"
              label="ดูทั้งหมด"
              @click="router.push('/instructor/courses')"
            />
          </div>

          <div class="space-y-4">
            <q-card
              v-for="course in recentCourses"
              :key="course.id"
              class="cursor-pointer hover:shadow-md transition"
              @click="router.push(`/instructor/courses/${course.id}`)"
            >
              <q-card-section>
                <div class="flex gap-4">
                  <div class="w-20 h-16 bg-primary-100 rounded-lg flex items-center justify-center overflow-hidden flex-shrink-0">
                    <img 
                      v-if="course.thumbnail" 
                      :src="course.thumbnail" 
                      :alt="course.title"
                      class="w-full h-full object-cover"
                    />
                    <q-icon v-else :name="course.icon" class="text-3xl" />
                  </div>
                  <div class="flex-1">
                    <div class="font-semibold text-gray-900">{{ course.title }}</div>
                    <div class="text-sm text-gray-600 mt-1">
                      {{ course.students }} ผู้เรียน • {{ course.lessons }} บทเรียน
                    </div>
                  </div>
                </div>
              </q-card-section>
            </q-card>
          </div>
        </q-card-section>
      </q-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import { instructorService } from '~/services/instructor.service';

definePageMeta({
  layout: 'instructor',
  middleware: 'auth'
});

const authStore = useAuthStore();
const router = useRouter();
const $q = useQuasar();

// Dashboard local state
const stats = ref({
  totalCourses: 0,
  totalStudents: 0,
  completedStudents: 0
});

const courseStatusCounts = ref({
  approved: 0,
  pending: 0,
  draft: 0,
  rejected: 0
});

const recentCourses = ref<{
  id: number;
  title: string;
  students: number;
  lessons: number;
  icon: string;
  thumbnail: string | null;
}[]>([]);

// Navigation functions
const goToProfile = () => {
  router.push('/instructor/profile');
};

const goToSettings = () => {
  router.push('/instructor/settings');
};

const handleLogout = () => {
  $q.dialog({
    title: 'ยืนยันการออกจากระบบ',
    message: 'คุณต้องการออกจากระบบใช่หรือไม่?',
    cancel: {
      label: 'ยกเลิก',
      flat: true,
      color: 'grey-8'
    },
    ok: {
      label: 'ออกจากระบบ',
      color: 'negative'
    },
    persistent: true
  }).onOk(() => {
    authStore.logout();
    router.push('/login');
  });
};

// Fetch dashboard data
const fetchDashboardData = async () => {
  try {
    const [courses, studentStats] = await Promise.all([
      instructorService.getCourses(),
      instructorService.getMyStudentsStats()
    ]);

    stats.value.totalCourses = courses.length;
    stats.value.totalStudents = studentStats.total_students;
    stats.value.completedStudents = studentStats.total_completed;

    courseStatusCounts.value = {
      approved: courses.filter(c => c.status === 'APPROVED').length,
      pending: courses.filter(c => c.status === 'PENDING').length,
      draft: courses.filter(c => c.status === 'DRAFT').length,
      rejected: courses.filter(c => c.status === 'REJECTED').length
    };

    recentCourses.value = courses.slice(0, 3).map(course => ({
      id: course.id,
      title: course.title.th,
      students: 0,
      lessons: 0,
      icon: 'book',
      thumbnail: course.thumbnail_url || null
    }));
  } catch (error) {
    console.error('Failed to fetch dashboard data:', error);
  }
};

// Fetch data on mount
onMounted(() => {
  authStore.fetchUserProfile();
  fetchDashboardData();
});
</script>
