/**
 * Conversation Viewer Component
 *
 * Displays conversation history with search, filter, and message expansion.
 * Supports multi-platform conversations (WhatsApp, Voice, Social Media).
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import {
  MessageSquare,
  Phone,
  Share2,
  ChevronDown,
  ChevronUp,
  Search,
} from "lucide-react";

interface ConversationMessage {
  role: "user" | "agent" | "system";
  content: string;
  timestamp: string;
  metadata?: Record<string, any>;
}

interface Conversation {
  id: string;
  platform: "whatsapp" | "voice" | "social";
  customerPhone?: string;
  customerName?: string;
  messages: string; // JSON string
  status: "open" | "resolved" | "archived";
  createdAt: string;
  updatedAt: string;
}

interface ConversationViewerProps {
  userId: string;
  lang?: string;
}

// Platform configuration
const PLATFORMS = {
  whatsapp: {
    name: { en: "WhatsApp", ar: "واتساب" },
    icon: MessageSquare,
    color: "emerald",
    bgColor: "bg-emerald-50",
    borderColor: "border-emerald-200",
    textColor: "text-emerald-700",
    iconBg: "bg-emerald-100",
  },
  voice: {
    name: { en: "Voice", ar: "مكالمة صوتية" },
    icon: Phone,
    color: "blue",
    bgColor: "bg-blue-50",
    borderColor: "border-blue-200",
    textColor: "text-blue-700",
    iconBg: "bg-blue-100",
  },
  social: {
    name: { en: "Social Media", ar: "وسائل التواصل" },
    icon: Share2,
    color: "purple",
    bgColor: "bg-purple-50",
    borderColor: "border-purple-200",
    textColor: "text-purple-700",
    iconBg: "bg-purple-100",
  },
};

// Status configuration
const STATUSES = {
  open: {
    en: "Open",
    ar: "مفتوح",
    color: "bg-amber-100 text-amber-700 border-amber-200",
  },
  resolved: {
    en: "Resolved",
    ar: "محلول",
    color: "bg-emerald-100 text-emerald-700 border-emerald-200",
  },
  archived: {
    en: "Archived",
    ar: "مؤرشف",
    color: "bg-slate-100 text-slate-700 border-slate-200",
  },
};

export default function ConversationViewer({
  userId,
  lang = "en",
}: ConversationViewerProps) {
  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";

  // State
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [platformFilter, setPlatformFilter] = useState<string>("");
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
  const [offset, setOffset] = useState(0);
  const [hasMore, setHasMore] = useState(false);
  const limit = 20;

  // Fetch conversations
  const fetchConversations = useCallback(
    async (reset: boolean = false) => {
      try {
        setLoading(true);

        const params = new URLSearchParams();
        if (platformFilter) params.append("platform", platformFilter);
        if (statusFilter) params.append("status", statusFilter);
        params.append("limit", String(limit));
        params.append("offset", String(reset ? 0 : offset));

        const response = await fetch(
          `/api/dashboard/conversations?${params.toString()}`,
        );

        if (!response.ok) {
          throw new Error("Failed to fetch conversations");
        }

        const data = await response.json();

        if (reset) {
          setConversations(data.conversations);
          setOffset(0);
        } else {
          setConversations((prev) => [...prev, ...data.conversations]);
        }

        setHasMore(data.pagination.hasMore);
        setOffset((prev) =>
          reset ? data.pagination.limit : prev + data.pagination.count,
        );
      } catch (error) {
        console.error("Failed to fetch conversations:", error);
      } finally {
        setLoading(false);
      }
    },
    [platformFilter, statusFilter, offset],
  );

  // Initial load
  useEffect(() => {
    fetchConversations(true);
  }, [platformFilter, statusFilter]);

  // Toggle expand/collapse
  const toggleExpand = (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  // Parse messages
  const parseMessages = (messagesJson: string): ConversationMessage[] => {
    try {
      return JSON.parse(messagesJson);
    } catch {
      return [];
    }
  };

  // Filter conversations by search query
  const filteredConversations = conversations.filter((conv) => {
    if (!searchQuery.trim()) return true;

    const query = searchQuery.toLowerCase();
    const name = (conv.customerName || "").toLowerCase();
    const phone = (conv.customerPhone || "").toLowerCase();

    // Search in messages
    const messages = parseMessages(conv.messages);
    const contentMatch = messages.some((msg) =>
      msg.content.toLowerCase().includes(query),
    );

    return name.includes(query) || phone.includes(query) || contentMatch;
  });

  // Format timestamp
  const formatTimestamp = (timestamp: string): string => {
    const date = new Date(timestamp);
    const locale = isAr ? "ar-SA" : "en-US";

    const today = new Date();
    const isToday = date.toDateString() === today.toDateString();

    if (isToday) {
      return date.toLocaleTimeString(locale, {
        hour: "2-digit",
        minute: "2-digit",
      });
    }

    return date.toLocaleDateString(locale, {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  // Load more
  const handleLoadMore = () => {
    fetchConversations(false);
  };

  return (
    <div className="space-y-6" dir={dir}>
      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-slate-900">
          {isAr ? "المحادثات" : "Conversations"}
        </h2>
        <p className="text-sm text-slate-600 mt-1">
          {isAr
            ? "عرض وإدارة محادثات العملاء عبر جميع المنصات"
            : "View and manage customer conversations across all platforms"}
        </p>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        {/* Search */}
        <div className="flex-1 relative">
          <Search
            className={`absolute top-1/2 -translate-y-1/2 ${isAr ? "right-3" : "left-3"} h-5 w-5 text-slate-400`}
          />
          <input
            type="text"
            placeholder={
              isAr
                ? "البحث بالاسم، الهاتف، أو المحتوى..."
                : "Search by name, phone, or content..."
            }
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className={`w-full ${isAr ? "pr-10 pl-4" : "pl-10 pr-4"} py-2.5 rounded-lg border border-slate-300 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 outline-none transition-all text-start`}
            dir={dir}
          />
        </div>

        {/* Platform Filter */}
        <select
          value={platformFilter}
          onChange={(e) => setPlatformFilter(e.target.value)}
          className="px-4 py-2.5 rounded-lg border border-slate-300 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 outline-none transition-all bg-white text-slate-900"
          dir={dir}
        >
          <option value="">{isAr ? "جميع المنصات" : "All Platforms"}</option>
          <option value="whatsapp">{isAr ? "واتساب" : "WhatsApp"}</option>
          <option value="voice">{isAr ? "مكالمة صوتية" : "Voice"}</option>
          <option value="social">
            {isAr ? "وسائل التواصل" : "Social Media"}
          </option>
        </select>

        {/* Status Filter */}
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="px-4 py-2.5 rounded-lg border border-slate-300 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 outline-none transition-all bg-white text-slate-900"
          dir={dir}
        >
          <option value="">{isAr ? "جميع الحالات" : "All Statuses"}</option>
          <option value="open">{isAr ? "مفتوح" : "Open"}</option>
          <option value="resolved">{isAr ? "محلول" : "Resolved"}</option>
          <option value="archived">{isAr ? "مؤرشف" : "Archived"}</option>
        </select>
      </div>

      {/* Loading Skeleton */}
      {loading && conversations.length === 0 && <ConversationsSkeleton />}

      {/* Conversations List */}
      {!loading && filteredConversations.length === 0 && (
        <div className="text-center py-16 rounded-xl border-2 border-dashed border-slate-200 bg-slate-50">
          <MessageSquare className="h-16 w-16 text-slate-300 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-slate-900 mb-2">
            {isAr ? "لا توجد محادثات" : "No conversations found"}
          </h3>
          <p className="text-sm text-slate-600">
            {searchQuery.trim()
              ? isAr
                ? "جرب تغيير مصطلح البحث أو الفلاتر"
                : "Try adjusting your search or filters"
              : isAr
                ? "ستظهر المحادثات هنا عند بدئها"
                : "Conversations will appear here when they start"}
          </p>
        </div>
      )}

      <div className="space-y-4">
        {filteredConversations.map((conversation) => {
          const isExpanded = expandedIds.has(conversation.id);
          const messages = parseMessages(conversation.messages);
          const firstMessage = messages[0];
          const platform = PLATFORMS[conversation.platform];
          const status = STATUSES[conversation.status];
          const Icon = platform.icon;

          return (
            <div
              key={conversation.id}
              className={`rounded-xl border-2 ${platform.borderColor} ${platform.bgColor} overflow-hidden transition-all hover:shadow-md`}
            >
              {/* Header */}
              <div className="p-4 bg-white border-b-2 border-slate-100">
                <div className="flex items-start justify-between gap-3">
                  {/* Platform Icon & Customer Info */}
                  <div className="flex items-start gap-3 flex-1 min-w-0">
                    <div
                      className={`${platform.iconBg} ${platform.textColor} p-3 rounded-lg flex-shrink-0`}
                    >
                      <Icon className="h-5 w-5" />
                    </div>

                    <div className="flex-1 min-w-0">
                      <h3 className="font-semibold text-slate-900 truncate text-start">
                        {conversation.customerName ||
                          (isAr ? "عميل غير معروف" : "Unknown Customer")}
                      </h3>
                      {conversation.customerPhone && (
                        <p
                          className="text-sm text-slate-600 truncate text-start"
                          dir="ltr"
                        >
                          {conversation.customerPhone}
                        </p>
                      )}
                      <div className="flex items-center gap-2 mt-1 flex-wrap">
                        <span
                          className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-semibold border ${status.color}`}
                        >
                          {isAr ? status.ar : status.en}
                        </span>
                        <span className="text-xs text-slate-500">
                          {formatTimestamp(conversation.createdAt)}
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* Expand/Collapse Button */}
                  <button
                    onClick={() => toggleExpand(conversation.id)}
                    className="flex-shrink-0 p-2 hover:bg-slate-100 rounded-lg transition-colors"
                    aria-label={
                      isExpanded
                        ? isAr
                          ? "طي"
                          : "Collapse"
                        : isAr
                          ? "توسيع"
                          : "Expand"
                    }
                  >
                    {isExpanded ? (
                      <ChevronUp className="h-5 w-5 text-slate-600" />
                    ) : (
                      <ChevronDown className="h-5 w-5 text-slate-600" />
                    )}
                  </button>
                </div>

                {/* Preview (when collapsed) */}
                {!isExpanded && firstMessage && (
                  <div className="mt-3 pt-3 border-t border-slate-100">
                    <p className="text-sm text-slate-600 line-clamp-2 text-start">
                      <span className="font-medium">
                        {firstMessage.role === "user"
                          ? isAr
                            ? "عميل:"
                            : "Customer:"
                          : isAr
                            ? "وكيل:"
                            : "Agent:"}
                      </span>{" "}
                      {firstMessage.content}
                    </p>
                  </div>
                )}
              </div>

              {/* Expanded Messages */}
              {isExpanded && (
                <div className="p-4 space-y-3 bg-white max-h-96 overflow-y-auto">
                  {messages.length === 0 ? (
                    <p className="text-sm text-slate-500 text-center py-4">
                      {isAr ? "لا توجد رسائل" : "No messages"}
                    </p>
                  ) : (
                    messages.map((message, index) => {
                      const isUser = message.role === "user";
                      const isSystem = message.role === "system";

                      if (isSystem) {
                        return (
                          <div key={index} className="flex justify-center">
                            <div className="bg-slate-100 text-slate-600 text-xs px-3 py-1.5 rounded-full">
                              {message.content}
                            </div>
                          </div>
                        );
                      }

                      return (
                        <div
                          key={index}
                          className={`flex ${isUser ? "justify-start" : "justify-end"}`}
                        >
                          <div
                            className={`max-w-[75%] rounded-2xl px-4 py-2.5 ${
                              isUser
                                ? "bg-slate-100 text-slate-900"
                                : "bg-brand-green text-white"
                            }`}
                          >
                            <p className="text-sm text-start whitespace-pre-wrap break-words">
                              {message.content}
                            </p>
                            <p
                              className={`text-xs mt-1 ${
                                isUser ? "text-slate-500" : "text-white/80"
                              } text-start`}
                            >
                              {formatTimestamp(message.timestamp)}
                            </p>
                          </div>
                        </div>
                      );
                    })
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Load More Button */}
      {hasMore && !loading && (
        <div className="text-center pt-4">
          <button
            onClick={handleLoadMore}
            className="px-6 py-2.5 bg-brand-green text-white rounded-lg hover:bg-brand-greenHover transition-colors font-medium"
          >
            {isAr ? "تحميل المزيد" : "Load More"}
          </button>
        </div>
      )}

      {/* Loading more indicator */}
      {loading && conversations.length > 0 && (
        <div className="text-center py-4">
          <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-brand-green border-r-transparent"></div>
        </div>
      )}
    </div>
  );
}

/**
 * Loading Skeleton Component
 */
function ConversationsSkeleton() {
  return (
    <div className="space-y-4">
      {[...Array(5)].map((_, i) => (
        <div
          key={i}
          className="rounded-xl border-2 border-slate-200 bg-white overflow-hidden animate-pulse"
        >
          <div className="p-4">
            <div className="flex items-start gap-3">
              <div className="h-12 w-12 bg-slate-200 rounded-lg"></div>
              <div className="flex-1 space-y-2">
                <div className="h-5 bg-slate-200 rounded w-1/3"></div>
                <div className="h-4 bg-slate-200 rounded w-1/4"></div>
                <div className="flex gap-2 mt-2">
                  <div className="h-6 bg-slate-200 rounded-full w-16"></div>
                  <div className="h-6 bg-slate-200 rounded w-20"></div>
                </div>
              </div>
            </div>
            <div className="mt-3 pt-3 border-t border-slate-100">
              <div className="h-4 bg-slate-200 rounded w-full"></div>
              <div className="h-4 bg-slate-200 rounded w-3/4 mt-2"></div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
