"use client";

import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import { ConversationDetailModal } from "@/components/dashboard/ConversationDetailModal";
import type { Lang } from "@/lib/config";

interface ConversationMessage {
  id: string;
  role: "user" | "assistant" | "staff";
  content: string;
  language: string;
  intent: string | null;
  toolsUsed: string[];
  metadata: Record<string, unknown> | null;
  timestamp: Date;
}

interface Conversation {
  id: string;
  organizationId: string;
  userPhone: string;
  userName: string | null;
  language: string;
  status: string;
  lastMessageAt: Date | null;
  messageCount: number;
  createdAt: Date;
  messages: ConversationMessage[];
  humanControlled: boolean;
  humanControlledAt: string | null;
  humanControlledBy: string | null;
}

interface WhatsAppInboxProps {
  lang: Lang;
  organizationId: string;
}

const API_BASE = "/api/dashboard/whatsapp-conversations";

export default function WhatsAppInbox({
  lang,
  organizationId: _organizationId,
}: WhatsAppInboxProps) {
  const isAr = lang === "ar";
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedConversation, setSelectedConversation] =
    useState<Conversation | null>(null);
  const [filters, setFilters] = useState({
    language: "all",
    status: "all",
    search: "",
  });
  const lastPollTimestamp = useRef<string>(new Date().toISOString());

  // Fetch conversations from dashboard API (auth resolves org server-side)
  const fetchConversations = useCallback(async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();
      if (filters.language !== "all")
        params.append("language", filters.language);
      if (filters.status !== "all") params.append("status", filters.status);

      const response = await fetch(`${API_BASE}?${params}`);
      const data = await response.json();

      if (data.success) {
        setConversations(data.data.conversations);
        lastPollTimestamp.current = new Date().toISOString();
      }
    } catch (error) {
      console.error("Failed to fetch conversations:", error);
    } finally {
      setLoading(false);
    }
  }, [filters.language, filters.status]);

  // Load conversations on mount
  useEffect(() => {
    fetchConversations();
  }, [fetchConversations]);

  // Auto-poll every 10 seconds
  useEffect(() => {
    const interval = setInterval(async () => {
      try {
        const params = new URLSearchParams();
        params.append("since", lastPollTimestamp.current);

        const response = await fetch(`${API_BASE}/poll?${params}`);
        const data = await response.json();

        if (data.success && data.data?.conversations?.length > 0) {
          lastPollTimestamp.current = new Date().toISOString();
          setConversations((prev) => {
            const updated = [...prev];
            for (const incoming of data.data.conversations) {
              const idx = updated.findIndex((c) => c.id === incoming.id);
              if (idx >= 0) {
                updated[idx] = incoming;
              } else {
                updated.unshift(incoming);
              }
            }
            return updated;
          });
        }
      } catch {
        /* silent polling failure */
      }
    }, 10000);

    return () => clearInterval(interval);
  }, []);

  // Handle conversation updates from the detail modal
  const handleConversationUpdate = useCallback((updated: Conversation) => {
    setConversations((prev) =>
      prev.map((c) => (c.id === updated.id ? updated : c)),
    );
    setSelectedConversation(updated);
  }, []);

  // Filter conversations by search
  const filteredConversations = useMemo(() => {
    return conversations.filter((conv) => {
      if (filters.search) {
        const searchLower = filters.search.toLowerCase();
        return (
          conv.userPhone.includes(searchLower) ||
          conv.userName?.toLowerCase().includes(searchLower)
        );
      }
      return true;
    });
  }, [conversations, filters.search]);

  // Group by date
  const groupedConversations = useMemo(() => {
    const groups: Record<
      string,
      { label: string; convs: Conversation[]; sortTs: number }
    > = {};

    filteredConversations.forEach((conv) => {
      const date = new Date(conv.lastMessageAt || conv.createdAt);
      // Use ISO date as key for reliable sorting, locale string as display label
      const sortKey = date.toISOString().slice(0, 10);
      const label = date.toLocaleDateString(isAr ? "ar-SA" : "en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });

      if (!groups[sortKey]) {
        groups[sortKey] = { label, convs: [], sortTs: date.getTime() };
      }
      groups[sortKey].convs.push(conv);
    });

    return Object.values(groups)
      .sort((a, b) => b.sortTs - a.sortTs)
      .map(({ label, convs }) => [label, convs] as [string, Conversation[]]);
  }, [filteredConversations, isAr]);

  // Stats
  const stats = useMemo(() => {
    return {
      total: conversations.length,
      active: conversations.filter((c) => c.status === "active").length,
      english: conversations.filter((c) => c.language === "en").length,
      arabic: conversations.filter((c) => c.language === "ar").length,
    };
  }, [conversations]);

  return (
    <div className="space-y-6">
      {/* Header with Stats */}
      <div>
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
          {isAr ? "محادثات واتساب" : "WhatsApp Conversations"}
        </h2>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700">
            <div className="text-sm text-gray-600 dark:text-gray-400">
              {isAr ? "إجمالي المحادثات" : "Total Conversations"}
            </div>
            <div className="text-2xl font-bold text-gray-900 dark:text-white">
              {stats.total}
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700">
            <div className="text-sm text-gray-600 dark:text-gray-400">
              {isAr ? "نشطة" : "Active"}
            </div>
            <div className="text-2xl font-bold text-green-600">
              {stats.active}
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700">
            <div className="text-sm text-gray-600 dark:text-gray-400">
              {isAr ? "إنجليزي" : "English"}
            </div>
            <div className="text-2xl font-bold text-blue-600">
              {stats.english}
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700">
            <div className="text-sm text-gray-600 dark:text-gray-400">
              {isAr ? "عربي" : "Arabic"}
            </div>
            <div className="text-2xl font-bold text-purple-600">
              {stats.arabic}
            </div>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {/* Search */}
          <div>
            <input
              type="text"
              placeholder={
                isAr ? "بحث بالهاتف أو الاسم..." : "Search by phone or name..."
              }
              value={filters.search}
              onChange={(e) =>
                setFilters({ ...filters, search: e.target.value })
              }
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            />
          </div>

          {/* Language Filter */}
          <div>
            <select
              value={filters.language}
              onChange={(e) =>
                setFilters({ ...filters, language: e.target.value })
              }
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            >
              <option value="all">
                {isAr ? "جميع اللغات" : "All Languages"}
              </option>
              <option value="en">{isAr ? "إنجليزي" : "English"}</option>
              <option value="ar">{isAr ? "عربي" : "Arabic"}</option>
            </select>
          </div>

          {/* Status Filter */}
          <div>
            <select
              value={filters.status}
              onChange={(e) =>
                setFilters({ ...filters, status: e.target.value })
              }
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            >
              <option value="all">
                {isAr ? "جميع الحالات" : "All Status"}
              </option>
              <option value="active">{isAr ? "نشط" : "Active"}</option>
              <option value="closed">{isAr ? "مغلق" : "Closed"}</option>
              <option value="archived">{isAr ? "مؤرشف" : "Archived"}</option>
            </select>
          </div>
        </div>

        <button
          onClick={fetchConversations}
          className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          {isAr ? "تحديث" : "Refresh"}
        </button>
      </div>

      {/* Conversations List */}
      {loading ? (
        <div className="text-center py-12">
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-gray-300 border-t-blue-600"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">
            {isAr ? "جاري تحميل المحادثات..." : "Loading conversations..."}
          </p>
        </div>
      ) : filteredConversations.length === 0 ? (
        <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
          <p className="text-gray-600 dark:text-gray-400">
            {isAr ? "لا توجد محادثات" : "No conversations found"}
          </p>
        </div>
      ) : (
        <div className="space-y-6">
          {groupedConversations.map(([date, convs]) => (
            <div key={date}>
              <h3 className="text-lg font-semibold text-gray-700 dark:text-gray-300 mb-3">
                {date}
              </h3>
              <div className="space-y-2">
                {convs.map((conv) => (
                  <button
                    key={conv.id}
                    onClick={() => setSelectedConversation(conv)}
                    className="w-full text-left bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-blue-500 dark:hover:border-blue-400 transition-colors"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-3">
                          <span className="font-semibold text-gray-900 dark:text-white">
                            {conv.userName || conv.userPhone}
                          </span>
                          <span className="text-xs px-2 py-1 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400">
                            {conv.language.toUpperCase()}
                          </span>
                          <span
                            className={`text-xs px-2 py-1 rounded-full ${
                              conv.status === "active"
                                ? "bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300"
                                : "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300"
                            }`}
                          >
                            {conv.status}
                          </span>
                          {conv.humanControlled && (
                            <span className="text-xs px-2 py-0.5 rounded-full bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300">
                              {isAr ? "أنت تتعامل" : "You\u0027re handling"}
                            </span>
                          )}
                        </div>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                          {conv.userPhone}
                        </p>
                        {conv.messages.length > 0 && (
                          <p className="text-sm text-gray-500 dark:text-gray-500 mt-2 line-clamp-1">
                            {conv.messages[conv.messages.length - 1].content}
                          </p>
                        )}
                      </div>
                      <div className="text-right ml-4">
                        <div className="text-xs text-gray-500 dark:text-gray-500">
                          {new Date(
                            conv.lastMessageAt || conv.createdAt,
                          ).toLocaleTimeString(isAr ? "ar-SA" : "en-US", {
                            hour: "2-digit",
                            minute: "2-digit",
                          })}
                        </div>
                        <div className="text-xs text-gray-400 dark:text-gray-600 mt-1">
                          {conv.messageCount} {isAr ? "رسالة" : "messages"}
                        </div>
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Conversation Detail Modal */}
      {selectedConversation && (
        <ConversationDetailModal
          conversation={selectedConversation}
          onClose={() => setSelectedConversation(null)}
          onConversationUpdate={handleConversationUpdate}
          apiBasePath={API_BASE}
        />
      )}
    </div>
  );
}
