'use client';

import { useState, useEffect } from 'react';

interface AdminButtonProps {
  articleId: number;
  articleTitle: string;
}

export default function AdminButton({ articleId, articleTitle }: AdminButtonProps) {
  const [showPanel, setShowPanel] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');

  // Set up keyboard shortcut listener
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.altKey && e.shiftKey && e.key === 'A') {
        e.preventDefault();
        setShowPanel(prev => !prev);
        checkAdmin();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    
    // Cleanup
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  // Check if admin mode is enabled (password in sessionStorage)
  const checkAdmin = () => {
    if (typeof window !== 'undefined') {
      const stored = sessionStorage.getItem('adminAuth');
      if (stored) {
        setPassword(stored);
        setIsAdmin(true);
        return true;
      }
    }
    return false;
  };

  const handleAuth = () => {
    if (password) {
      sessionStorage.setItem('adminAuth', password);
      setIsAdmin(true);
      setMessage('');
    }
  };

  const handleAction = async (action: string) => {
    if (!checkAdmin() && !password) {
      setMessage('Please enter admin password');
      return;
    }

    setLoading(true);
    setMessage('');

    const authToken = sessionStorage.getItem('adminAuth') || password;

    try {
      const response = await fetch('/api/admin/article', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({
          articleId,
          action,
          reason: action === 'unpublish' ? 'Flagged by admin' : undefined
        })
      });

      const data = await response.json();

      if (response.ok) {
        setMessage(`✅ ${data.message}`);
        
        // Reload page after 1 second
        setTimeout(() => {
          window.location.reload();
        }, 1000);
      } else {
        setMessage(`❌ ${data.error}`);
        if (response.status === 401) {
          sessionStorage.removeItem('adminAuth');
          setIsAdmin(false);
        }
      }
    } catch (error) {
      setMessage('❌ Error: ' + error);
    } finally {
      setLoading(false);
    }
  };

  if (!showPanel) return null;

  return (
    <div className="fixed bottom-4 right-4 bg-red-600 text-white p-4 rounded-lg shadow-lg max-w-sm z-50">
      <div className="flex justify-between items-start mb-3">
        <h3 className="font-bold text-sm">Admin Controls</h3>
        <button 
          onClick={() => setShowPanel(false)}
          className="text-white hover:text-gray-200"
        >
          ✕
        </button>
      </div>

      <div className="text-xs mb-3">
        <strong>Article #{articleId}</strong><br/>
        {articleTitle.substring(0, 50)}...
      </div>

      {!isAdmin ? (
        <div className="mb-3">
          <input
            type="password"
            placeholder="Admin password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleAuth()}
            className="w-full px-3 py-2 text-sm text-black rounded border"
          />
          <button
            onClick={handleAuth}
            className="w-full mt-2 px-3 py-2 bg-white text-red-600 rounded text-sm font-bold hover:bg-gray-100"
          >
            Unlock Admin
          </button>
        </div>
      ) : (
        <div className="space-y-2">
          <button
            onClick={() => handleAction('unpublish')}
            disabled={loading}
            className="w-full px-3 py-2 bg-yellow-500 text-black rounded text-sm font-bold hover:bg-yellow-400 disabled:opacity-50"
          >
            {loading ? 'Processing...' : '🚫 Unpublish (Hide)'}
          </button>
          
          <button
            onClick={() => handleAction('delete')}
            disabled={loading}
            className="w-full px-3 py-2 bg-red-800 text-white rounded text-sm font-bold hover:bg-red-700 disabled:opacity-50"
          >
            {loading ? 'Processing...' : '🗑️ Delete Forever'}
          </button>

          <button
            onClick={() => {
              sessionStorage.removeItem('adminAuth');
              setIsAdmin(false);
              setPassword('');
            }}
            className="w-full px-3 py-2 bg-gray-700 text-white rounded text-sm hover:bg-gray-600"
          >
            Lock Admin
          </button>
        </div>
      )}

      {message && (
        <div className="mt-3 text-xs p-2 bg-white text-black rounded">
          {message}
        </div>
      )}

      <div className="mt-3 text-xs text-gray-300">
        Press Alt+Shift+A to toggle
      </div>
    </div>
  );
}
