import React, { useState, useEffect } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useSession } from 'next-auth/react';
import { MessageSquare, ChevronLeft, ChevronRight, Search } from 'lucide-react';
import AdminLayout from '../../components/AdminLayout';

interface User {
  id: number;
  username: string | null;
  email: string | null;
  name: string | null;
  image: string | null;
  status: 'active' | 'disabled' | 'suspended';
  is_admin: number;
  query_count: number;
  subscription_plan: string;
  last_active: string | null;
  created_at: string;
  conversation_count: number;
  message_count: number;
}

const USERS_PER_PAGE = 15;

export default function AdminUsers() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [darkMode, setDarkMode] = useState(false);

  useEffect(() => {
    try {
      const savedTheme = localStorage.getItem('theme');
      if (savedTheme === 'dark') setDarkMode(true);
    } catch {}
  }, []);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin');
    }
  }, [status, router]);

  useEffect(() => {
    if (status === 'authenticated') {
      loadUsers();
    }
  }, [status]);

  async function loadUsers() {
    setLoading(true);
    try {
      const res = await fetch('/api/admin/users');
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      setUsers(data.users || []);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  async function updateUserStatus(userId: number, newStatus: string) {
    try {
      const res = await fetch('/api/admin/users', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId, status: newStatus }),
      });
      if (!res.ok) throw new Error('Failed to update status');
      setUsers(users.map(u => u.id === userId ? { ...u, status: newStatus as any } : u));
    } catch (err: any) {
      alert('Error: ' + err.message);
    }
  }

  async function toggleAdmin(userId: number, currentIsAdmin: number) {
    try {
      const res = await fetch('/api/admin/users', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId, is_admin: currentIsAdmin ? 0 : 1 }),
      });
      if (!res.ok) throw new Error('Failed to update admin status');
      setUsers(users.map(u => u.id === userId ? { ...u, is_admin: currentIsAdmin ? 0 : 1 } : u));
    } catch (err: any) {
      alert('Error: ' + err.message);
    }
  }

  async function deleteUser(userId: number) {
    if (!confirm('Are you sure you want to delete this user? This cannot be undone.')) return;
    try {
      const res = await fetch('/api/admin/users', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId }),
      });
      if (!res.ok) throw new Error('Failed to delete user');
      setUsers(users.filter(u => u.id !== userId));
    } catch (err: any) {
      alert('Error: ' + err.message);
    }
  }

  // Filter users
  const filteredUsers = users.filter(user => {
    const matchesSearch = !searchTerm || 
      (user.email?.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (user.username?.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (user.name?.toLowerCase().includes(searchTerm.toLowerCase()));
    const matchesStatus = statusFilter === 'all' || user.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  // Pagination
  const totalPages = Math.ceil(filteredUsers.length / USERS_PER_PAGE);
  const paginatedUsers = filteredUsers.slice(
    (currentPage - 1) * USERS_PER_PAGE,
    currentPage * USERS_PER_PAGE
  );

  // Reset to page 1 when filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm, statusFilter]);

  const theme = {
    bg: darkMode ? '#1a1a2e' : '#f8fafc',
    cardBg: darkMode ? '#16213e' : '#ffffff',
    text: darkMode ? '#e2e8f0' : '#1e293b',
    textSecondary: darkMode ? '#94a3b8' : '#64748b',
    textMuted: darkMode ? '#64748b' : '#9ca3af',
    border: darkMode ? '#2d3748' : '#e2e8f0',
  };

  const S: Record<string, React.CSSProperties> = {
    controls: {
      display: 'flex',
      gap: 12,
      marginBottom: 24,
      flexWrap: 'wrap',
      alignItems: 'center',
    },
    searchContainer: {
      position: 'relative',
      flex: '1 1 300px',
    },
    searchIcon: {
      position: 'absolute',
      left: 12,
      top: '50%',
      transform: 'translateY(-50%)',
      color: theme.textMuted,
    },
    searchInput: {
      width: '100%',
      padding: '10px 12px 10px 40px',
      borderRadius: 8,
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.text,
      fontSize: 14,
      boxSizing: 'border-box',
    },
    select: {
      padding: '10px 12px',
      borderRadius: 8,
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.text,
      fontSize: 14,
    },
    table: {
      width: '100%',
      borderCollapse: 'collapse',
      background: theme.cardBg,
      borderRadius: 12,
      overflow: 'hidden',
    },
    th: {
      padding: '12px 16px',
      textAlign: 'left' as const,
      background: darkMode ? '#1f2937' : '#f9fafb',
      color: theme.textSecondary,
      fontSize: 12,
      fontWeight: 600,
      textTransform: 'uppercase' as const,
      borderBottom: `1px solid ${theme.border}`,
    },
    td: {
      padding: '12px 16px',
      borderBottom: `1px solid ${theme.border}`,
      color: theme.text,
      fontSize: 14,
    },
    avatar: {
      width: 36,
      height: 36,
      borderRadius: '50%',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      color: '#fff',
      fontWeight: 600,
      fontSize: 14,
    },
    userInfo: {
      display: 'flex',
      alignItems: 'center',
      gap: 12,
    },
    statusBadge: {
      padding: '4px 8px',
      borderRadius: 4,
      fontSize: 12,
      fontWeight: 500,
    },
    actionBtn: {
      padding: '6px 12px',
      borderRadius: 6,
      border: 'none',
      fontSize: 12,
      cursor: 'pointer',
      marginRight: 8,
    },
    pagination: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginTop: 24,
      padding: '12px 0',
    },
    pageInfo: {
      color: theme.textSecondary,
      fontSize: 14,
    },
    pageButtons: {
      display: 'flex',
      gap: 8,
    },
    pageBtn: {
      padding: '8px 12px',
      borderRadius: 6,
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.text,
      cursor: 'pointer',
      display: 'flex',
      alignItems: 'center',
      gap: 4,
      fontSize: 14,
    },
    planBadge: {
      padding: '2px 6px',
      borderRadius: 4,
      fontSize: 11,
      fontWeight: 500,
      textTransform: 'capitalize' as const,
    },
  };

  function getStatusStyle(status: string) {
    switch (status) {
      case 'active': return { background: darkMode ? '#064e3b' : '#dcfce7', color: '#16a34a' };
      case 'disabled': return { background: darkMode ? '#713f12' : '#fef3c7', color: '#ca8a04' };
      case 'suspended': return { background: darkMode ? '#7f1d1d' : '#fee2e2', color: '#dc2626' };
      default: return { background: '#f3f4f6', color: '#6b7280' };
    }
  }

  function getPlanStyle(plan: string) {
    switch (plan) {
      case 'premium': return { background: '#fef3c7', color: '#b45309' };
      case 'gold': return { background: '#fef9c3', color: '#a16207' };
      case 'silver': return { background: '#e0e7ff', color: '#4f46e5' };
      default: return { background: darkMode ? '#374151' : '#f3f4f6', color: theme.textSecondary };
    }
  }

  function formatDate(dateStr: string) {
    return new Date(dateStr).toLocaleDateString('en-US', {
      year: 'numeric', month: 'short', day: 'numeric'
    });
  }

  if (status === 'loading' || loading) {
    return (
      <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="users">
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh', color: theme.textSecondary }}>
          Loading...
        </div>
      </AdminLayout>
    );
  }

  if (error) {
    return (
      <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="users">
        <div style={{ padding: 16, background: '#fee2e2', color: '#dc2626', borderRadius: 8 }}>
          {error}
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout darkMode={darkMode} setDarkMode={setDarkMode} currentPage="users">
      <Head>
        <title>User Management - Admin - Gregory AI</title>
      </Head>

      {/* Controls */}
      <div style={S.controls}>
        <div style={S.searchContainer as any}>
          <Search size={18} style={S.searchIcon as any} />
          <input
            type="text"
            placeholder="Search by name, email, or username..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            style={S.searchInput as any}
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          style={S.select}
        >
          <option value="all">All Status</option>
          <option value="active">Active</option>
          <option value="disabled">Disabled</option>
          <option value="suspended">Suspended</option>
        </select>
        <button
          onClick={loadUsers}
          style={{
            ...S.select,
            cursor: 'pointer',
            background: 'linear-gradient(90deg, #2563eb, #7c3aed)',
            color: '#fff',
            border: 'none',
          }}
        >
          Refresh
        </button>
      </div>

      {/* Users Table */}
      <div style={{ overflowX: 'auto', borderRadius: 12, border: `1px solid ${theme.border}` }}>
        <table style={S.table}>
          <thead>
            <tr>
              <th style={S.th}>User</th>
              <th style={S.th}>Plan</th>
              <th style={S.th}>Status</th>
              <th style={S.th}>Role</th>
              <th style={S.th}>Chats</th>
              <th style={S.th}>Joined</th>
              <th style={S.th}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {paginatedUsers.length === 0 ? (
              <tr>
                <td colSpan={7} style={{ ...S.td, textAlign: 'center', color: theme.textSecondary }}>
                  No users found
                </td>
              </tr>
            ) : (
              paginatedUsers.map((user) => (
                <tr key={user.id}>
                  <td style={S.td}>
                    <div style={S.userInfo}>
                      {user.image ? (
                        <img src={user.image} alt="" style={{ ...S.avatar, background: 'none' }} />
                      ) : (
                        <div style={S.avatar}>
                          {(user.name || user.email || user.username || 'U')[0].toUpperCase()}
                        </div>
                      )}
                      <div>
                        <div style={{ fontWeight: 600 }}>{user.name || user.username || 'Unknown'}</div>
                        <div style={{ fontSize: 12, color: theme.textMuted }}>{user.email}</div>
                      </div>
                    </div>
                  </td>
                  <td style={S.td}>
                    <span style={{ ...S.planBadge, ...getPlanStyle(user.subscription_plan || 'free') }}>
                      {user.subscription_plan || 'free'}
                    </span>
                  </td>
                  <td style={S.td}>
                    <span style={{ ...S.statusBadge, ...getStatusStyle(user.status) }}>
                      {user.status}
                    </span>
                  </td>
                  <td style={S.td}>
                    <span style={{
                      ...S.statusBadge,
                      background: user.is_admin ? (darkMode ? '#1f2d3d' : '#dbeafe') : (darkMode ? '#2d2d44' : '#f3f4f6'),
                      color: user.is_admin ? '#2563eb' : theme.textMuted
                    }}>
                      {user.is_admin ? 'Admin' : 'User'}
                    </span>
                  </td>
                  <td style={S.td}>
                    <div 
                      onClick={() => router.push(`/admin/conversations?userId=${user.id}`)}
                      style={{ 
                        display: 'inline-flex', 
                        alignItems: 'center', 
                        gap: 6, 
                        cursor: 'pointer',
                        color: '#3b82f6',
                        fontWeight: 500,
                      }}
                      title="View conversations"
                    >
                      <MessageSquare size={14} />
                      {user.conversation_count}
                    </div>
                  </td>
                  <td style={S.td}>{formatDate(user.created_at)}</td>
                  <td style={S.td}>
                    <select
                      value={user.status}
                      onChange={(e) => updateUserStatus(user.id, e.target.value)}
                      style={{ ...S.select, padding: '6px 10px', fontSize: 12 }}
                    >
                      <option value="active">Active</option>
                      <option value="disabled">Disabled</option>
                      <option value="suspended">Suspended</option>
                    </select>
                    <button
                      onClick={() => toggleAdmin(user.id, user.is_admin)}
                      style={{
                        ...S.actionBtn,
                        background: user.is_admin ? (darkMode ? '#3d3d5c' : '#f3f4f6') : (darkMode ? '#1f2d3d' : '#dbeafe'),
                        color: user.is_admin ? theme.textSecondary : '#2563eb'
                      }}
                    >
                      {user.is_admin ? 'Remove Admin' : 'Make Admin'}
                    </button>
                    <button
                      onClick={() => deleteUser(user.id)}
                      style={{ ...S.actionBtn, background: darkMode ? '#3d1f1f' : '#fee2e2', color: '#dc2626' }}
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div style={S.pagination}>
          <div style={S.pageInfo}>
            Showing {((currentPage - 1) * USERS_PER_PAGE) + 1} - {Math.min(currentPage * USERS_PER_PAGE, filteredUsers.length)} of {filteredUsers.length} users
          </div>
          <div style={S.pageButtons}>
            <button
              style={{ ...S.pageBtn, opacity: currentPage === 1 ? 0.5 : 1 }}
              onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
              disabled={currentPage === 1}
            >
              <ChevronLeft size={16} /> Previous
            </button>
            <span style={{ ...S.pageBtn, background: 'transparent', border: 'none' }}>
              Page {currentPage} of {totalPages}
            </span>
            <button
              style={{ ...S.pageBtn, opacity: currentPage === totalPages ? 0.5 : 1 }}
              onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
            >
              Next <ChevronRight size={16} />
            </button>
          </div>
        </div>
      )}
    </AdminLayout>
  );
}
