Files
portaldata/components/chartstable/tabelstatusmahasiswa.tsx
Randa Firman Putra 133ec36510 tes lagi
2025-11-03 17:47:24 +07:00

366 lines
12 KiB
TypeScript

'use client';
import { useEffect, useState } from 'react';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
import { Loader2 } from "lucide-react";
interface MahasiswaStatus {
nim: string;
nama: string;
status_kuliah: string;
tahun_angkatan: number;
}
interface TabelStatusMahasiswaProps {
selectedYear: string;
}
export default function TabelStatusMahasiswa({ selectedYear }: TabelStatusMahasiswaProps) {
const [mahasiswaData, setMahasiswaData] = useState<MahasiswaStatus[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// State for pagination
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [paginatedData, setPaginatedData] = useState<MahasiswaStatus[]>([]);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
setError(null);
const url = selectedYear === 'all'
? '/api/tabeldetail'
: `/api/tabeldetail?tahun_angkatan=${selectedYear}`;
const response = await fetch(url, {
cache: 'no-store',
});
if (!response.ok) {
throw new Error('Failed to fetch mahasiswa data');
}
const data = await response.json();
setMahasiswaData(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Terjadi kesalahan');
console.error('Error fetching data:', err);
} finally {
setLoading(false);
}
};
fetchData();
}, [selectedYear]);
// Update paginated data when data or pagination settings change
useEffect(() => {
paginateData();
}, [mahasiswaData, currentPage, pageSize]);
// Paginate data
const paginateData = () => {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
setPaginatedData(mahasiswaData.slice(startIndex, endIndex));
};
// Get total number of pages
const getTotalPages = () => {
return Math.ceil(mahasiswaData.length / pageSize);
};
// Handle page change
const handlePageChange = (page: number) => {
setCurrentPage(page);
};
// Handle page size change
const handlePageSizeChange = (size: string) => {
setPageSize(Number(size));
setCurrentPage(1); // Reset to first page when changing page size
};
// Fungsi untuk mendapatkan styling badge berdasarkan status (sama seperti data-table-mahasiswa)
const getStatusBadgeStyle = (status: string) => {
switch (status) {
case "Aktif":
return "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300";
case "Cuti":
return "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300";
case "Lulus":
return "bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300";
case "Non Aktif":
return "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300";
default:
return "bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300";
}
};
// Hitung statistik berdasarkan status
const statusStats = mahasiswaData.reduce((acc, mahasiswa) => {
const status = mahasiswa.status_kuliah;
acc[status] = (acc[status] || 0) + 1;
return acc;
}, {} as Record<string, number>);
if (loading) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
<div className="flex items-center gap-2">
<Loader2 className="h-5 w-5 animate-spin" />
Loading...
</div>
</CardTitle>
</CardHeader>
</Card>
);
}
if (error) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold text-red-500 dark:text-red-400">
Error: {error}
</CardTitle>
</CardHeader>
</Card>
);
}
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Tabel Status Mahasiswa {selectedYear !== 'all' ? `Angkatan ${selectedYear}` : 'Semua Angkatan'}
</CardTitle>
{/* Tampilkan ringkasan statistik */}
<div className="flex flex-wrap gap-2 mt-2">
{Object.entries(statusStats).map(([status, count]) => (
<span
key={status}
className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadgeStyle(status)}`}
>
{status}: {count}
</span>
))}
<span className="px-2 py-1 rounded-full text-xs font-semibold bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200">
Total: {mahasiswaData.length}
</span>
</div>
</CardHeader>
<CardContent>
{/* Show entries selector */}
<div className="flex items-center gap-2 mb-4">
<span className="text-sm">Show</span>
<Select
value={pageSize.toString()}
onValueChange={handlePageSizeChange}
>
<SelectTrigger className="w-[80px]">
<SelectValue placeholder={pageSize.toString()} />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="25">25</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
</SelectContent>
</Select>
<span className="text-sm">entries</span>
</div>
<div className="border rounded-md overflow-hidden">
<Table>
<TableHeader>
<TableRow className="bg-gray-50 dark:bg-slate-800">
<TableHead className="font-semibold text-center">No</TableHead>
<TableHead className="font-semibold">NIM</TableHead>
<TableHead className="font-semibold">Nama Mahasiswa</TableHead>
<TableHead className="font-semibold text-center">Tahun Angkatan</TableHead>
<TableHead className="font-semibold text-center">Status Kuliah</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{paginatedData.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
Tidak ada data yang tersedia
</TableCell>
</TableRow>
) : (
paginatedData.map((mahasiswa, index) => (
<TableRow
key={mahasiswa.nim}
className={index % 2 === 0 ? "bg-white dark:bg-slate-900" : "bg-gray-50/50 dark:bg-slate-800/50"}
>
<TableCell className="text-center font-medium dark:text-white">
{(currentPage - 1) * pageSize + index + 1}
</TableCell>
<TableCell className="font-medium dark:text-white">
{mahasiswa.nim}
</TableCell>
<TableCell className="dark:text-white">
{mahasiswa.nama}
</TableCell>
<TableCell className="text-center dark:text-white">
{mahasiswa.tahun_angkatan}
</TableCell>
<TableCell className="text-center">
<span
className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadgeStyle(mahasiswa.status_kuliah)}`}
>
{mahasiswa.status_kuliah}
</span>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{/* Pagination info and controls */}
{!loading && !error && mahasiswaData.length > 0 && (
<div className="flex flex-col sm:flex-row justify-between items-center gap-4 mt-4">
<div className="text-sm text-muted-foreground">
Showing {getDisplayRange().start} to {getDisplayRange().end} of {mahasiswaData.length} entries
</div>
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
/>
</PaginationItem>
{renderPaginationItems()}
<PaginationItem>
<PaginationNext
onClick={() => handlePageChange(Math.min(getTotalPages(), currentPage + 1))}
className={currentPage === getTotalPages() ? "pointer-events-none opacity-50" : "cursor-pointer"}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
)}
</CardContent>
</Card>
);
// Calculate the range of entries being displayed
function getDisplayRange() {
if (mahasiswaData.length === 0) return { start: 0, end: 0 };
const start = (currentPage - 1) * pageSize + 1;
const end = Math.min(currentPage * pageSize, mahasiswaData.length);
return { start, end };
}
// Generate pagination items
function renderPaginationItems() {
const totalPages = getTotalPages();
const items = [];
// Always show first page
items.push(
<PaginationItem key="first">
<PaginationLink
isActive={currentPage === 1}
onClick={() => handlePageChange(1)}
className="cursor-pointer"
>
1
</PaginationLink>
</PaginationItem>
);
// Show ellipsis if needed
if (currentPage > 3) {
items.push(
<PaginationItem key="ellipsis-start">
<PaginationEllipsis />
</PaginationItem>
);
}
// Show pages around current page
for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
if (i === 1 || i === totalPages) continue; // Skip first and last pages as they're always shown
items.push(
<PaginationItem key={i}>
<PaginationLink
isActive={currentPage === i}
onClick={() => handlePageChange(i)}
className="cursor-pointer"
>
{i}
</PaginationLink>
</PaginationItem>
);
}
// Show ellipsis if needed
if (currentPage < totalPages - 2) {
items.push(
<PaginationItem key="ellipsis-end">
<PaginationEllipsis />
</PaginationItem>
);
}
// Always show last page if there's more than one page
if (totalPages > 1) {
items.push(
<PaginationItem key="last">
<PaginationLink
isActive={currentPage === totalPages}
onClick={() => handlePageChange(totalPages)}
className="cursor-pointer"
>
{totalPages}
</PaginationLink>
</PaginationItem>
);
}
return items;
}
}