'use client';

import { useEffect, useState } from "react";
import { useTheme } from "next-themes";
import DashboardStats, { DashboardStatsSkeleton } from "@/components/dashboard/DashboardStats";
import DashboardCharts from "@/components/dashboard/DashboardCharts";

interface MahasiswaTotal {
  total_mahasiswa: number;
  mahasiswa_aktif: number;
  total_lulus: number;
  pria_lulus: number;
  wanita_lulus: number;
  total_berprestasi: number;
  prestasi_akademik: number;
  prestasi_non_akademik: number;
  total_mahasiswa_aktif_lulus: number;
  total_mahasiswa_beasiswa: number;
  total_mahasiswa_beasiswa_pemerintah: number;
  total_mahasiswa_beasiswa_non_pemerintah: number;
}


export default function DashboardPage() {
  const { theme } = useTheme();
  const [mahasiswaData, setMahasiswaData] = useState<MahasiswaTotal>({
    total_mahasiswa: 0,
    mahasiswa_aktif: 0,
    total_lulus: 0,
    pria_lulus: 0,
    wanita_lulus: 0,
    total_berprestasi: 0,
    prestasi_akademik: 0,
    prestasi_non_akademik: 0,
    total_mahasiswa_aktif_lulus: 0,
    total_mahasiswa_beasiswa: 0,
    total_mahasiswa_beasiswa_pemerintah: 0,
    total_mahasiswa_beasiswa_non_pemerintah: 0
  });

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Menggunakan cache API untuk mempercepat loading
        const cacheKey = 'mahasiswa-total-data';
        const cachedData = sessionStorage.getItem(cacheKey);
        const cachedTimestamp = sessionStorage.getItem(`${cacheKey}-timestamp`);
        
        // Cek apakah data cache masih valid (kurang dari 60 detik)
        const isCacheValid = cachedTimestamp && 
          (Date.now() - parseInt(cachedTimestamp)) < 60000;

        if (cachedData && isCacheValid) {
          setMahasiswaData(JSON.parse(cachedData));
      }
        
        // Fetch data total mahasiswa
        const totalResponse = await fetch('/api/mahasiswa/total', {
          cache: 'no-store',
      });

        if (!totalResponse.ok) {
          throw new Error('Failed to fetch total data');
      }
        
        const totalData = await totalResponse.json();
        setMahasiswaData(totalData);
        
        // Menyimpan data dan timestamp ke sessionStorage
        sessionStorage.setItem(cacheKey, JSON.stringify(totalData));
        sessionStorage.setItem(`${cacheKey}-timestamp`, Date.now().toString());
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
        console.error('Error fetching data:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  return (
    <div className="container mx-auto p-4 space-y-6">
      <h1 className="text-2xl font-bold mb-4">Visualisasi Data Akademik Mahasiswa Informatika</h1>
      
      {loading ? (
        <DashboardStatsSkeleton />
      ) : error ? (
        <div className="bg-red-50 border-l-4 border-red-500 p-4 mb-4">
          <div className="flex">
            <div className="flex-shrink-0">
              <svg className="h-5 w-5 text-red-500" viewBox="0 0 20 20" fill="currentColor">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3">
              <p className="text-sm text-red-700">{error}</p>
                  </div>
                    </div>
                  </div>
      ) : (
        <>
          <DashboardStats mahasiswaData={mahasiswaData} />
          <DashboardCharts />
        </>
        )
      }
      </div>
  );
}
