"use client";

import { useState, useEffect, useCallback } from "react";
import { MessageSquare, Paperclip, Plus, Loader2 } from "lucide-react";
import DOMPurify from "dompurify";
import AddInboundMessageModal from "./AddInboundMessageModal";

interface Message {
  id: string;
  direction: "outbound" | "inbound";
  fromEmail: string;
  toEmail: string;
  subject: string | null;
  bodyHtml: string;
  attachments: Array<{
    filename: string;
    url: string;
    size: number;
    mimeType: string;
  }>;
  senderName?: string;
  createdAt: string;
}

interface ConversationThreadProps {
  contactId: string;
  contactEmail: string;
  csrfToken: string;
}

export default function ConversationThread({
  contactId,
  contactEmail,
  csrfToken,
}: ConversationThreadProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showAddInboundModal, setShowAddInboundModal] = useState(false);

  const fetchMessages = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const response = await fetch(
        `/api/staff/dashboard/contacts/${contactId}/messages`,
      );
      if (!response.ok) {
        throw new Error("Failed to fetch messages");
      }
      const data = await response.json();
      setMessages(data.messages || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load messages");
    } finally {
      setIsLoading(false);
    }
  }, [contactId]);

  useEffect(() => {
    fetchMessages();
  }, [fetchMessages]);

  const handleInboundMessageAdded = () => {
    fetchMessages();
    setShowAddInboundModal(false);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  // Sanitize HTML content to prevent XSS
  const sanitizeHtml = (html: string) => {
    return DOMPurify.sanitize(html, {
      ALLOWED_TAGS: [
        "p",
        "br",
        "strong",
        "em",
        "u",
        "a",
        "ul",
        "ol",
        "li",
        "blockquote",
        "h1",
        "h2",
        "h3",
        "div",
        "span",
      ],
      ALLOWED_ATTR: ["href", "target", "rel", "class"],
    });
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-8 text-gray-500">
        <Loader2 className="w-5 h-5 animate-spin mr-2" />
        Loading conversation...
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 bg-red-50 text-red-700 rounded-lg text-sm">
        {error}
      </div>
    );
  }

  if (messages.length === 0) {
    return (
      <div className="text-center py-6 text-gray-500">
        <MessageSquare className="w-8 h-8 mx-auto mb-2 opacity-50" />
        <p className="text-sm">No conversation yet</p>
        <button
          onClick={() => setShowAddInboundModal(true)}
          className="mt-2 text-sm text-primary-600 hover:underline"
        >
          Log a customer response
        </button>
        {showAddInboundModal && (
          <AddInboundMessageModal
            isOpen={showAddInboundModal}
            onClose={() => setShowAddInboundModal(false)}
            onSuccess={handleInboundMessageAdded}
            contactId={contactId}
            contactEmail={contactEmail}
            csrfToken={csrfToken}
          />
        )}
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-medium text-gray-700">
          Conversation ({messages.length}{" "}
          {messages.length === 1 ? "message" : "messages"})
        </h4>
        <button
          onClick={() => setShowAddInboundModal(true)}
          className="inline-flex items-center gap-1 text-xs text-primary-600 hover:underline"
        >
          <Plus className="w-3 h-3" />
          Add customer response
        </button>
      </div>

      <div className="space-y-3">
        {messages.map((message) => (
          <div
            key={message.id}
            className={`p-4 rounded-lg border ${
              message.direction === "outbound"
                ? "bg-primary-50 border-primary-200"
                : "bg-gray-50 border-gray-200"
            }`}
          >
            {/* Header */}
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium">
                  {message.direction === "outbound"
                    ? `You${message.senderName ? ` (${message.senderName})` : ""}`
                    : message.fromEmail}
                </span>
                {message.direction === "inbound" && (
                  <span className="text-xs text-gray-400">
                    (Manually logged)
                  </span>
                )}
              </div>
              <span className="text-xs text-gray-500">
                {formatDate(message.createdAt)}
              </span>
            </div>

            {/* Subject (if present) */}
            {message.subject && (
              <p className="text-xs text-gray-500 mb-2">
                Subject: {message.subject}
              </p>
            )}

            {/* Body - sanitized with DOMPurify */}
            <div
              className="prose prose-sm max-w-none text-gray-700"
              dangerouslySetInnerHTML={{
                __html: sanitizeHtml(message.bodyHtml),
              }}
            />

            {/* Attachments */}
            {message.attachments.length > 0 && (
              <div className="mt-3 pt-3 border-t border-gray-200">
                <div className="flex flex-wrap gap-2">
                  {message.attachments.map((attachment) => (
                    <a
                      key={attachment.url}
                      href={attachment.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1 px-2 py-1 bg-white border border-gray-200 rounded text-xs hover:bg-gray-50 transition-colors"
                    >
                      <Paperclip className="w-3 h-3" />
                      {attachment.filename}
                    </a>
                  ))}
                </div>
              </div>
            )}
          </div>
        ))}
      </div>

      {showAddInboundModal && (
        <AddInboundMessageModal
          isOpen={showAddInboundModal}
          onClose={() => setShowAddInboundModal(false)}
          onSuccess={handleInboundMessageAdded}
          contactId={contactId}
          contactEmail={contactEmail}
          csrfToken={csrfToken}
        />
      )}
    </div>
  );
}
