'use client';

import DashboardLayout from '@/layouts/DashboardLayout';
import { CalendarIcon, ChartBarIcon, ArrowTrendingUpIcon, ArrowTrendingDownIcon, ArrowDownTrayIcon } from '@heroicons/react/24/outline';
import { cn } from '@/utils/cn';
import { useState } from 'react';

const reportData = {
  overview: {
    totalCourses: 4,
    completedCourses: 1,
    averageScore: 88.3,
    totalStudyHours: 45.5,
    certificatesEarned: 3,
    currentStreak: 12
  },
  courseProgress: [
    {
      id: 1,
      name: 'HACCP - Hazard Analysis Critical Control Point',
      progress: 67,
      timeSpent: 18.5,
      lastAccessed: '2024-01-24',
      averageScore: 85,
      status: 'in_progress'
    },
    {
      id: 2,
      name: 'SLHS - Sanitasi Lingkungan Hidup Sehat',
      progress: 45,
      timeSpent: 12.3,
      lastAccessed: '2024-01-23',
      averageScore: 78,
      status: 'in_progress'
    },
    {
      id: 3,
      name: 'Sertifikasi Halal - Sistem Jaminan Halal',
      progress: 100,
      timeSpent: 8.7,
      lastAccessed: '2024-01-22',
      averageScore: 92,
      status: 'completed'
    },
    {
      id: 4,
      name: 'Keamanan Pangan Industri',
      progress: 5,
      timeSpent: 2.0,
      lastAccessed: '2024-01-21',
      averageScore: 0,
      status: 'started'
    }
  ],
  weeklyActivity: [
    { day: 'Senin', hours: 2.5, completed: 3 },
    { day: 'Selasa', hours: 1.8, completed: 2 },
    { day: 'Rabu', hours: 3.2, completed: 4 },
    { day: 'Kamis', hours: 2.1, completed: 2 },
    { day: 'Jumat', hours: 4.0, completed: 5 },
    { day: 'Sabtu', hours: 1.5, completed: 1 },
    { day: 'Minggu', hours: 0.8, completed: 1 }
  ],
  monthlyTrends: {
    studyHours: { current: 45.5, previous: 38.2, change: 19.1 },
    averageScore: { current: 88.3, previous: 85.7, change: 3.0 },
    coursesCompleted: { current: 1, previous: 0, change: 100 },
    certificates: { current: 3, previous: 2, change: 50 }
  }
};

const statusColors = {
  completed: 'bg-green-100 text-green-800',
  in_progress: 'bg-blue-100 text-blue-800',
  started: 'bg-yellow-100 text-yellow-800'
};

const statusLabels = {
  completed: 'Selesai',
  in_progress: 'Berlangsung',
  started: 'Dimulai'
};

function formatDate(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleDateString('id-ID', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  });
}

function TrendIndicator({ value, isPositive }: { value: number; isPositive?: boolean }) {
  const positive = isPositive !== undefined ? isPositive : value > 0;
  const TrendIcon = positive ? ArrowTrendingUpIcon : ArrowTrendingDownIcon;
  
  return (
    <div className={cn(
      "flex items-center text-sm",
      positive ? "text-green-600" : "text-red-600"
    )}>
      <TrendIcon className="h-4 w-4 mr-1" />
      <span>{Math.abs(value)}%</span>
    </div>
  );
}

