'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { ArrowLeft, User, Mail, BookOpen, GraduationCap, Calendar, CheckCircle, Clock } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';
import { adminApi } from '@/services/api/admin';
import { StudentDetailResponse } from '@/types';

export default function AdminStudentDetailPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const [student, setStudent] = useState<StudentDetailResponse | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchDetail = async () => {
      try {
        const data = await adminApi.getStudentById(id);
        setStudent(data);
      } catch (error) {
        toast.error('Gagal mengambil data detail murid');
        console.error(error);
      } finally {
        setIsLoading(false);
      }
    };
    if (id) fetchDetail();
  }, [id]);

  if (isLoading) {
    return <div className="flex justify-center py-20 text-muted-foreground">Memuat detail murid...</div>;
  }

  if (!student) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-center space-y-4">
        <p className="text-muted-foreground">Murid tidak ditemukan</p>
        <Button variant="outline" onClick={() => router.back()} className="rounded-xl">Kembali</Button>
      </div>
    );
  }

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' });
  };

  const formatDateTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('id-ID', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
  };

  return (
    <>
      <title>{`${student.fullName} | Nadhom Smart`}</title>
      <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => router.back()} className="rounded-full">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-2xl font-bold">{student.fullName}</h1>
            <p className="text-muted-foreground text-sm">Detail profil dan progress hafalan</p>
          </div>
        </div>

        {/* Profil Section */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-card border border-border/50 rounded-2xl p-6 shadow-sm flex flex-col gap-4">
            <h3 className="font-semibold text-lg border-b border-border/50 pb-3">Informasi Pribadi</h3>
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-primary/10 rounded-lg text-primary"><User className="h-4 w-4" /></div>
                <div>
                  <p className="text-xs text-muted-foreground">Username</p>
                  <p className="font-medium">@{student.username}</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="p-2 bg-primary/10 rounded-lg text-primary"><Mail className="h-4 w-4" /></div>
                <div>
                  <p className="text-xs text-muted-foreground">Email</p>
                  <p className="font-medium">{student.email}</p>
                </div>
              </div>
            </div>
          </div>
          <div className="bg-card border border-border/50 rounded-2xl p-6 shadow-sm flex flex-col gap-4">
            <h3 className="font-semibold text-lg border-b border-border/50 pb-3">Akademik</h3>
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-secondary/10 rounded-lg text-secondary"><BookOpen className="h-4 w-4" /></div>
                <div>
                  <p className="text-xs text-muted-foreground">NIS</p>
                  <p className="font-medium">{student.nis || '-'}</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="p-2 bg-secondary/10 rounded-lg text-secondary"><GraduationCap className="h-4 w-4" /></div>
                <div>
                  <p className="text-xs text-muted-foreground">Kelas</p>
                  <p className="font-medium">{student.className || '-'}</p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <div className="p-2 bg-secondary/10 rounded-lg text-secondary"><Calendar className="h-4 w-4" /></div>
                <div>
                  <p className="text-xs text-muted-foreground">Tanggal Bergabung</p>
                  <p className="font-medium">{student.joinDate ? formatDate(student.joinDate) : '-'}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Progress Hafalan */}
        <div className="bg-card border border-border/50 rounded-2xl p-6 shadow-sm space-y-6">
          <div className="flex justify-between items-center border-b border-border/50 pb-4">
            <div>
              <h3 className="font-semibold text-lg">Progress Hafalan</h3>
              <p className="text-sm text-muted-foreground">Daftar hafalan yang telah disetorkan</p>
            </div>
            <Badge variant="secondary" className="rounded-full px-3">{student.progress?.length || 0} Bait</Badge>
          </div>

          <div className="space-y-4">
            {!student.progress || student.progress.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                Belum ada progress hafalan yang dicatat.
              </div>
            ) : (
              student.progress.map((prog) => (
                <div key={prog.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 rounded-xl border border-border/50 hover:bg-accent/50 transition-colors gap-4">
                  <div>
                    <h4 className="font-medium text-base mb-1">{prog.chapterTitle}</h4>
                    <p className="text-sm text-muted-foreground flex items-center gap-2">
                      <span>Bait ke-{prog.verseNumber}</span>
                      <span className="w-1 h-1 bg-border rounded-full" />
                      <span className="flex items-center gap-1"><Clock className="h-3 w-3" /> {formatDateTime(prog.completedAt)}</span>
                    </p>
                  </div>
                  <div className="flex items-center justify-between sm:justify-end gap-4 w-full sm:w-auto">
                    <div className="text-left sm:text-right">
                      <p className="text-xs text-muted-foreground mb-1">Skor Terbaik</p>
                      <p className="font-semibold text-primary">{prog.bestScore}</p>
                    </div>
                    <Badge variant={prog.status === 'COMPLETED' ? 'default' : 'outline'} className={`rounded-full ${prog.status === 'COMPLETED' ? 'bg-green-500 hover:bg-green-600 border-0' : ''}`}>
                      {prog.status === 'COMPLETED' && <CheckCircle className="h-3 w-3 mr-1" />}
                      {prog.status}
                    </Badge>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </motion.div>
    </>
  );
}
