'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { motion } from 'framer-motion';
import { Search, Loader2, Users } from 'lucide-react';
import Link from 'next/link';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { teacherApi } from '@/services/api/teacher';

export default function TeacherStudentsPage() {
  const [search, setSearch] = useState('');

  const { data: response, isLoading } = useQuery({
    queryKey: ['teacher', 'my-students'],
    queryFn: () => teacherApi.getMyStudents(),
  });

  const students = response?.data || [];

  const filtered = students.filter((s) => {
    const matchSearch = !search || 
      s.fullName.toLowerCase().includes(search.toLowerCase()) || 
      (s.nis && s.nis.toLowerCase().includes(search.toLowerCase()));
    return matchSearch;
  });

  return (
    <>
      <title>Daftar Siswa | Nadhom Smart</title>
      <div className="space-y-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input 
            placeholder="Cari nama atau NIS siswa..." 
            value={search} 
            onChange={(e) => setSearch(e.target.value)} 
            className="pl-9 rounded-xl" 
          />
        </div>

        {isLoading ? (
          <div className="flex justify-center p-8">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        ) : (
          <>
            <p className="text-xs text-muted-foreground">{filtered.length} siswa</p>
            
            {filtered.length === 0 ? (
              <div className="text-center p-8 bg-muted/20 rounded-xl border border-dashed">
                <Users className="h-10 w-10 text-muted-foreground mx-auto mb-2 opacity-20" />
                <p className="text-sm text-muted-foreground">Tidak ada siswa ditemukan</p>
              </div>
            ) : (
              <div className="space-y-2">
                {filtered.map((s, i) => (
                  <motion.div 
                    key={s.id} 
                    initial={{ opacity: 0, y: 8 }} 
                    animate={{ opacity: 1, y: 0 }} 
                    transition={{ delay: i * 0.03 }}
                  >
                    <Link href={`/teacher/students/${s.studentId}`} className="block">
                      <Card className="border-border/50 hover:shadow-md hover:border-primary/30 transition-all cursor-pointer">
                        <CardContent className="flex items-center gap-3 p-4">
                        <Avatar className="h-10 w-10">
                          <AvatarFallback className="bg-primary/10 text-primary text-xs font-semibold">
                            {s.fullName ? s.fullName.charAt(0).toUpperCase() : '?'}
                          </AvatarFallback>
                        </Avatar>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-semibold truncate text-foreground">{s.fullName}</p>
                          <p className="text-xs text-muted-foreground mt-0.5">
                            NIS: {s.nis || '-'} · Kelas: {s.className || '-'}
                          </p>
                        </div>
                        <div className="text-right">
                          <p className="text-[10px] text-muted-foreground bg-muted px-2 py-1 rounded-md">
                            Bergabung: {s.joinDate ? new Date(s.joinDate).toLocaleDateString('id-ID') : '-'}
                          </p>
                        </div>
                      </CardContent>
                    </Card>
                    </Link>
                  </motion.div>
                ))}
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}
