'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { 
  BookOpenIcon,
  ChartBarIcon,
  ClockIcon,
  TrophyIcon
} from '@heroicons/react/24/outline';
import DashboardLayout from '@/layouts/DashboardLayout';
import WelcomeCard from '@/components/dashboard/WelcomeCard';
import StatsCard from '@/components/dashboard/StatsCard';
import CourseCard from '@/components/dashboard/CourseCard';
import { useAuth } from '@/contexts/AuthContext';

// Sample data
const statsData = [
  {
    title: 'Kursus Terdaftar',
    value: '12',
    subtitle: '3 kursus aktif',
    icon: <BookOpenIcon />,
    color: 'blue' as const,
    trend: { value: '+2 bulan ini', isPositive: true }
  },
  {
    title: 'Rata-rata Nilai',
    value: '78%',
    subtitle: '↗ 5% dari bulan lalu',
    icon: <ChartBarIcon />,
    color: 'success' as const,
    trend: { value: '+5%', isPositive: true }
  },
  {
    title: 'Sertifikat Diperoleh',
    value: '5',
    subtitle: '2 menunggu',
    icon: <TrophyIcon />,
    color: 'yellow' as const
  },
  {
    title: 'Jam Pembelajaran',
    value: '24',
    subtitle: '6 jam minggu ini',
    icon: <ClockIcon />,
    color: 'purple' as const,
    trend: { value: '+3 jam', isPositive: true }
  }
];

type UiCourseCard = {
  id: string;
  title: string;
  instructor: string;
  progress: number;
  status: 'Wajib' | 'Berlangsung' | 'Baru' | 'Selesai';
  thumbnail?: string;
  duration?: string;
  color?: 'pink' | 'blue' | 'orange' | 'green' | 'purple';
};

function toCardCourse(item: any): UiCourseCard {
  const status: UiCourseCard['status'] = Number(item?.progress || 0) === 100
    ? 'Selesai'
    : item?.status === 'in_progress'
      ? 'Berlangsung'
      : 'Baru';

  const color: UiCourseCard['color'] = item?.color === '#FF9800'
    ? 'orange'
    : item?.color === '#3F51B5'
      ? 'blue'
      : 'blue';

  const duration = typeof item?.duration === 'string'
    ? item.duration.replace('h', ' jam')
    : (item?.duration ? String(item.duration) : undefined);

  return {
    id: String(item?.id || ''),
    title: String(item?.title || ''),
    instructor: String(item?.instructor || ''),
    progress: Number(item?.progress || 0),
    status,
    color,
    thumbnail: item?.thumbnail,
    duration,
  };
}

const recentActivities = [
  {
    id: 1,
    type: 'course_completed',
    title: 'Menyelesaikan modul "Prinsip HACCP"',
    time: '2 jam yang lalu',
    course: 'HACCP - Hazard Analysis Critical Control Point'
  },
  {
    id: 2,
    type: 'assignment_submitted',
    title: 'Mengumpulkan tugas "Analisis Bahaya Pangan"',
    time: '5 jam yang lalu',
    course: 'HACCP - Hazard Analysis Critical Control Point'
  },
  {
    id: 3,
    type: 'exam_taken',
    title: 'Mengikuti ujian "Sanitasi Dasar"',
    time: '1 hari yang lalu',
    course: 'SLHS - Sanitasi Lingkungan Hidup Sehat',
    score: '85%'
  },
  {
    id: 4,
    type: 'certificate_earned',
    title: 'Memperoleh sertifikat "Keamanan Pangan Dasar"',
    time: '3 hari yang lalu',
    course: 'Keamanan Pangan untuk Industri'
  }
];

