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 { useCourseAssignments } from "@/hooks/queries";
import { Upload, ClipboardList } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import AiWritingHelper from "@/components/ai/AiWritingHelper";
import AiTipBanner from "@/components/ai/AiTipBanner";
import type { CourseAssignment } from "@/types";

export default function StudentAssignments() {
  const [submitOpen, setSubmitOpen] = useState(false);
  const [selectedAssignment, setSelectedAssignment] = useState<number | null>(null);
  const [draftText, setDraftText] = useState("");
  const { toast } = useToast();
  const { data: assignmentsData, isLoading } = useCourseAssignments();
  const assignments: CourseAssignment[] = 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);
    setSelectedAssignment(null);
    toast({ title: "Assignment Submitted", description: "Your work has been submitted successfully." });
  };

  const stateVariant = (s: string) => s === "finish" ? "default" : s === "cancel" ? "destructive" : "secondary";
  const stateLabel = (s: string) => s === "publish" ? "Active" : s === "finish" ? "Completed" : s === "cancel" ? "Cancelled" : "Draft";

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

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

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

      <Tabs defaultValue="all">
        <TabsList>
          <TabsTrigger value="all">All ({assignments.length})</TabsTrigger>
          <TabsTrigger value="publish">Active ({stateFilter("publish").length})</TabsTrigger>
          <TabsTrigger value="finish">Completed ({stateFilter("finish").length})</TabsTrigger>
        </TabsList>

        {["all", "publish", "finish"].map(tab => (
          <TabsContent key={tab} value={tab} className="mt-4 space-y-3">
            {stateFilter(tab).length === 0 ? (
              <div className="text-center py-8">
                <ClipboardList className="h-10 w-10 text-muted-foreground mx-auto mb-3" />
                <p className="text-muted-foreground text-sm">No assignments found.</p>
              </div>
            ) : stateFilter(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.name}</p>
                      <p className="text-xs text-muted-foreground">
                        {a.course_name} · Due: {a.submission_date}
                      </p>
                      <p className="text-xs text-muted-foreground mt-0.5">
                        Marks: {a.marks} · {a.assignment_type_name}
                      </p>
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <Badge variant={stateVariant(a.state)}>{stateLabel(a.state)}</Badge>
                      {a.state === "publish" && (
                        <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>
  );
}
