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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Mail, Send, Loader2, Inbox, PenSquare } from "lucide-react";
import { useMessages, useSentMessages, useUnreadMessageCount, useSendMessage } from "@/hooks/queries";
import { communicationService } from "@/services/communication.service";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import type { Message } from "@/types/communication";

export default function StudentMessages() {
  const { toast } = useToast();
  const qc = useQueryClient();
  const { data: inboxData, isLoading: li } = useMessages();
  const { data: sentData, isLoading: ls } = useSentMessages();
  const { data: unreadData } = useUnreadMessageCount();
  const sendMessage = useSendMessage();

  const inbox = inboxData?.results ?? [];
  const sent = sentData?.results ?? [];
  const unreadCount = unreadData?.count ?? 0;

  const [showCompose, setShowCompose] = useState(false);
  const [recipientId, setRecipientId] = useState("");
  const [subject, setSubject] = useState("");
  const [content, setContent] = useState("");

  const [selectedMessage, setSelectedMessage] = useState<Message | null>(null);
  const [showDetail, setShowDetail] = useState(false);

  const markRead = useMutation({
    mutationFn: (id: number) => communicationService.getMessage(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["messages"] });
      qc.invalidateQueries({ queryKey: ["messages", "unread-count"] });
    },
  });

  const handleOpenMessage = (msg: Message) => {
    setSelectedMessage(msg);
    setShowDetail(true);
    if (!msg.is_read) markRead.mutate(msg.id);
  };

  const handleSend = () => {
    sendMessage.mutate(
      { recipient_id: Number(recipientId), subject, content },
      {
        onSuccess: () => { toast({ title: "Message Sent" }); setShowCompose(false); setRecipientId(""); setSubject(""); setContent(""); },
        onError: () => toast({ title: "Error", description: "Failed to send message", variant: "destructive" }),
      },
    );
  };

  if (li || ls) 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">Messages</h1>
          <p className="text-muted-foreground">Communicate with your classmates and teachers.</p>
        </div>
        <Button onClick={() => setShowCompose(true)}>
          <PenSquare className="mr-2 h-4 w-4" /> New Message
        </Button>
      </div>

      <Tabs defaultValue="inbox">
        <TabsList>
          <TabsTrigger value="inbox" className="gap-2">
            <Inbox className="h-4 w-4" /> Inbox
            {unreadCount > 0 && <Badge variant="destructive" className="ml-1 text-xs px-1.5">{unreadCount}</Badge>}
          </TabsTrigger>
          <TabsTrigger value="sent" className="gap-2">
            <Send className="h-4 w-4" /> Sent
          </TabsTrigger>
        </TabsList>
        <TabsContent value="inbox" className="space-y-2 mt-4">
          {inbox.map(msg => (
            <Card key={msg.id} className={`cursor-pointer hover:shadow-sm transition-shadow ${!msg.is_read ? "border-primary/30 bg-primary/5" : ""}`} onClick={() => handleOpenMessage(msg)}>
              <CardContent className="flex items-center gap-4 py-3">
                <Mail className={`h-5 w-5 shrink-0 ${!msg.is_read ? "text-primary" : "text-muted-foreground"}`} />
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className={`text-sm truncate ${!msg.is_read ? "font-semibold" : ""}`}>{msg.subject}</span>
                    {!msg.is_read && <Badge variant="default" className="text-xs">New</Badge>}
                  </div>
                  <p className="text-xs text-muted-foreground mt-0.5">From: {msg.sender_name}</p>
                </div>
                <span className="text-xs text-muted-foreground shrink-0">{new Date(msg.created_at).toLocaleDateString()}</span>
              </CardContent>
            </Card>
          ))}
          {inbox.length === 0 && (
            <Card><CardContent className="py-8 text-center text-muted-foreground">Your inbox is empty.</CardContent></Card>
          )}
        </TabsContent>
        <TabsContent value="sent" className="space-y-2 mt-4">
          {sent.map(msg => (
            <Card key={msg.id} className="cursor-pointer hover:shadow-sm transition-shadow" onClick={() => handleOpenMessage(msg)}>
              <CardContent className="flex items-center gap-4 py-3">
                <Send className="h-5 w-5 shrink-0 text-muted-foreground" />
                <div className="flex-1 min-w-0">
                  <span className="text-sm truncate">{msg.subject}</span>
                  <p className="text-xs text-muted-foreground mt-0.5">To: {msg.recipient_name}</p>
                </div>
                <span className="text-xs text-muted-foreground shrink-0">{new Date(msg.created_at).toLocaleDateString()}</span>
              </CardContent>
            </Card>
          ))}
          {sent.length === 0 && (
            <Card><CardContent className="py-8 text-center text-muted-foreground">No sent messages.</CardContent></Card>
          )}
        </TabsContent>
      </Tabs>

      <Sheet open={showDetail} onOpenChange={setShowDetail}>
        <SheetContent className="sm:max-w-lg">
          {selectedMessage && (
            <>
              <SheetHeader>
                <SheetTitle>{selectedMessage.subject}</SheetTitle>
              </SheetHeader>
              <div className="space-y-4 mt-4">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <span>From: {selectedMessage.sender_name}</span>
                  <span>·</span>
                  <span>To: {selectedMessage.recipient_name}</span>
                </div>
                <span className="text-xs text-muted-foreground">{new Date(selectedMessage.created_at).toLocaleString()}</span>
                <div className="p-4 rounded-lg border bg-muted/30 text-sm whitespace-pre-wrap">{selectedMessage.content}</div>
              </div>
            </>
          )}
        </SheetContent>
      </Sheet>

      <Dialog open={showCompose} onOpenChange={setShowCompose}>
        <DialogContent>
          <DialogHeader><DialogTitle>New Message</DialogTitle></DialogHeader>
          <div className="space-y-4 pt-4">
            <div className="space-y-2">
              <Label>Recipient ID</Label>
              <Input type="number" placeholder="Enter recipient user ID" value={recipientId} onChange={e => setRecipientId(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>Subject</Label>
              <Input placeholder="Message subject" value={subject} onChange={e => setSubject(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label>Content</Label>
              <Textarea placeholder="Write your message..." rows={4} value={content} onChange={e => setContent(e.target.value)} />
            </div>
            <Button className="w-full" onClick={handleSend} disabled={sendMessage.isPending || !recipientId || !subject || !content}>
              {sendMessage.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              <Send className="mr-2 h-4 w-4" /> Send
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