export default function Dashboard() {
  const { user, isLoading } = useAuth();
  const [activeCourses, setActiveCourses] = useState<UiCourseCard[]>([]);
  const [loadingActive, setLoadingActive] = useState(true);
  const [errorActive, setErrorActive] = useState<string | null>(null);

  useEffect(() => {
    const ctrl = new AbortController();
    (async () => {
      setLoadingActive(true);
      setErrorActive(null);
      try {
        const res = await fetch('/api/courses?page=1&limit=3', { signal: ctrl.signal });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const json = await res.json();
        const list = Array.isArray(json?.data) ? json.data : [];
        setActiveCourses(list.map(toCardCourse));
      } catch (e: any) {
        setErrorActive(e?.message || 'Gagal memuat kursus aktif');
      } finally {
        setLoadingActive(false);
      }
    })();
    return () => ctrl.abort();
  }, []);

  // Loading state while checking authentication
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary-500"></div>
      </div>
    );
  }

  // AuthContext will handle redirect if user is not authenticated
  if (!user) {
    return null;
  }

  return (
    <DashboardLayout>
      <div className="space-y-6">
        {/* Welcome Section */}
        <WelcomeCard 
          userName="John"
          coursesCount={3}
          hoursStudied={2}
        />
        
        {/* Stats Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {statsData.map((stat, index) => (
            <StatsCard
              key={index}
              title={stat.title}
              value={stat.value}
              subtitle={stat.subtitle}
              icon={stat.icon}
              color={stat.color}
              trend={stat.trend}
            />
          ))}
        </div>
        
        {/* Active Courses Section */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-900">Kursus Aktif</h2>
            <Link 
              href="/courses" 
              className="text-sm text-primary-600 hover:text-primary-700 font-medium"
            >
              Lihat Semua →
            </Link>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {loadingActive && (
              <div className="col-span-3 p-4 bg-white rounded-lg border border-gray-200">Memuat kursus aktif...</div>
            )}
            {!loadingActive && errorActive && (
              <div className="col-span-3 p-4 bg-red-50 text-red-700 border border-red-200 rounded-lg">{errorActive}</div>
            )}
            {!loadingActive && !errorActive && activeCourses.length === 0 && (
              <div className="col-span-3 p-4 bg-white rounded-lg border border-gray-200 text-gray-600">Tidak ada kursus aktif.</div>
            )}
            {!loadingActive && !errorActive && activeCourses.map((course) => (
              <CourseCard key={course.id} course={course} />
            ))}
          </div>
        </div>
        
        {/* Quick Actions */}
        <div className="bg-white rounded-lg shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">
            Aksi Cepat
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <Link
              href="/courses"
              className="flex items-center p-4 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors"
            >
              <BookOpenIcon className="h-8 w-8 text-blue-600 mr-3" />
              <div>
                <div className="font-medium text-gray-900">Jelajahi Kursus</div>
                <div className="text-sm text-gray-500">Temukan kursus baru</div>
              </div>
            </Link>
            
            <Link
              href="/certificates"
              className="flex items-center p-4 bg-green-50 rounded-lg hover:bg-green-100 transition-colors"
            >
              <TrophyIcon className="h-8 w-8 text-green-600 mr-3" />
              <div>
                <div className="font-medium text-gray-900">Sertifikat</div>
                <div className="text-sm text-gray-500">Lihat pencapaian</div>
              </div>
            </Link>
            
            <Link
              href="/profile"
              className="flex items-center p-4 bg-purple-50 rounded-lg hover:bg-purple-100 transition-colors"
            >
              <ChartBarIcon className="h-8 w-8 text-purple-600 mr-3" />
              <div>
                <div className="font-medium text-gray-900">Profil</div>
                <div className="text-sm text-gray-500">Kelola akun</div>
              </div>
            </Link>
            
            <Link
              href="/help"
              className="flex items-center p-4 bg-yellow-50 rounded-lg hover:bg-yellow-100 transition-colors"
            >
              <ClockIcon className="h-8 w-8 text-yellow-600 mr-3" />
              <div>
                <div className="font-medium text-gray-900">Bantuan</div>
                <div className="text-sm text-gray-500">Pusat bantuan</div>
              </div>
            </Link>
          </div>
        </div>

        {/* Development Demo Section moved to Sidebar under Add-ons */}
        
        {/* Recent Activities Section */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-900">Aktivitas Terkini</h2>
            <Link 
              href="/aktivitas" 
              className="text-sm text-primary-600 hover:text-primary-700 font-medium"
            >
              Lihat Semua →
            </Link>
          </div>
          
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="divide-y divide-gray-100">
              {recentActivities.map((activity) => (
                <div key={activity.id} className="p-4 hover:bg-gray-50 transition-colors">
                  <div className="flex items-start space-x-3">
                    <div className="flex-shrink-0">
                      <div className={`w-2 h-2 rounded-full mt-2 ${
                        activity.type === 'course_completed' ? 'bg-green-500' :
                        activity.type === 'assignment_submitted' ? 'bg-blue-500' :
                        activity.type === 'exam_taken' ? 'bg-yellow-500' :
                        'bg-purple-500'
                      }`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900">
                        {activity.title}
                      </p>
                      <p className="text-sm text-gray-600 mt-1">
                        {activity.course}
                      </p>
                      <div className="flex items-center mt-2 space-x-4">
                        <p className="text-xs text-gray-500">
                          {activity.time}
                        </p>
                        {activity.score && (
                          <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            Nilai: {activity.score}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </DashboardLayout>
  );
}