"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { ConversationDetailModal } from "./ConversationDetailModal";

interface ConversationMessage {
  id: string;
  role: "user" | "assistant";
  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[];
}

interface WhatsAppConversationsPanelProps {
  organizationId?: string;
  isStaff?: boolean;
}

export function WhatsAppConversationsPanel({
  organizationId,
  isStaff: _isStaff = false,
}: WhatsAppConversationsPanelProps) {
  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: "",
  });

  // Fetch conversations
  const fetchConversations = useCallback(async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();
      if (organizationId) params.append("organizationId", organizationId);
      if (filters.language !== "all")
        params.append("language", filters.language);
      if (filters.status !== "all") params.append("status", filters.status);

      const response = await fetch(
        `/api/staff/whatsapp-conversations?${params}`,
      );
      const data = await response.json();

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

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

  // Filter conversations
  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, Conversation[]> = {};

    filteredConversations.forEach((conv) => {
      const date = new Date(conv.lastMessageAt || conv.createdAt);
      const dateKey = date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });

      if (!groups[dateKey]) {
        groups[dateKey] = [];
      }
      groups[dateKey].push(conv);
    });

    return Object.entries(groups).sort((a, b) => {
      return new Date(b[0]).getTime() - new Date(a[0]).getTime();
    });
  }, [filteredConversations]);

  // 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">
          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">
              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">
              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">
              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">
              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="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">All Languages</option>
              <option value="en">English</option>
              <option value="ar">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">All Status</option>
              <option value="active">Active</option>
              <option value="closed">Closed</option>
              <option value="archived">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"
        >
          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">
            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">
            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>
                        </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("en-US", {
                            hour: "2-digit",
                            minute: "2-digit",
                          })}
                        </div>
                        <div className="text-xs text-gray-400 dark:text-gray-600 mt-1">
                          {conv.messageCount} messages
                        </div>
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

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