export default function ReportsPage() {
  const [isDownloading, setIsDownloading] = useState(false);

  const handleDownloadReport = async () => {
    setIsDownloading(true);
    
    try {
      // Simulate report generation
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // Create CSV content
      const csvContent = generateCSVReport();
      
      // Create and download file
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `laporan-pembelajaran-${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
    } catch (error) {
      console.error('Error downloading report:', error);
      alert('Gagal mengunduh laporan. Silakan coba lagi.');
    } finally {
      setIsDownloading(false);
    }
  };

  const generateCSVReport = () => {
    const headers = ['Kursus', 'Progress (%)', 'Waktu Belajar (jam)', 'Terakhir Diakses', 'Rata-rata Nilai', 'Status'];
    const rows = reportData.courseProgress.map(course => [
      course.name,
      course.progress,
      course.timeSpent,
      course.lastAccessed,
      course.averageScore,
      statusLabels[course.status as keyof typeof statusLabels]
    ]);
    
    const csvContent = [headers, ...rows]
      .map(row => row.map(field => `"${field}"`).join(','))
      .join('\n');
    
    return `\uFEFF${csvContent}`; // Add BOM for proper UTF-8 encoding
  };

  return (
    <DashboardLayout>
      <div className="p-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">Laporan</h1>
            <p className="text-gray-600">Analisis progress dan performa pembelajaran Anda</p>
          </div>
          <button 
            onClick={handleDownloadReport}
            disabled={isDownloading}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <ArrowDownTrayIcon className={cn("h-4 w-4 mr-2", isDownloading && "animate-spin")} />
            {isDownloading ? 'Mengunduh...' : 'Unduh Laporan'}
          </button>
        </div>

        {/* Overview Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-6 mb-8">
          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between mb-2">
              <p className="text-sm font-medium text-gray-600">Total Kursus</p>
              <ChartBarIcon className="h-5 w-5 text-blue-600" />
            </div>
            <p className="text-2xl font-bold text-gray-900">{reportData.overview.totalCourses}</p>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between mb-2">
              <p className="text-sm font-medium text-gray-600">Selesai</p>
              <ArrowTrendingUpIcon className="h-5 w-5 text-green-600" />
            </div>
            <p className="text-2xl font-bold text-gray-900">{reportData.overview.completedCourses}</p>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between mb-2">
              <p className="text-sm font-medium text-gray-600">Rata-rata Nilai</p>
              <ChartBarIcon className="h-5 w-5 text-purple-600" />
            </div>
            <p className="text-2xl font-bold text-gray-900">{reportData.overview.averageScore}</p>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between mb-2">
              <p className="text-sm font-medium text-gray-600">Jam Belajar</p>
              <CalendarIcon className="h-5 w-5 text-orange-600" />
            </div>
            <p className="text-2xl font-bold text-gray-900">{reportData.overview.totalStudyHours}h</p>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between mb-2">
              <p className="text-sm font-medium text-gray-600">Sertifikat</p>
              <ChartBarIcon className="h-5 w-5 text-yellow-600" />
            </div>
            <p className="text-2xl font-bold text-gray-900">{reportData.overview.certificatesEarned}</p>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between mb-2">
              <p className="text-sm font-medium text-gray-600">Streak Hari</p>
              <ArrowTrendingUpIcon className="h-5 w-5 text-red-600" />
            </div>
            <p className="text-2xl font-bold text-gray-900">{reportData.overview.currentStreak}</p>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
          {/* Course Progress */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100">
            <div className="p-6 border-b border-gray-100">
              <h2 className="text-xl font-semibold text-gray-900">Progress Kursus</h2>
            </div>
            <div className="p-6">
              <div className="space-y-4">
                {reportData.courseProgress.map((course) => (
                  <div key={course.id} className="border border-gray-200 rounded-lg p-4">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1">
                        <h3 className="font-medium text-gray-900 mb-1">{course.name}</h3>
                        <div className="flex items-center space-x-4 text-sm text-gray-600">
                          <span>Terakhir: {formatDate(course.lastAccessed)}</span>
                          <span>{course.timeSpent}h</span>
                          {course.averageScore > 0 && (
                            <span>Nilai: {course.averageScore}%</span>
                          )}
                        </div>
                      </div>
                      <span className={cn(
                        "px-2 py-1 rounded-full text-xs font-medium",
                        statusColors[course.status as keyof typeof statusColors]
                      )}>
                        {statusLabels[course.status as keyof typeof statusLabels]}
                      </span>
                    </div>
                    
                    <div className="mb-2">
                      <div className="flex items-center justify-between text-sm mb-1">
                        <span className="text-gray-600">Progress</span>
                        <span className="font-medium text-gray-900">{course.progress}%</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div 
                          className={cn(
                            "h-2 rounded-full transition-all duration-300",
                            course.progress === 100 ? 'bg-green-500' : 'bg-blue-500'
                          )}
                          style={{ width: `${course.progress}%` }}
                        />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Weekly Activity */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100">
            <div className="p-6 border-b border-gray-100">
              <h2 className="text-xl font-semibold text-gray-900">Aktivitas Mingguan</h2>
            </div>
            <div className="p-6">
              <div className="space-y-4">
                {reportData.weeklyActivity.map((day, index) => (
                  <div key={index} className="flex items-center justify-between">
                    <div className="flex items-center space-x-4">
                      <span className="w-16 text-sm font-medium text-gray-900">{day.day}</span>
                      <div className="flex-1">
                        <div className="w-32 bg-gray-200 rounded-full h-2">
                          <div 
                            className="h-2 bg-blue-500 rounded-full transition-all duration-300"
                            style={{ width: `${(day.hours / 4) * 100}%` }}
                          />
                        </div>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-medium text-gray-900">{day.hours}h</p>
                      <p className="text-xs text-gray-600">{day.completed} selesai</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Monthly Trends */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100">
          <div className="p-6 border-b border-gray-100">
            <h2 className="text-xl font-semibold text-gray-900">Tren Bulanan</h2>
          </div>
          <div className="p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-2">Jam Belajar</p>
                <p className="text-2xl font-bold text-gray-900 mb-1">{reportData.monthlyTrends.studyHours.current}h</p>
                <TrendIndicator value={reportData.monthlyTrends.studyHours.change} />
              </div>
              
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-2">Rata-rata Nilai</p>
                <p className="text-2xl font-bold text-gray-900 mb-1">{reportData.monthlyTrends.averageScore.current}%</p>
                <TrendIndicator value={reportData.monthlyTrends.averageScore.change} />
              </div>
              
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-2">Kursus Selesai</p>
                <p className="text-2xl font-bold text-gray-900 mb-1">{reportData.monthlyTrends.coursesCompleted.current}</p>
                <TrendIndicator value={reportData.monthlyTrends.coursesCompleted.change} />
              </div>
              
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-2">Sertifikat Baru</p>
                <p className="text-2xl font-bold text-gray-900 mb-1">{reportData.monthlyTrends.certificates.current}</p>
                <TrendIndicator value={reportData.monthlyTrends.certificates.change} />
              </div>
            </div>
          </div>
        </div>
      </div>
    </DashboardLayout>
  );
}