import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { useAssignments } from "@/hooks/queries";
import { Upload } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import AiWritingHelper from "@/components/ai/AiWritingHelper";
import AiTipBanner from "@/components/ai/AiTipBanner";

export default function StudentAssignments() {
  const [submitOpen, setSubmitOpen] = useState(false);
  const [selectedAssignment, setSelectedAssignment] = useState<string | null>(null);
  const [draftText, setDraftText] = useState("");
  const { toast } = useToast();
  const { data: assignmentsData, isLoading } = useAssignments();
  const assignments = assignmentsData?.items ?? [];
  if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  const handleSubmit = () => {
    setSubmitOpen(false);
    toast({ title: "Assignment Submitted", description: "Your work has been submitted successfully." });
  };

  const statusFilter = (status: string) => assignments.filter(a => status === "all" ? true : a.status === status);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Assignments</h1>
        <p className="text-muted-foreground">View and submit your assignments.</p>
      </div>

      <AiTipBanner context="student-assignments" variant="recommendation" />

      <Tabs defaultValue="all">
        <TabsList>
          <TabsTrigger value="all">All ({assignments.length})</TabsTrigger>
          <TabsTrigger value="pending">Pending ({statusFilter("pending").length})</TabsTrigger>
          <TabsTrigger value="submitted">Submitted ({statusFilter("submitted").length})</TabsTrigger>
          <TabsTrigger value="graded">Graded ({statusFilter("graded").length})</TabsTrigger>
        </TabsList>

        {["all", "pending", "submitted", "graded", "overdue"].map(tab => (
          <TabsContent key={tab} value={tab} className="mt-4 space-y-3">
            {statusFilter(tab).map(a => (
              <Card key={a.id}>
                <CardContent className="pt-4">
                  <div className="flex items-center justify-between">
                    <div className="min-w-0">
                      <p className="font-medium text-sm">{a.title}</p>
                      <p className="text-xs text-muted-foreground">{a.courseName} · Due: {a.dueDate}</p>
                      {a.grade !== undefined && <p className="text-xs font-medium text-primary mt-1">Grade: {a.grade}/{a.maxGrade}</p>}
                      {a.feedback && <p className="text-xs text-muted-foreground mt-0.5">"{a.feedback}"</p>}
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <Badge variant={a.status === "graded" ? "default" : a.status === "overdue" ? "destructive" : "secondary"}>{a.status}</Badge>
                      {a.status === "pending" && (
                        <Button size="sm" onClick={() => { setSelectedAssignment(a.id); setSubmitOpen(true); }}>Submit</Button>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </TabsContent>
        ))}
      </Tabs>

      <Dialog open={submitOpen} onOpenChange={setSubmitOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Submit Assignment</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="border-2 border-dashed rounded-lg p-8 text-center text-muted-foreground">
              <Upload className="h-8 w-8 mx-auto mb-2 opacity-50" />
              <p className="text-sm">Drag & drop your file here or click to browse</p>
              <p className="text-xs mt-1">PDF, DOC, DOCX up to 10MB</p>
            </div>
            <Textarea placeholder="Add a comment (optional)..." rows={3} value={draftText} onChange={(e) => setDraftText(e.target.value)} />
            <AiWritingHelper text={draftText} task_type="ielts_writing" />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setSubmitOpen(false)}>Cancel</Button>
            <Button onClick={handleSubmit}>Submit</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
