import { useState, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "wouter";
import {
  useListConversations,
  getListConversationsQueryKey,
  useListMessages,
  getListMessagesQueryKey,
  useSendMessage,
  useMarkConversationRead,
  useCreateConversation,
} from "@workspace/api-client-react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/contexts/AuthContext";
import { io } from "socket.io-client";
import { ArrowRight, ArrowLeft, MessageCircle, Plus, Send } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";

const BASE = import.meta.env.BASE_URL.replace(/\/$/, "");

function getSocket() {
  return io(window.location.origin, {
    path: `${BASE}/api/socket.io`,
  });
}

export default function ChatPage() {
  const { t, i18n } = useTranslation();
  const [, setLocation] = useLocation();
  const { user } = useAuth();
  const lang = i18n.language;
  const isRtl = lang === "ar";
  const queryClient = useQueryClient();
  const BackIcon = isRtl ? ArrowRight : ArrowLeft;

  const [selectedConvId, setSelectedConvId] = useState<number | null>(null);
  const [messageText, setMessageText] = useState("");
  const [showNewConv, setShowNewConv] = useState(false);
  const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);
  const bottomRef = useRef<HTMLDivElement>(null);

  const { data: conversations, isLoading: convsLoading } = useListConversations({
    query: { queryKey: getListConversationsQueryKey() },
  });

  const { data: messages } = useListMessages(
    selectedConvId!,
    { query: { queryKey: getListMessagesQueryKey(selectedConvId!), enabled: !!selectedConvId } },
  );

  type DirectoryUser = {
    id: number;
    username: string;
    displayNameAr: string | null;
    displayNameEn: string | null;
    avatarUrl: string | null;
    isActive: boolean;
  };
  const { data: users } = useQuery<DirectoryUser[]>({
    queryKey: ["users-directory"],
    queryFn: () =>
      fetch("/api/users/directory", { credentials: "include" }).then((r) => r.json()),
    enabled: showNewConv,
  });

  const sendMessage = useSendMessage();
  const markRead = useMarkConversationRead();
  const createConv = useCreateConversation();

  // Socket.IO
  useEffect(() => {
    if (!user) return;
    const socket = getSocket();

    if (selectedConvId) {
      socket.emit("join_conversation", selectedConvId);
    }

    socket.on("new_message", () => {
      queryClient.invalidateQueries({ queryKey: getListConversationsQueryKey() });
      if (selectedConvId) {
        queryClient.invalidateQueries({ queryKey: getListMessagesQueryKey(selectedConvId) });
      }
    });

    socket.on("messages_read", () => {
      queryClient.invalidateQueries({ queryKey: getListConversationsQueryKey() });
      if (selectedConvId) {
        queryClient.invalidateQueries({ queryKey: getListMessagesQueryKey(selectedConvId) });
      }
    });

    return () => {
      if (selectedConvId) {
        socket.emit("leave_conversation", selectedConvId);
      }
      socket.disconnect();
    };
  }, [user, selectedConvId, queryClient]);

  // Mark conversation as read when selected
  useEffect(() => {
    if (selectedConvId) {
      markRead.mutate(
        { id: selectedConvId },
        {
          onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: getListConversationsQueryKey() });
          },
        },
      );
    }
  }, [selectedConvId]);

  // Scroll to bottom on new messages
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const handleSend = () => {
    if (!messageText.trim() || !selectedConvId) return;
    sendMessage.mutate(
      { id: selectedConvId, data: { content: messageText.trim() } },
      {
        onSuccess: () => {
          setMessageText("");
          queryClient.invalidateQueries({ queryKey: getListMessagesQueryKey(selectedConvId!) });
          queryClient.invalidateQueries({ queryKey: getListConversationsQueryKey() });
        },
      },
    );
  };

  const handleCreateConv = () => {
    if (!selectedUserIds.length) return;
    createConv.mutate(
      { data: { participantIds: selectedUserIds, isGroup: selectedUserIds.length > 1 } },
      {
        onSuccess: (conv) => {
          queryClient.invalidateQueries({ queryKey: getListConversationsQueryKey() });
          setSelectedConvId(conv.id);
          setShowNewConv(false);
          setSelectedUserIds([]);
        },
      },
    );
  };

  const selectedConv = conversations?.find((c) => c.id === selectedConvId);
  const convName = selectedConv
    ? (lang === "ar" ? selectedConv.nameAr : selectedConv.nameEn) ||
      selectedConv.participants
        ?.filter((p) => p.id !== user?.id)
        .map((p) => (lang === "ar" ? p.displayNameAr : p.displayNameEn) ?? p.username)
        .join(", ")
    : "";

  return (
    <div className="min-h-screen os-bg flex flex-col">
      {/* Header */}
      <div className="glass-panel border-b border-slate-200/70 px-4 py-4 flex items-center gap-3 sticky top-0 z-10">
        <button
          onClick={() => (selectedConvId ? setSelectedConvId(null) : setLocation("/"))}
          className="p-2 rounded-xl hover:bg-slate-100 text-muted-foreground hover:text-foreground transition-colors"
        >
          <BackIcon size={20} />
        </button>
        <div className="flex items-center gap-2 flex-1">
          <MessageCircle size={20} className="text-green-400" />
          <h1 className="text-lg font-semibold text-foreground">
            {selectedConvId ? convName : t("chat.title")}
          </h1>
        </div>
        {!selectedConvId && (
          <button
            onClick={() => setShowNewConv(true)}
            className="p-2 rounded-xl hover:bg-slate-100 text-muted-foreground hover:text-foreground transition-colors"
          >
            <Plus size={20} />
          </button>
        )}
      </div>

      {/* New Conversation Dialog */}
      {showNewConv && (
        <div className="fixed inset-0 bg-slate-900/30 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="glass-panel rounded-3xl p-6 w-full max-w-sm space-y-4">
            <h2 className="font-semibold text-foreground">{t("chat.createConversation")}</h2>
            <p className="text-sm text-muted-foreground">{t("chat.searchUsers")}</p>
            <ScrollArea className="h-48">
              <div className="space-y-2">
                {users?.filter((u) => u.id !== user?.id).map((u) => (
                  <label key={u.id} className="flex items-center gap-3 p-2 rounded-xl hover:bg-slate-100 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={selectedUserIds.includes(u.id)}
                      onChange={(e) => {
                        setSelectedUserIds(
                          e.target.checked
                            ? [...selectedUserIds, u.id]
                            : selectedUserIds.filter((id) => id !== u.id),
                        );
                      }}
                      className="accent-primary"
                    />
                    <Avatar className="w-8 h-8">
                      <AvatarFallback className="text-xs bg-primary/20 text-primary">
                        {u.username.slice(0, 2).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <div className="text-sm font-medium text-foreground">{u.username}</div>
                      <div className="text-xs text-muted-foreground">
                        {lang === "ar" ? u.displayNameAr : u.displayNameEn}
                      </div>
                    </div>
                  </label>
                ))}
              </div>
            </ScrollArea>
            <div className="flex gap-2">
              <Button variant="outline" className="flex-1" onClick={() => setShowNewConv(false)}>
                {t("common.cancel")}
              </Button>
              <Button
                className="flex-1"
                onClick={handleCreateConv}
                disabled={!selectedUserIds.length || createConv.isPending}
              >
                {t("common.add")}
              </Button>
            </div>
          </div>
        </div>
      )}

      {selectedConvId ? (
        /* Message View */
        <div className="flex-1 flex flex-col">
          <ScrollArea className="flex-1 p-4">
            <div className="space-y-3">
              {messages?.map((msg) => {
                const isMe = msg.senderId === user?.id;
                const senderName =
                  (lang === "ar" ? msg.sender?.displayNameAr : msg.sender?.displayNameEn) ??
                  msg.sender?.username ??
                  "";
                return (
                  <div key={msg.id} className={`flex ${isMe ? "justify-end" : "justify-start"}`}>
                    <div className={`max-w-xs lg:max-w-md ${isMe ? "" : ""}`}>
                      {!isMe && (
                        <div className="text-xs text-muted-foreground mb-1 px-1">{senderName}</div>
                      )}
                      <div
                        className={`px-4 py-2 rounded-2xl text-sm ${
                          isMe
                            ? "bg-primary text-primary-foreground rounded-ee-sm"
                            : "glass-panel rounded-es-sm"
                        }`}
                      >
                        {msg.content}
                      </div>
                      <div className="text-xs text-muted-foreground mt-1 px-1">
                        {new Date(msg.createdAt).toLocaleTimeString(lang === "ar" ? "ar-SA" : "en-US", {
                          hour: "2-digit",
                          minute: "2-digit",
                        })}
                      </div>
                    </div>
                  </div>
                );
              })}
              <div ref={bottomRef} />
            </div>
          </ScrollArea>

          {/* Message Input */}
          <div className="glass-panel border-t border-slate-200/70 p-4">
            <div className="flex gap-2">
              <Input
                value={messageText}
                onChange={(e) => setMessageText(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && (e.preventDefault(), handleSend())}
                placeholder={t("chat.typeMessage")}
                className="flex-1 bg-white/70 border-slate-200"
              />
              <Button
                onClick={handleSend}
                disabled={!messageText.trim() || sendMessage.isPending}
                size="icon"
              >
                <Send size={16} />
              </Button>
            </div>
          </div>
        </div>
      ) : (
        /* Conversation List */
        <div className="flex-1 p-4 space-y-2">
          {convsLoading ? (
            <div className="flex items-center justify-center py-20 text-muted-foreground">
              {t("common.loading")}
            </div>
          ) : !conversations?.length ? (
            <div className="flex flex-col items-center justify-center py-20 gap-3 text-muted-foreground">
              <MessageCircle size={40} className="opacity-30" />
              <span>{t("chat.noConversations")}</span>
            </div>
          ) : (
            conversations.map((conv) => {
              const name =
                (lang === "ar" ? conv.nameAr : conv.nameEn) ||
                conv.participants
                  ?.filter((p) => p.id !== user?.id)
                  .map((p) => (lang === "ar" ? p.displayNameAr : p.displayNameEn) ?? p.username)
                  .join(", ") ||
                t("chat.directMessage");

              const lastMsg = conv.lastMessage;

              return (
                <button
                  key={conv.id}
                  onClick={() => setSelectedConvId(conv.id)}
                  className="w-full glass-panel rounded-2xl p-4 flex items-center gap-3 hover:bg-slate-100 transition-colors text-start"
                >
                  <Avatar className="w-10 h-10 shrink-0">
                    <AvatarFallback className="bg-primary/20 text-primary font-medium">
                      {String(name).slice(0, 2)}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between">
                      <span className="font-medium text-foreground text-sm truncate">{name}</span>
                      {conv.unreadCount > 0 && (
                        <Badge className="bg-primary/20 text-primary border-primary/30 text-xs shrink-0">
                          {conv.unreadCount}
                        </Badge>
                      )}
                    </div>
                    {lastMsg && (
                      <p className="text-xs text-muted-foreground truncate mt-0.5">
                        {lastMsg.content}
                      </p>
                    )}
                  </div>
                </button>
              );
            })
          )}
        </div>
      )}
    </div>
  );
}
