'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 { 
  Select, 
  SelectContent, 
  SelectItem, 
  SelectTrigger, 
  SelectValue 
} from "@/components/ui/select";
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Loader2, BookOpen, ChevronDown } from "lucide-react";
import { Badge } from "@/components/ui/badge";

interface MataKuliahBelumDiambil {
  nama_mk: string;
  jenis_mk: string;
  kode_mk: string;
  sks: number;
  semester: number;
}

interface MahasiswaMKBelumDiambil {
  nim: string;
  nama: string;
  tahun_angkatan: number;
  sks_total: number;
  mk_belum_diambil: MataKuliahBelumDiambil[];
}

interface TabelMKBelumDiambilProps {
  selectedYear: string;
  selectedJenisMK: string;
  onJenisMKChange: (jenis: string) => void;
}

export default function TabelMKBelumDiambil({ 
  selectedYear, 
  selectedJenisMK, 
  onJenisMKChange 
}: TabelMKBelumDiambilProps) {
  const [mahasiswaData, setMahasiswaData] = useState<MahasiswaMKBelumDiambil[]>([]);
  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<MahasiswaMKBelumDiambil[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        let url = '/api/tabeldetail/mk-belum-diambil';
        const params = new URLSearchParams();

        if (selectedYear && selectedYear !== 'all') {
          params.append('tahun_angkatan', selectedYear);
        }
        if (selectedJenisMK && selectedJenisMK !== 'all') {
          params.append('jenis_mk', selectedJenisMK);
        }

        if (params.toString()) {
          url += `?${params.toString()}`;
        }
          
        const response = await fetch(url, {
          cache: 'no-store',
        });
        
        if (!response.ok) {
          throw new Error('Failed to fetch mahasiswa MK belum diambil data');
        }
        
        const data = await response.json();
        setMahasiswaData(data);
        setCurrentPage(1); // Reset ke halaman pertama saat filter berubah
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Terjadi kesalahan');
        console.error('Error fetching data:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [selectedYear, selectedJenisMK]);

  // 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);
  };

  // Get badge color based on jenis_mk
  const getJenisMKBadgeColor = (jenis: string) => {
    switch (jenis) {
      case 'Wajib':
        return 'bg-blue-500 hover:bg-blue-600';
      case 'Pilihan Wajib':
        return 'bg-green-500 hover:bg-green-600';
      case 'Pilihan':
        return 'bg-amber-500 hover:bg-amber-600';
      default:
        return 'bg-gray-500 hover:bg-gray-600';
    }
  };

  // Calculate statistics
  const stats = {
    total: mahasiswaData.length,
    total_mk_belum_diambil: mahasiswaData.reduce((sum, mhs) => sum + mhs.mk_belum_diambil.length, 0),
    avg_mk_belum_diambil: mahasiswaData.length > 0 
      ? (mahasiswaData.reduce((sum, mhs) => sum + mhs.mk_belum_diambil.length, 0) / mahasiswaData.length).toFixed(1)
      : 0,
  };

  // Get jenis MK counts
  const jenisMKCounts = mahasiswaData.reduce((acc, mhs) => {
    mhs.mk_belum_diambil.forEach(mk => {
      acc[mk.jenis_mk] = (acc[mk.jenis_mk] || 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" />
              Memuat data...
            </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 flex items-center gap-2">
          <BookOpen className="h-5 w-5" />
          Tabel Mahasiswa - Mata Kuliah Belum Diambil {selectedYear !== 'all' ? `Angkatan ${selectedYear}` : 'Semua Angkatan'}
        </CardTitle>
        {/* Tampilkan ringkasan statistik */}
        <div className="grid grid-cols-2 md:grid-cols-3 gap-2 mt-2">
          <div className="px-3 py-2 rounded-lg bg-blue-50 dark:bg-blue-900/20">
            <div className="text-xs text-blue-600 dark:text-blue-400">Total Mahasiswa</div>
            <div className="font-bold text-blue-800 dark:text-blue-300">{stats.total}</div>
          </div>
          <div className="px-3 py-2 rounded-lg bg-amber-50 dark:bg-amber-900/20">
            <div className="text-xs text-amber-600 dark:text-amber-400">Total MK Belum Diambil</div>
            <div className="font-bold text-amber-800 dark:text-amber-300">{stats.total_mk_belum_diambil}</div>
          </div>
        </div>
        {/* Tampilkan badge jenis MK */}
        {selectedJenisMK === 'all' && Object.keys(jenisMKCounts).length > 0 && (
          <div className="flex flex-wrap gap-2 mt-2">
            {Object.entries(jenisMKCounts)
              .sort(([a], [b]) => {
                const order = ['Wajib', 'Pilihan Wajib', 'Pilihan'];
                return order.indexOf(a) - order.indexOf(b);
              })
              .map(([jenis, count]) => (
                <Badge
                  key={jenis}
                  className={`${getJenisMKBadgeColor(jenis)} text-white`}
                >
                  {jenis}: {count} MK
                </Badge>
              ))}
          </div>
        )}
      </CardHeader>
      <CardContent>
        {/* Show entries selector and filter */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 mb-4">
          <div className="flex items-center gap-2 dark:text-white">
            <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>

          {/* Filter Jenis MK */}
          <div className="flex items-center gap-2 dark:text-white">
            <span className="text-sm">Filter Jenis MK:</span>
            <Select
              value={selectedJenisMK}
              onValueChange={onJenisMKChange}
            >
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="Semua Jenis MK" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Semua Jenis MK</SelectItem>
                <SelectItem value="Wajib">Wajib</SelectItem>
                <SelectItem value="Pilihan Wajib">Pilihan Wajib</SelectItem>
                <SelectItem value="Pilihan">Pilihan</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </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">SKS Total</TableHead>
                <TableHead className="font-semibold text-center">Jumlah MK Belum Diambil</TableHead>
                <TableHead className="font-semibold">MK Belum Diambil</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {paginatedData.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                    Tidak ada data yang tersedia
                  </TableCell>
                </TableRow>
              ) : (
                paginatedData.map((mahasiswa, index) => (
                  <TableRow 
                    key={`${mahasiswa.nim}-${mahasiswa.tahun_angkatan}`}
                    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 dark:text-white">
                      {mahasiswa.sks_total}
                    </TableCell>
                    <TableCell className="text-center dark:text-white">
                      <Badge variant="outline" className="font-semibold">
                        {mahasiswa.mk_belum_diambil.length} MK
                      </Badge>
                    </TableCell>
                    <TableCell className="text-center dark:text-white">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button 
                            variant="outline" 
                            size="sm" 
                            className="flex items-center gap-1"
                          >
                            Lihat Detail
                            <ChevronDown className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent 
                          className="w-[400px] max-h-[400px] overflow-y-auto"
                          align="end"
                        >
                          {mahasiswa.mk_belum_diambil.length === 0 ? (
                            <DropdownMenuItem disabled>
                              Tidak ada MK yang belum diambil
                            </DropdownMenuItem>
                          ) : (
                            mahasiswa.mk_belum_diambil.map((mk, mkIndex) => (
                              <DropdownMenuItem 
                                key={`${mk.kode_mk}-${mkIndex}`}
                                className="flex flex-col items-start py-3 cursor-default focus:bg-slate-100 dark:focus:bg-slate-800"
                              >
                                <div className="flex items-center justify-between w-full mb-1">
                                  <span className="font-medium text-sm">{mk.nama_mk}</span>
                                  <Badge 
                                    className={`${getJenisMKBadgeColor(mk.jenis_mk)} text-white text-xs ml-2`}
                                  >
                                    {mk.jenis_mk}
                                  </Badge>
                                </div>
                                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                                  <span className="font-mono">{mk.kode_mk}</span>
                                  <span>•</span>
                                  <span>{mk.sks} SKS</span>
                                  <span>•</span>
                                  <span>Semester {mk.semester}</span>
                                </div>
                              </DropdownMenuItem>
                            ))
                          )}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </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 className="dark:text-white">
              <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;
      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;
  }
}

