'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { PageHeader } from '@/components/common/PageHeader';
import { PrestasiCard } from '@/components/mahasiswa/PrestasiCard';
import { EmptyState } from '@/components/common/EmptyState';
import { getCurrentUserSync } from '@/lib/api/auth';
import { getPrestasiList } from '@/lib/api/prestasi';
import { TSessionUser } from '@/types/auth';
import { TPrestasi } from '@/types/domain';
import { Plus, Search, Award } from 'lucide-react';

export default function MahasiswaPrestasiListPage() {
  const router = useRouter();
  const [user, setUser] = useState<TSessionUser | null>(null);
  const [list, setList] = useState<TPrestasi[]>([]);
  const [status, setStatus] = useState('Semua');
  const [search, setSearch] = useState('');
  const [isLoading, setIsLoading] = useState(true);

  // Pagination states
  const [currentPage, setCurrentPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState<number | 'all'>(10);

  useEffect(() => {
    const session = getCurrentUserSync();
    if (session) {
      setUser(session);
      loadPrestasi(session.id, status, search);
    }
  }, [status, search]);

  // Reset pagination when search/filter changes
  useEffect(() => {
    setCurrentPage(1);
  }, [status, search]);

  async function loadPrestasi(mahasiswaId: string, statusFilter: string, searchFilter: string) {
    setIsLoading(true);
    try {
      const res = await getPrestasiList({
        mahasiswaId,
        status: statusFilter,
        search: searchFilter,
      });
      if (res.success && res.data) {
        setList(res.data);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsLoading(false);
    }
  }

  const statuses = [
    { label: 'Semua', value: 'Semua' },
    { label: 'Draft', value: 'draft' },
    { label: 'Menunggu', value: 'menunggu_verifikasi' },
    { label: 'Terverifikasi', value: 'terverifikasi' },
    { label: 'Ditolak', value: 'ditolak' },
  ];

  const totalRows = list.length;
  const totalPages = rowsPerPage === 'all' ? 1 : Math.ceil(totalRows / rowsPerPage);
  const startIndex = (currentPage - 1) * (rowsPerPage === 'all' ? 0 : rowsPerPage);
  const endIndex = rowsPerPage === 'all' ? totalRows : Math.min(startIndex + rowsPerPage, totalRows);
  const paginatedList = list.slice(startIndex, endIndex);

  if (!user) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <span className="text-sm text-text-muted font-bold">Memuat data pengguna...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <PageHeader
        title="Prestasi Saya"
        description="Pencatatan prestasi perlombaan, minat bakat, dan forum kemahasiswaan."
        action={
          <Link
            href="/dashboard/mahasiswa/prestasi/tambah"
            className="inline-flex items-center gap-2 px-5 py-2.5 bg-primary hover:bg-primary-dark text-white rounded-xl text-sm font-semibold shadow-md shadow-primary/20 hover:shadow-lg transition-all"
          >
            <Plus className="h-4.5 w-4.5" />
            Tambah Prestasi
          </Link>
        }
      />

      {/* Filter and Search Bar */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-text-muted/10 pb-4">
        {/* Status Tabs */}
        <div className="flex items-center gap-1.5 overflow-x-auto pb-1 md:pb-0 whitespace-nowrap">
          {statuses.map((s) => (
            <button
              key={s.value}
              onClick={() => setStatus(s.value)}
              className={`px-4 py-2 rounded-xl text-xs font-bold transition-all ${
                status === s.value
                  ? 'bg-primary text-white shadow-md shadow-primary/20'
                  : 'bg-card text-text-muted border border-text-muted/10 hover:border-text-primary hover:text-text-primary'
              }`}
            >
              {s.label}
            </button>
          ))}
        </div>

        <div className="flex flex-wrap items-center gap-3 w-full md:w-auto justify-between md:justify-end">
          <div className="flex items-center gap-2 text-xs font-semibold text-text-muted">
            <span>Tampilkan</span>
            <select
              value={rowsPerPage}
              onChange={(e) => {
                const val = e.target.value;
                setRowsPerPage(val === 'all' ? 'all' : parseInt(val));
                setCurrentPage(1);
              }}
              className="px-2.5 py-1.5 bg-card border border-text-muted/20 rounded-lg text-text-primary font-bold focus:outline-none focus:border-primary transition-all shadow-sm"
            >
              <option value={10}>10</option>
              <option value={25}>25</option>
              <option value={50}>50</option>
              <option value="all">Semua</option>
            </select>
            <span>baris per halaman</span>
          </div>

          {/* Search Input */}
          <div className="relative w-full md:max-w-xs">
            <span className="absolute inset-y-0 left-0 pl-3.5 flex items-center text-text-muted pointer-events-none">
              <Search className="h-4 w-4" />
            </span>
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Cari prestasi..."
              className="w-full pl-10 pr-4 py-2.5 bg-card border border-text-muted/20 rounded-xl text-sm placeholder:text-text-muted text-text-primary focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
            />
          </div>
        </div>
      </div>

      {/* Grid List */}
      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3].map((n) => (
            <div key={n} className="h-44 bg-card border border-text-muted/10 rounded-2xl animate-pulse" />
          ))}
        </div>
      ) : list.length > 0 ? (
        <div className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {paginatedList.map((item) => (
              <PrestasiCard key={item.id} prestasi={item} />
            ))}
          </div>

          {/* Pagination Footer */}
          <div className="p-4 bg-card border border-text-muted/10 rounded-2xl flex flex-col sm:flex-row items-center justify-between gap-4 text-xs font-semibold text-text-muted shadow-sm">
            <span>
              Menampilkan {totalRows > 0 ? startIndex + 1 : 0} - {endIndex} dari {totalRows} data
            </span>
            
            {totalPages > 1 && (
                <div className="flex items-center gap-1.5">
                  <button
                    type="button"
                    disabled={currentPage === 1}
                    onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                    className="p-1.5 bg-card hover:bg-background border border-text-muted/10 rounded-lg text-text-primary font-bold transition-all disabled:opacity-50"
                  >
                    Sebelumnya
                  </button>
                  {Array.from({ length: totalPages }, (_, i) => i + 1).map(pageNum => (
                    <button
                      key={pageNum}
                      type="button"
                      onClick={() => setCurrentPage(pageNum)}
                      className={`w-7 h-7 rounded-lg text-xs font-bold transition-all ${
                        currentPage === pageNum
                          ? "bg-primary text-white"
                          : "bg-card hover:bg-background border border-text-muted/10 text-text-primary"
                      }`}
                    >
                      {pageNum}
                    </button>
                  ))}
                  <button
                    type="button"
                    disabled={currentPage === totalPages}
                    onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                    className="p-1.5 bg-card hover:bg-background border border-text-muted/10 rounded-lg text-text-primary font-bold transition-all disabled:opacity-50"
                  >
                    Selanjutnya
                  </button>
                </div>
              )}
            </div>
          </div>
      ) : (
        <EmptyState
          title="Tidak Ada Prestasi"
          description={
            search || status !== 'Semua'
              ? 'Tidak ada prestasi yang cocok dengan kata kunci atau filter terpilih.'
              : 'Anda belum mendaftarkan prestasi kemahasiswaan apa pun.'
          }
          actionLabel="Tambah Prestasi"
          onAction={() => router.push('/dashboard/mahasiswa/prestasi/tambah')}
        />
      )}
    </div>
  );
}
