import React, { useState, useEffect } from 'react';
import { useUser } from '@clerk/clerk-react';
import { usePartyKit } from '../hooks/usePartyKit';

interface AdminMessage {
  type: 'admin-message';
  message: string;
  sender: string;
}

const AdminPage: React.FC = () => {
  const { user } = useUser();
  const { sendMessage, lastMessage, getToken } = usePartyKit();
  const [broadcastMessage, setBroadcastMessage] = useState('');
  const [targetUserId, setTargetUserId] = useState('');
  const [receivedMessages, setReceivedMessages] = useState<AdminMessage[]>([]);
  const [isAdmin, setIsAdmin] = useState(false);

  // Replace with your actual admin user ID from .env or similar
  const CLERK_ADMIN_USERID = import.meta.env.VITE_CLERK_ADMIN_USERID;

  useEffect(() => {
    if (user?.id === CLERK_ADMIN_USERID) {
      setIsAdmin(true);
    } else {
      setIsAdmin(false);
    }
  }, [user, CLERK_ADMIN_USERID]);

  useEffect(() => {
    if (lastMessage) {
      try {
        const parsedMessage = JSON.parse(lastMessage);
        if (parsedMessage.type === 'admin-message') {
          setReceivedMessages((prev) => [...prev, parsedMessage]);
        }
      } catch (error) {
        console.error('Failed to parse last message:', error);
      }
    }
  }, [lastMessage]);

  const handleBroadcast = async () => {
    if (!user || !isAdmin) {
      alert('You are not authorized to send admin messages.');
      return;
    }

    if (broadcastMessage.trim()) {
      const token = await getToken(); // Get the token using the exposed getToken from usePartyKit
      const messagePayload = {
        type: 'admin-broadcast',
        token: token, // Send the Clerk token
        userId: user.id,
        userName: user.fullName || user.id,
        message: broadcastMessage.trim(),
        ...(targetUserId.trim() && { targetUserId: targetUserId.trim() }),
      };
      sendMessage(JSON.stringify(messagePayload));
      setBroadcastMessage('');
      setTargetUserId('');
    }
  };

  if (!isAdmin) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-900 text-white">
        <p className="text-xl">Access Denied: You are not an administrator.</p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-900 text-white p-8">
      <h1 className="text-3xl font-bold mb-6">Admin Broadcast Page</h1>

      <div className="mb-8 p-6 bg-gray-800 rounded-lg shadow-lg">
        <h2 className="text-2xl font-semibold mb-4">Send Broadcast Message</h2>
        <div className="mb-4">
          <label htmlFor="message" className="block text-lg font-medium mb-2">
            Message:
          </label>
          <textarea
            id="message"
            className="w-full p-3 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
            rows={4}
            value={broadcastMessage}
            onChange={(e) => setBroadcastMessage(e.target.value)}
            placeholder="Enter your broadcast message here..."
          ></textarea>
        </div>
        <div className="mb-4">
          <label htmlFor="targetUserId" className="block text-lg font-medium mb-2">
            Target User ID (Optional, leave blank for all users):
          </label>
          <input
            type="text"
            id="targetUserId"
            className="w-full p-3 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
            value={targetUserId}
            onChange={(e) => setTargetUserId(e.target.value)}
            placeholder="e.g., user_123abc"
          />
        </div>
        <button
          onClick={handleBroadcast}
          className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-md transition duration-300 ease-in-out"
        >
          Send Broadcast
        </button>
      </div>

      <div className="p-6 bg-gray-800 rounded-lg shadow-lg">
        <h2 className="text-2xl font-semibold mb-4">Received Admin Messages</h2>
        <div className="max-h-64 overflow-y-auto bg-gray-700 p-4 rounded-md">
          {receivedMessages.length === 0 ? (
            <p className="text-gray-400">No admin messages received yet.</p>
          ) : (
            <ul>
              {receivedMessages.map((msg, index) => (
                <li key={index} className="mb-2 p-3 bg-gray-600 rounded-md">
                  <strong>{msg.sender}:</strong> {msg.message}
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>
    </div>
  );
};

export default AdminPage;
