import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Plus, Megaphone, Loader2, Send } from "lucide-react";
import { useAnnouncements, useCreateAnnouncement, usePublishAnnouncement, useCourses } from "@/hooks/queries";
import { useToast } from "@/hooks/use-toast";
import type { Announcement } from "@/types/communication";

const priorityColors: Record<Announcement["priority"], string> = {
  urgent: "destructive",
  important: "default",
  normal: "secondary",
};

export default function TeacherAnnouncements() {
  const { toast } = useToast();
  const { data: announcements = [], isLoading } = useAnnouncements();
  const { data: coursesData } = useCourses();
  const courses = coursesData?.results ?? [];
  const createAnnouncement = useCreateAnnouncement();
  const publishAnnouncement = usePublishAnnouncement();

  const [showCreate, setShowCreate] = useState(false);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [courseId, setCourseId] = useState<string>("");
  const [priority, setPriority] = useState<Announcement["priority"]>("normal");
  const [sendEmail, setSendEmail] = useState(false);

  const resetForm = () => { setTitle(""); setContent(""); setCourseId(""); setPriority("normal"); setSendEmail(false); };

  const handleCreate = () => {
    createAnnouncement.mutate(
      { title, content, course_id: courseId ? Number(courseId) : undefined, priority, send_email: sendEmail },
      {
        onSuccess: () => { toast({ title: "Announcement Created" }); setShowCreate(false); resetForm(); },
        onError: () => toast({ title: "Error", description: "Failed to create announcement", variant: "destructive" }),
      },
    );
  };

  const handlePublish = (id: number) => {
    publishAnnouncement.mutate(id, {
      onSuccess: () => toast({ title: "Announcement Published" }),
      onError: () => toast({ title: "Error", description: "Failed to publish announcement", variant: "destructive" }),
    });
  };

  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>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Announcements</h1>
          <p className="text-muted-foreground">Create and manage announcements for your courses.</p>
        </div>
        <Dialog open={showCreate} onOpenChange={setShowCreate}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> Create Announcement</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>New Announcement</DialogTitle></DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Title</Label>
                <Input placeholder="Announcement title" value={title} onChange={e => setTitle(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Content</Label>
                <Textarea placeholder="Write your announcement..." rows={4} value={content} onChange={e => setContent(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Course</Label>
                <Select value={courseId} onValueChange={setCourseId}>
                  <SelectTrigger><SelectValue placeholder="All courses" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Courses</SelectItem>
                    {courses.map(c => (
                      <SelectItem key={c.id} value={String(c.id)}>{c.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Priority</Label>
                <Select value={priority} onValueChange={v => setPriority(v as Announcement["priority"])}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="normal">Normal</SelectItem>
                    <SelectItem value="important">Important</SelectItem>
                    <SelectItem value="urgent">Urgent</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center gap-2">
                <Checkbox id="send-email" checked={sendEmail} onCheckedChange={v => setSendEmail(!!v)} />
                <Label htmlFor="send-email">Send email notification</Label>
              </div>
              <Button className="w-full" onClick={handleCreate} disabled={createAnnouncement.isPending || !title || !content}>
                {createAnnouncement.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <div className="space-y-3">
        {announcements.map(a => (
          <Card key={a.id}>
            <CardContent className="flex items-center gap-4 py-4">
              <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
                <Megaphone className="h-5 w-5 text-primary" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="font-medium truncate">{a.title}</span>
                  <Badge variant={priorityColors[a.priority] as "default" | "secondary" | "destructive"}>{a.priority}</Badge>
                  {a.is_published && <Badge variant="outline">Published</Badge>}
                </div>
                <p className="text-sm text-muted-foreground line-clamp-1 mt-0.5">{a.content}</p>
                <div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
                  {a.course_name && <span>{a.course_name}</span>}
                  {a.published_at && <span>· {new Date(a.published_at).toLocaleDateString()}</span>}
                </div>
              </div>
              {!a.is_published && (
                <Button size="sm" onClick={() => handlePublish(a.id)} disabled={publishAnnouncement.isPending}>
                  {publishAnnouncement.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="mr-2 h-4 w-4" />}
                  Publish
                </Button>
              )}
            </CardContent>
          </Card>
        ))}
        {announcements.length === 0 && (
          <Card>
            <CardContent className="py-12 text-center text-muted-foreground">
              <Megaphone className="h-12 w-12 mx-auto mb-3 opacity-40" />
              <p>No announcements yet.</p>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
