'use client';

import { useState, useEffect, useCallback } from 'react';
import { GraduationCap, Plus, Trash2 } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';

const ORANGE_BTN = 'bg-gradient-to-r from-orange-600 to-amber-500 shadow-sm';

export function AdminMCQ() {
  const [questions, setQuestions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [q, setQ] = useState({ question: '', optionA: '', optionB: '', optionC: '', optionD: '', correctAnswer: 'A', category: 'gk', difficulty: 'medium', explanation: '' });
  const [addLoading, setAddLoading] = useState(false);

  const fetchQ = useCallback(async () => {
    try { const r = await fetch('/api/admin/mcq'); const d = await r.json(); if (d.success) setQuestions(d.questions); } catch { }
    finally { setLoading(false); }
  }, []);
  useEffect(() => { fetchQ(); }, [fetchQ]);

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault(); setAddLoading(true);
    try { const r = await fetch('/api/admin/mcq', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(q) }); const d = await r.json(); if (d.success) { setShowAddDialog(false); setQ({ question: '', optionA: '', optionB: '', optionC: '', optionD: '', correctAnswer: 'A', category: 'gk', difficulty: 'medium', explanation: '' }); fetchQ(); } } catch { }
    finally { setAddLoading(false); }
  };
  const handleDelete = async (id: string) => {
    try { const r = await fetch('/api/admin/mcq', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) }); const d = await r.json(); if (d.success) fetchQ(); } catch { }
  };

  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" /></div>;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between"><p className="text-sm text-muted-foreground">{questions.length} questions</p><Button className={`gap-2 ${ORANGE_BTN}`} onClick={() => setShowAddDialog(true)}><Plus className="h-4 w-4" />Add Question</Button></div>
      <div className="grid gap-4 sm:grid-cols-2">
        {questions.map((item) => (
          <Card key={item.id} className="border-0 shadow-sm"><CardContent className="p-4">
            <div className="flex items-start justify-between gap-3"><div className="flex-1">
              <div className="flex items-center gap-2 mb-2"><Badge className="bg-orange-50 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400 text-[10px] border-0">{item.category}</Badge><Badge className="bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400 text-[10px] border-0">{item.difficulty}</Badge></div>
              <p className="text-sm font-medium">{item.question}</p>
              <div className="mt-2 grid grid-cols-2 gap-1 text-xs">
                {['A', 'B', 'C', 'D'].map((l) => (<span key={l} className={`rounded-lg px-2 py-1 ${item.correctAnswer === l ? 'bg-emerald-50 text-emerald-700 font-semibold dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-slate-50 dark:bg-slate-800'}`}>{l}. {item[`option${l}`]}</span>))}
              </div>
            </div>
            <AlertDialog><AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8 shrink-0"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button></AlertDialogTrigger><AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Delete Question</AlertDialogTitle><AlertDialogDescription>Delete this MCQ question?</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => handleDelete(item.id)} className="bg-destructive text-destructive-foreground">Delete</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>
            </div>
          </CardContent></Card>
        ))}
        {questions.length === 0 && <div className="col-span-full py-16 text-center"><GraduationCap className="mx-auto h-12 w-12 text-slate-300" strokeWidth={1.5} /><p className="mt-3 text-sm text-muted-foreground">No MCQ questions found</p></div>}
      </div>

      <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}><DialogContent className="sm:max-w-[520px] max-h-[85vh] overflow-y-auto"><DialogHeader><DialogTitle className="flex items-center gap-2"><GraduationCap className="h-5 w-5 text-orange-500" />Add MCQ Question</DialogTitle></DialogHeader>
        <form onSubmit={handleAdd} className="space-y-3 pt-2">
          <div className="space-y-1.5"><Label className="text-xs font-medium">Question</Label><Input value={q.question} onChange={(e) => setQ({ ...q, question: e.target.value })} required /></div>
          <div className="grid grid-cols-2 gap-3">{['A', 'B', 'C', 'D'].map((l) => (<div key={l} className="space-y-1.5"><Label className="text-xs font-medium">Option {l}</Label><Input value={q[`option${l}` as keyof typeof q] as string} onChange={(e) => setQ({ ...q, [`option${l}`]: e.target.value })} required /></div>))}</div>
          <div className="grid grid-cols-3 gap-3">
            <div className="space-y-1.5"><Label className="text-xs font-medium">Correct</Label><select value={q.correctAnswer} onChange={(e) => setQ({ ...q, correctAnswer: e.target.value })} className="w-full rounded-lg border bg-background px-3 py-2 text-sm"><option value="A">A</option><option value="B">B</option><option value="C">C</option><option value="D">D</option></select></div>
            <div className="space-y-1.5"><Label className="text-xs font-medium">Category</Label><select value={q.category} onChange={(e) => setQ({ ...q, category: e.target.value })} className="w-full rounded-lg border bg-background px-3 py-2 text-sm"><option value="gk">GK</option><option value="math">Math</option><option value="science">Science</option><option value="english">English</option><option value="bangla">Bangla</option><option value="ict">ICT</option></select></div>
            <div className="space-y-1.5"><Label className="text-xs font-medium">Difficulty</Label><select value={q.difficulty} onChange={(e) => setQ({ ...q, difficulty: e.target.value })} className="w-full rounded-lg border bg-background px-3 py-2 text-sm"><option value="easy">Easy</option><option value="medium">Medium</option><option value="hard">Hard</option></select></div>
          </div>
          <div className="space-y-1.5"><Label className="text-xs font-medium">Explanation</Label><Input value={q.explanation} onChange={(e) => setQ({ ...q, explanation: e.target.value })} /></div>
          <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={addLoading}>{addLoading ? 'Adding...' : 'Add Question'}</Button>
        </form>
      </DialogContent></Dialog>
    </div>
  );
}
