'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { motion } from 'framer-motion';
import { Search, Filter, Loader2, ClipboardCheck } from 'lucide-react';
import Link from 'next/link';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Card, CardContent } from '@/components/ui/card';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { teacherApi } from '@/services/api/teacher';

const statusLabels: Record<string, string> = { 
  PENDING: 'Menunggu', 
  APPROVED: 'Disetujui', 
  NEED_REVISION: 'Revisi', 
  AI_REVIEWED: 'Review AI',
  REJECTED: 'Ditolak' 
};

const statusClasses: Record<string, string> = {
  PENDING: 'bg-warning/10 text-warning border-warning/20',
  APPROVED: 'bg-success/10 text-success border-success/20',
  NEED_REVISION: 'bg-destructive/10 text-destructive border-destructive/20',
  AI_REVIEWED: 'bg-blue-500/10 text-blue-500 border-blue-500/20',
  REJECTED: 'bg-destructive/10 text-destructive border-destructive/20',
};

function getRelativeTime(dateString?: string) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  const now = new Date();
  const diffInMinutes = Math.floor((now.getTime() - date.getTime()) / 1000 / 60);
  
  if (diffInMinutes < 1) return 'Baru saja';
  if (diffInMinutes < 60) return `${diffInMinutes} menit lalu`;
  const diffInHours = Math.floor(diffInMinutes / 60);
  if (diffInHours < 24) return `${diffInHours} jam lalu`;
  return `${Math.floor(diffInHours / 24)} hari lalu`;
}

export default function ReviewsPage() {
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');

  const { data: response, isLoading } = useQuery({
    queryKey: ['teacher', 'reviews'],
    queryFn: () => teacherApi.getPendingReviews(),
  });

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

  const filtered = reviews.filter((r) => {
    const matchSearch = !search || r.student?.user?.fullName?.toLowerCase().includes(search.toLowerCase());
    const matchStatus = statusFilter === 'all' || r.status === statusFilter;
    return matchSearch && matchStatus;
  });

  return (
    <>
      <title>Review Setoran | 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 siswa..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 rounded-xl" />
        </div>

        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full rounded-xl text-xs h-9">
            <Filter className="h-3 w-3 mr-1.5" />
            <SelectValue placeholder="Filter Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Semua</SelectItem>
            <SelectItem value="PENDING">Menunggu</SelectItem>
            <SelectItem value="AI_REVIEWED">Review AI</SelectItem>
            <SelectItem value="APPROVED">Disetujui</SelectItem>
            <SelectItem value="NEED_REVISION">Perlu Revisi</SelectItem>
          </SelectContent>
        </Select>

        {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} setoran</p>

            {filtered.length === 0 ? (
              <div className="text-center p-8 bg-muted/20 rounded-xl border border-dashed">
                <ClipboardCheck className="h-10 w-10 text-muted-foreground mx-auto mb-2 opacity-20" />
                <p className="text-sm text-muted-foreground">Tidak ada setoran ditemukan</p>
              </div>
            ) : (
              <div className="flex flex-col gap-3 pb-24">
                {filtered.map((r, i) => (
                  <motion.div key={r.id} initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.03 }}>
                    <Link href={`/teacher/reviews/${r.id}`} 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-3">
                          <Avatar className="h-9 w-9">
                            <AvatarFallback className="bg-primary/10 text-primary text-xs font-semibold">
                              {r.student?.user?.fullName?.charAt(0).toUpperCase() || '?'}
                            </AvatarFallback>
                          </Avatar>
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium truncate">{r.student?.user?.fullName || 'Anonim'}</p>
                            <p className="text-xs text-muted-foreground">
                              Nadhom #{r.verse?.number || '?'} · {getRelativeTime(r.submittedAt)}
                            </p>
                          </div>
                          <div className="text-right">
                            <Badge variant="outline" className={`text-[10px] ${statusClasses[r.status] || statusClasses['PENDING']}`}>
                              {statusLabels[r.status] || r.status}
                            </Badge>
                            {(r.aiScore?.finalScore || r.teacherReview?.score) && (
                              <p className="text-xs font-bold text-primary mt-1">
                                {r.teacherReview?.score || r.aiScore?.finalScore}
                              </p>
                            )}
                          </div>
                        </CardContent>
                      </Card>
                    </Link>
                  </motion.div>
                ))}
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}
