"use client";

import { useState, useCallback } from "react";
import {
  Search,
  Send,
  Loader2,
  MessageSquare,
  RefreshCw,
  CheckCheck,
} from "lucide-react";
import type {
  InboxConversation,
  SocialMessageOutput,
} from "@/lib/types/social-media.types";
import { fetchWithCSRF } from "@/lib/csrf-client";
import PlatformIcon from "./PlatformIcon";

interface InboxViewProps {
  isAr: boolean;
  conversations: InboxConversation[];
  loading: boolean;
  onRefresh: () => Promise<void>;
}

export default function InboxView({
  isAr,
  conversations,
  loading,
  onRefresh,
}: InboxViewProps) {
  const [selectedConversation, setSelectedConversation] = useState<
    string | null
  >(null);
  const [messages, setMessages] = useState<SocialMessageOutput[]>([]);
  const [messagesLoading, setMessagesLoading] = useState(false);
  const [replyText, setReplyText] = useState("");
  const [sending, setSending] = useState(false);
  const [search, setSearch] = useState("");
  const [error, setError] = useState<string | null>(null);

  const loadMessages = useCallback(
    async (conversationId: string) => {
      setSelectedConversation(conversationId);
      setMessagesLoading(true);
      setError(null);
      try {
        const res = await fetch(`/api/social/inbox/${conversationId}`);
        if (res.ok) {
          const json = await res.json();
          setMessages(json.data || []);
        } else {
          setError(isAr ? "فشل تحميل الرسائل" : "Failed to load messages");
        }
      } catch {
        setError(isAr ? "فشل تحميل الرسائل" : "Failed to load messages");
      } finally {
        setMessagesLoading(false);
      }
    },
    [isAr],
  );

  const handleSendReply = useCallback(async () => {
    if (!selectedConversation || !replyText.trim()) return;
    setSending(true);
    setError(null);
    try {
      const res = await fetchWithCSRF(
        `/api/social/inbox/${selectedConversation}/reply`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ content: replyText }),
        },
      );
      if (res.ok) {
        setReplyText("");
        loadMessages(selectedConversation);
      } else {
        setError(isAr ? "فشل إرسال الرد" : "Failed to send reply");
      }
    } catch {
      setError(isAr ? "فشل إرسال الرد" : "Failed to send reply");
    } finally {
      setSending(false);
    }
  }, [selectedConversation, replyText, loadMessages, isAr]);

  const filtered = conversations.filter(
    (c) =>
      !search ||
      c.participantName?.toLowerCase().includes(search.toLowerCase()) ||
      c.participantHandle?.toLowerCase().includes(search.toLowerCase()) ||
      c.lastMessage?.content?.toLowerCase().includes(search.toLowerCase()),
  );

  const selectedConv = conversations.find(
    (c) => c.conversationId === selectedConversation,
  );

  return (
    <div className="flex h-[600px] bg-white rounded-2xl border border-slate-200 overflow-hidden">
      {/* Conversation list */}
      <div className="w-80 border-r border-slate-200 flex flex-col">
        <div className="p-3 border-b border-slate-100 flex items-center gap-2">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
            <input
              type="text"
              placeholder={isAr ? "بحث..." : "Search..."}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green/20"
              dir={isAr ? "rtl" : "ltr"}
            />
          </div>
          <button
            onClick={onRefresh}
            className="p-2 rounded-lg hover:bg-slate-100 transition-colors"
          >
            <RefreshCw
              className={`h-4 w-4 text-slate-500 ${loading ? "animate-spin" : ""}`}
            />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto">
          {loading && conversations.length === 0 ? (
            <div className="flex items-center justify-center h-40">
              <Loader2 className="h-6 w-6 animate-spin text-slate-400" />
            </div>
          ) : filtered.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-40 text-slate-400 text-sm">
              <MessageSquare className="h-8 w-8 mb-2" />
              {isAr ? "لا توجد محادثات" : "No conversations"}
            </div>
          ) : (
            filtered.map((conv) => (
              <button
                key={conv.conversationId}
                onClick={() => loadMessages(conv.conversationId)}
                className={`w-full px-4 py-3 text-left hover:bg-slate-50 transition-colors border-b border-slate-50 ${
                  selectedConversation === conv.conversationId
                    ? "bg-blue-50 border-l-2 border-l-blue-500"
                    : ""
                }`}
              >
                <div className="flex items-center gap-3">
                  <div className="relative">
                    {conv.participantAvatarUrl ? (
                      <img
                        src={conv.participantAvatarUrl}
                        alt=""
                        className="h-10 w-10 rounded-full object-cover"
                      />
                    ) : (
                      <div className="h-10 w-10 rounded-full bg-slate-200 flex items-center justify-center">
                        <span className="text-sm font-medium text-slate-600">
                          {conv.participantName?.[0] || "?"}
                        </span>
                      </div>
                    )}
                    <div className="absolute -bottom-0.5 -right-0.5">
                      <PlatformIcon platform={conv.platform} size="sm" />
                    </div>
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-slate-900 truncate">
                        {conv.participantName ||
                          conv.participantHandle ||
                          (isAr ? "مجهول" : "Unknown")}
                      </span>
                      {conv.unreadCount > 0 && (
                        <span className="ml-2 px-1.5 py-0.5 bg-brand-green text-white text-[10px] font-bold rounded-full min-w-[18px] text-center">
                          {conv.unreadCount}
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-slate-500 truncate mt-0.5">
                      {conv.lastMessage?.content || ""}
                    </p>
                  </div>
                </div>
              </button>
            ))
          )}
        </div>
      </div>

      {/* Message thread */}
      <div className="flex-1 flex flex-col">
        {!selectedConversation ? (
          <div className="flex-1 flex items-center justify-center text-slate-400">
            <div className="text-center">
              <MessageSquare className="h-12 w-12 mx-auto mb-3" />
              <p className="text-sm">
                {isAr
                  ? "اختر محادثة لعرض الرسائل"
                  : "Select a conversation to view messages"}
              </p>
            </div>
          </div>
        ) : (
          <>
            {/* Header */}
            <div className="px-4 py-3 border-b border-slate-200 flex items-center gap-3">
              <PlatformIcon platform={selectedConv?.platform || "FACEBOOK"} />
              <div>
                <p className="text-sm font-medium text-slate-900">
                  {selectedConv?.participantName ||
                    selectedConv?.participantHandle}
                </p>
                <p className="text-xs text-slate-500">
                  {selectedConv?.accountName}
                </p>
              </div>
            </div>

            {/* Error banner */}
            {error && (
              <div className="mx-4 mt-2 p-2 bg-red-50 border border-red-200 rounded-lg flex items-center justify-between">
                <span className="text-sm text-red-700">{error}</span>
                <button
                  onClick={() => setError(null)}
                  className="text-red-400 hover:text-red-600 text-xs ml-2"
                >
                  ✕
                </button>
              </div>
            )}

            {/* Messages */}
            <div className="flex-1 overflow-y-auto p-4 space-y-3">
              {messagesLoading ? (
                <div className="flex items-center justify-center h-40">
                  <Loader2 className="h-6 w-6 animate-spin text-slate-400" />
                </div>
              ) : (
                messages.map((msg) => (
                  <div
                    key={msg.id}
                    className={`flex ${msg.direction === "OUTBOUND" ? "justify-end" : "justify-start"}`}
                  >
                    <div
                      className={`max-w-[70%] px-4 py-2.5 rounded-2xl text-sm ${
                        msg.direction === "OUTBOUND"
                          ? "bg-brand-green text-white rounded-br-sm"
                          : "bg-slate-100 text-slate-800 rounded-bl-sm"
                      }`}
                    >
                      <p>{msg.content}</p>
                      <div
                        className={`flex items-center gap-1 mt-1 text-[10px] ${
                          msg.direction === "OUTBOUND"
                            ? "text-white/70"
                            : "text-slate-400"
                        }`}
                      >
                        <span>
                          {new Date(msg.createdAt).toLocaleTimeString(
                            isAr ? "ar-SA" : "en-US",
                            { hour: "2-digit", minute: "2-digit" },
                          )}
                        </span>
                        {msg.direction === "OUTBOUND" && msg.isRead && (
                          <CheckCheck className="h-3 w-3" />
                        )}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* Reply input */}
            <div className="px-4 py-3 border-t border-slate-200">
              <div className="flex items-center gap-2">
                <input
                  type="text"
                  value={replyText}
                  onChange={(e) => setReplyText(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && !e.shiftKey) {
                      e.preventDefault();
                      handleSendReply();
                    }
                  }}
                  placeholder={isAr ? "اكتب رداً..." : "Type a reply..."}
                  className="flex-1 px-4 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-brand-green/20"
                  dir={isAr ? "rtl" : "ltr"}
                />
                <button
                  onClick={handleSendReply}
                  disabled={!replyText.trim() || sending}
                  className="p-2.5 bg-brand-green text-white rounded-xl hover:bg-brand-green/90 disabled:opacity-50 transition-colors"
                >
                  {sending ? (
                    <Loader2 className="h-5 w-5 animate-spin" />
                  ) : (
                    <Send className={`h-5 w-5 ${isAr ? "rotate-180" : ""}`} />
                  )}
                </button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
