'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';

interface Article {
  id: number;
  title: string;
  title_burmese: string;
  slug: string;
  status: string;
  content_length: number;
  burmese_length: number;
  published_at: string;
  view_count: number;
}

export default function AdminDashboard() {
  const [password, setPassword] = useState('');
  const [isAuthed, setIsAuthed] = useState(false);
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [statusFilter, setStatusFilter] = useState('published');

  useEffect(() => {
    // Check if already authenticated
    const stored = sessionStorage.getItem('adminAuth');
    if (stored) {
      setIsAuthed(true);
      setPassword(stored);
      loadArticles(stored, statusFilter);
    }
  }, []);

  const handleAuth = () => {
    sessionStorage.setItem('adminAuth', password);
    setIsAuthed(true);
    loadArticles(password, statusFilter);
  };

  const loadArticles = async (authToken: string, status: string) => {
    setLoading(true);
    try {
      const response = await fetch(`/api/admin/article?status=${status}&limit=50`, {
        headers: {
          'Authorization': `Bearer ${authToken}`
        }
      });

      if (response.ok) {
        const data = await response.json();
        setArticles(data.articles);
      } else {
        setMessage('❌ Authentication failed');
        sessionStorage.removeItem('adminAuth');
        setIsAuthed(false);
      }
    } catch (error) {
      setMessage('❌ Error loading articles');
    } finally {
      setLoading(false);
    }
  };

  const handleAction = async (articleId: number, action: string) => {
    if (!confirm(`Are you sure you want to ${action} article #${articleId}?`)) {
      return;
    }

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

      if (response.ok) {
        setMessage(`✅ Article ${action}ed successfully`);
        loadArticles(password, statusFilter);
      } else {
        const data = await response.json();
        setMessage(`❌ ${data.error}`);
      }
    } catch (error) {
      setMessage('❌ Error: ' + error);
    }
  };

  if (!isAuthed) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="bg-white p-8 rounded-lg shadow-lg max-w-md w-full">
          <h1 className="text-3xl font-bold mb-6 text-center">🔒 Admin Login</h1>
          <input
            type="password"
            placeholder="Admin Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleAuth()}
            className="w-full px-4 py-3 border rounded-lg mb-4 text-lg"
          />
          <button
            onClick={handleAuth}
            className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold hover:bg-blue-700"
          >
            Login
          </button>
          <p className="mt-4 text-sm text-gray-600 text-center">
            Enter admin password to access dashboard
          </p>
        </div>
      </div>
    );
  }

  const translationRatio = (article: Article) => {
    if (article.content_length === 0) return 0;
    return Math.round((article.burmese_length / article.content_length) * 100);
  };

  const getStatusColor = (status: string) => {
    return status === 'published' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800';
  };

  const getRatioColor = (ratio: number) => {
    if (ratio >= 40) return 'text-green-600';
    if (ratio >= 20) return 'text-yellow-600';
    return 'text-red-600';
  };

  return (
    <div className="min-h-screen bg-gray-100">
      <div className="bg-white shadow">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex justify-between items-center">
            <h1 className="text-3xl font-bold text-gray-900">Admin Dashboard</h1>
            <div className="flex gap-4">
              <select
                value={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value);
                  loadArticles(password, e.target.value);
                }}
                className="px-4 py-2 border rounded-lg"
              >
                <option value="published">Published</option>
                <option value="draft">Draft</option>
              </select>
              <button
                onClick={() => {
                  sessionStorage.removeItem('adminAuth');
                  setIsAuthed(false);
                }}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
              >
                Logout
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {message && (
          <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
            {message}
          </div>
        )}

        {loading ? (
          <div className="text-center py-12">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
            <p className="mt-4 text-gray-600">Loading articles...</p>
          </div>
        ) : (
          <>
            <div className="bg-white rounded-lg shadow overflow-hidden">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Title</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Translation</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Views</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {articles.map((article) => {
                    const ratio = translationRatio(article);
                    return (
                      <tr key={article.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                          {article.id}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-900">
                          <Link
                            href={`/article/${article.slug}`}
                            target="_blank"
                            className="hover:text-blue-600 hover:underline"
                          >
                            {article.title_burmese.substring(0, 80)}...
                          </Link>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(article.status)}`}>
                            {article.status}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <span className={`text-sm font-semibold ${getRatioColor(ratio)}`}>
                            {ratio}%
                          </span>
                          <span className="text-xs text-gray-500 ml-2">
                            ({article.burmese_length.toLocaleString()} / {article.content_length.toLocaleString()})
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {article.view_count || 0}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                          <Link
                            href={`/article/${article.slug}`}
                            target="_blank"
                            className="text-blue-600 hover:text-blue-900"
                          >
                            View
                          </Link>
                          {article.status === 'published' ? (
                            <button
                              onClick={() => handleAction(article.id, 'unpublish')}
                              className="text-yellow-600 hover:text-yellow-900"
                            >
                              Unpublish
                            </button>
                          ) : (
                            <button
                              onClick={() => handleAction(article.id, 'publish')}
                              className="text-green-600 hover:text-green-900"
                            >
                              Publish
                            </button>
                          )}
                          <button
                            onClick={() => handleAction(article.id, 'delete')}
                            className="text-red-600 hover:text-red-900"
                          >
                            Delete
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            <div className="mt-6 text-sm text-gray-600">
              <p>Showing {articles.length} {statusFilter} articles</p>
              <p className="mt-2">
                <strong>Translation Quality:</strong>{' '}
                <span className="text-green-600">40%+ = Good</span>,{' '}
                <span className="text-yellow-600">20-40% = Check</span>,{' '}
                <span className="text-red-600">&lt;20% = Poor</span>
              </p>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
