'use client';

import { useCallback, useEffect, useState } from 'react';
import { ForwardTargetDialog } from '../ForwardTargetDialog';

interface PendingMessage {
  id: string;
  content: string;
  senderJid: string;
  senderName: string | null;
  tags: string[];
  createdAt: string;
  sourceGroupId: string;
  sourceGroupName: string;
  sourceGroupPlatformId: string;
}

export default function PendingMessagesPage() {
  const [messages, setMessages] = useState<PendingMessage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(() => {
    setLoading(true);
    fetch('/api/messages/pending')
      .then(async (res) => {
        if (!res.ok) throw new Error(`API ${res.status}`);
        return res.json() as Promise<PendingMessage[]>;
      })
      .then((data) => { setMessages(data); setError(null); })
      .catch((err: Error) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

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

  return (
    <div className="max-w-3xl">
      <h1 className="text-xl font-semibold mb-2">Pending messages</h1>
      <p className="text-sm text-gray-500 mb-6">
        Messages waiting for admin approval. Click "Approve &amp; Forward" to choose which groups to send to.
      </p>

      {error && (
        <div className="mb-4 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-800">
          Failed to load: {error}
        </div>
      )}

      {!loading && !error && messages.length === 0 && (
        <div className="rounded-xl border border-gray-200 bg-white p-6 text-sm text-gray-500">
          No pending messages right now.
        </div>
      )}

      <ul className="space-y-3">
        {messages.map((m) => (
          <PendingMessageRow
            key={m.id}
            message={m}
            onApproved={() => setMessages((prev) => prev.filter((x) => x.id !== m.id))}
          />
        ))}
      </ul>
    </div>
  );
}

function PendingMessageRow({
  message,
  onApproved,
}: {
  message: PendingMessage;
  onApproved: () => void;
}) {
  const [dialogOpen, setDialogOpen] = useState(false);

  return (
    <li className="rounded-xl border border-gray-200 bg-white p-4 flex flex-col gap-2">
      <div className="flex items-baseline justify-between gap-2">
        <div className="text-sm font-medium text-gray-900">{message.sourceGroupName}</div>
        <div className="text-xs text-gray-500">{new Date(message.createdAt).toLocaleString()}</div>
      </div>
      <div className="text-xs text-gray-500">
        From <span className="font-mono">{message.senderName ?? message.senderJid}</span>
        {message.tags.length > 0 && (
          <span className="ml-2 inline-flex flex-wrap gap-1">
            {message.tags.map((t) => (
              <span key={t} className="rounded bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-700">
                {t}
              </span>
            ))}
          </span>
        )}
      </div>
      <div className="text-sm text-gray-800 whitespace-pre-wrap break-words">{message.content}</div>
      <div className="flex justify-end pt-1">
        <button
          onClick={() => setDialogOpen(true)}
          className="rounded bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700"
        >
          Approve &amp; Forward
        </button>
      </div>

      {dialogOpen && (
        <ForwardTargetDialog
          messageId={message.id}
          onApproved={onApproved}
          onClose={() => setDialogOpen(false)}
        />
      )}
    </li>
  );
}
