/**
 * WhatsApp Panel Component
 * Two-panel layout: Conversation list (left) + Transcript viewer (right)
 */

"use client";

import { useState } from "react";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";

interface WhatsAppPanelProps {
  lang: Lang;
  conversations: any[];
  integrationStatus: any;
  onRefresh: () => void;
}

export default function WhatsAppPanel({
  lang,
  conversations,
  integrationStatus,
  onRefresh,
}: WhatsAppPanelProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;
  const [selectedConversation, setSelectedConversation] = useState<any>(null);
  const [conversationDetails, setConversationDetails] = useState<any>(null);
  const [loadingDetails, setLoadingDetails] = useState(false);

  // Load full conversation details
  const loadConversationDetails = async (conversationId: string) => {
    setLoadingDetails(true);
    try {
      const response = await fetch(`/api/conversations/${conversationId}`);
      if (response.ok) {
        const data = await response.json();
        setConversationDetails(data.conversation);
      }
    } catch (error) {
      console.error("Failed to load conversation details:", error);
    } finally {
      setLoadingDetails(false);
    }
  };

  const handleSelectConversation = (conversation: any) => {
    setSelectedConversation(conversation);
    loadConversationDetails(conversation.id);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "active":
        return "bg-emerald-100 text-emerald-700";
      case "resolved":
        return "bg-slate-100 text-slate-600";
      case "escalated_to_human":
        return "bg-amber-100 text-amber-700";
      case "abandoned":
        return "bg-rose-100 text-rose-700";
      default:
        return "bg-slate-100 text-slate-600";
    }
  };

  return (
    <div className="grid gap-4 lg:grid-cols-3">
      {/* Left Panel: Conversation List */}
      <div className="lg:col-span-1">
        <div className="rounded-xl bg-white shadow-sm">
          {/* Connection Status Banner */}
          <div
            className={`rounded-t-xl p-4 ${
              integrationStatus?.connected
                ? "bg-emerald-50 border-b border-emerald-100"
                : "bg-rose-50 border-b border-rose-100"
            }`}
          >
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div
                  className={`h-2 w-2 rounded-full ${
                    integrationStatus?.connected
                      ? "bg-emerald-500"
                      : "bg-rose-500"
                  }`}
                ></div>
                <span className="text-sm font-medium text-slate-900">
                  {integrationStatus?.connected
                    ? dt.connectedStatus
                    : dt.disconnectedStatus}
                </span>
              </div>
              {integrationStatus?.phoneNumber && (
                <span className="text-xs text-slate-600">
                  {integrationStatus.phoneNumber}
                </span>
              )}
            </div>
            {integrationStatus?.n8nWorkflowId && (
              <button className="mt-2 text-xs text-brand-green hover:underline">
                {dt.viewN8nWorkflow} →
              </button>
            )}
          </div>

          {/* Search */}
          <div className="border-b border-slate-100 p-3">
            <input
              type="text"
              placeholder={dt.searchConversations}
              className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand-green focus:outline-none focus:ring-1 focus:ring-brand-green/40"
            />
          </div>

          {/* Conversation List */}
          <div className="max-h-[600px] overflow-y-auto">
            {conversations.length === 0 ? (
              <div className="flex flex-col items-center justify-center p-8 text-center">
                <p className="text-sm text-slate-500">{dt.noConversations}</p>
                <p className="mt-1 text-xs text-slate-400">
                  {dt.noConversationsDesc}
                </p>
              </div>
            ) : (
              conversations.map((conv) => (
                <div
                  key={conv.id}
                  onClick={() => handleSelectConversation(conv)}
                  className={`cursor-pointer border-b border-slate-50 p-4 transition-colors hover:bg-slate-50 ${
                    selectedConversation?.id === conv.id ? "bg-emerald-50" : ""
                  }`}
                >
                  <div className="flex items-start gap-3">
                    <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-brand-green/10 text-sm font-bold text-brand-green">
                      {conv.customerName?.charAt(0).toUpperCase() ||
                        conv.customerPhone.slice(-2)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between gap-2">
                        <p className="text-sm font-medium text-slate-900 truncate">
                          {conv.customerName || conv.customerPhone}
                        </p>
                        {conv.unreadCount > 0 && (
                          <span className="flex h-5 w-5 items-center justify-center rounded-full bg-brand-green text-xs font-bold text-white">
                            {conv.unreadCount}
                          </span>
                        )}
                      </div>
                      <p className="text-xs text-slate-500 truncate">
                        {conv.lastMessage}
                      </p>
                      <div className="mt-1 flex items-center justify-between">
                        <span
                          className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${getStatusColor(conv.status)}`}
                        >
                          {conv.status}
                        </span>
                        <span className="text-xs text-slate-400">
                          {conv.lastMessageAt
                            ? new Date(conv.lastMessageAt).toLocaleTimeString(
                                isAr ? "ar-SA" : "en-US",
                                {
                                  hour: "2-digit",
                                  minute: "2-digit",
                                },
                              )
                            : ""}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      {/* Right Panel: Conversation Details */}
      <div className="lg:col-span-2">
        <div className="rounded-xl bg-white shadow-sm">
          {!selectedConversation ? (
            <div className="flex flex-col items-center justify-center p-12 text-center">
              <div className="text-6xl opacity-20">💬</div>
              <p className="mt-4 text-sm text-slate-500">
                {isAr
                  ? "اختر محادثة لعرض التفاصيل"
                  : "Select a conversation to view details"}
              </p>
            </div>
          ) : (
            <>
              {/* Conversation Header */}
              <div className="border-b border-slate-100 p-4">
                <div className="flex items-start justify-between">
                  <div>
                    <h3 className="text-lg font-semibold text-slate-900">
                      {dt.conversationWith}{" "}
                      {selectedConversation.customerName ||
                        selectedConversation.customerPhone}
                    </h3>
                    <p className="text-sm text-slate-600">
                      {selectedConversation.customerPhone}
                    </p>
                  </div>
                  <div className="flex gap-2">
                    <button className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:border-brand-green hover:text-brand-green">
                      {dt.markAsResolved}
                    </button>
                  </div>
                </div>
              </div>

              {/* AI Summary Section */}
              {conversationDetails?.summary && (
                <div className="border-b border-slate-100 bg-emerald-50/30 p-4">
                  <h4 className="text-sm font-semibold text-slate-900">
                    {dt.conversationSummary}
                  </h4>
                  <p className="mt-2 text-sm text-slate-700">
                    {conversationDetails.summary}
                  </p>

                  {/* AI Actions */}
                  {conversationDetails.aiActions &&
                    Array.isArray(conversationDetails.aiActions) &&
                    conversationDetails.aiActions.length > 0 && (
                      <div className="mt-3">
                        <p className="text-xs font-semibold text-slate-600">
                          {dt.aiActionsTaken}:
                        </p>
                        <ul className="mt-2 space-y-1">
                          {conversationDetails.aiActions.map(
                            (action: any, index: number) => (
                              <li
                                key={index}
                                className="flex items-start gap-2 text-xs text-slate-700"
                              >
                                <span className="text-emerald-600">✓</span>
                                <span>
                                  {action.description || action.action}
                                </span>
                                {action.timestamp && (
                                  <span className="text-slate-400">
                                    {new Date(
                                      action.timestamp,
                                    ).toLocaleTimeString(
                                      isAr ? "ar-SA" : "en-US",
                                      {
                                        hour: "2-digit",
                                        minute: "2-digit",
                                      },
                                    )}
                                  </span>
                                )}
                              </li>
                            ),
                          )}
                        </ul>
                      </div>
                    )}

                  {/* Linked Booking */}
                  {conversationDetails.bookingId && (
                    <div className="mt-3 rounded-lg border border-emerald-200 bg-white p-3">
                      <p className="text-xs font-semibold text-emerald-700">
                        {isAr ? "✓ تم إنشاء حجز" : "✓ Booking created"}
                      </p>
                      <button className="mt-1 text-xs text-brand-green hover:underline">
                        {isAr ? "عرض تفاصيل الحجز →" : "View booking details →"}
                      </button>
                    </div>
                  )}
                </div>
              )}

              {/* Message History */}
              <div className="max-h-[500px] overflow-y-auto p-4">
                {loadingDetails ? (
                  <div className="flex items-center justify-center py-12">
                    <div className="text-sm text-slate-500">
                      {isAr ? "جاري التحميل..." : "Loading..."}
                    </div>
                  </div>
                ) : conversationDetails?.messages &&
                  conversationDetails.messages.length > 0 ? (
                  <div className="space-y-3">
                    {conversationDetails.messages.map((msg: any) => (
                      <div
                        key={msg.id}
                        className={`flex ${msg.sender === "customer" ? (isAr ? "justify-end" : "justify-start") : isAr ? "justify-start" : "justify-end"}`}
                      >
                        <div
                          className={`max-w-[70%] rounded-lg px-4 py-2 ${
                            msg.sender === "customer"
                              ? "bg-slate-100 text-slate-900"
                              : "bg-brand-green text-white"
                          }`}
                        >
                          <p className="text-sm">{msg.message}</p>
                          <p
                            className={`mt-1 text-xs ${
                              msg.sender === "customer"
                                ? "text-slate-500"
                                : "text-emerald-100"
                            }`}
                          >
                            {new Date(msg.timestamp).toLocaleTimeString(
                              isAr ? "ar-SA" : "en-US",
                              {
                                hour: "2-digit",
                                minute: "2-digit",
                              },
                            )}
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="flex flex-col items-center justify-center py-12 text-center">
                    <p className="text-sm text-slate-500">
                      {isAr ? "لا توجد رسائل بعد" : "No messages yet"}
                    </p>
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
