import { useState, useEffect } from "react"
import type { NextPage } from "next"
import Head from "next/head"
import Link from "next/link"

interface User {
  id: number
  email: string
  role: string
  is_active: boolean
  created_at: string
  last_login: string | null
  sources_moderated: number
}

const UsersManagement: NextPage = () => {
  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(true)
  const [showAddForm, setShowAddForm] = useState(false)
  const [newUser, setNewUser] = useState({ email: '', password: '', role: 'moderator' })

  useEffect(() => {
    fetchUsers()
  }, [])

  const fetchUsers = async () => {
    try {
      const response = await fetch('/api/admin/users')
      const data = await response.json()
      setUsers(data.users || [])
    } catch (error) {
      console.error('Error fetching users:', error)
    }
    setLoading(false)
  }

  const handleAddUser = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newUser.email || !newUser.password) return

    try {
      const response = await fetch('/api/admin/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newUser)
      })
      
      if (response.ok) {
        setNewUser({ email: '', password: '', role: 'moderator' })
        setShowAddForm(false)
        fetchUsers()
      } else {
        const error = await response.json()
        alert('Error: ' + error.error)
      }
    } catch (error) {
      alert('Failed to add user')
    }
  }

  if (loading) return <div>Loading...</div>

  return (
    <div>
      <Head>
        <title>Users Management - Infohliadka</title>
      </Head>
      
      <div style={{ padding: '20px' }}>
        <div style={{ marginBottom: '20px' }}>
          <Link href="/admin">← Back to Admin</Link>
        </div>
        
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
          <h1>Users Management</h1>
          <button 
            onClick={() => setShowAddForm(!showAddForm)}
            style={{ padding: '10px 15px', backgroundColor: '#28a745', color: 'white', border: 'none', borderRadius: '4px' }}
          >
            Add User
          </button>
        </div>

        {showAddForm && (
          <div style={{ marginBottom: '20px', padding: '15px', backgroundColor: '#f8f9fa', border: '1px solid #ddd' }}>
            <h3>Add New User</h3>
            <form onSubmit={handleAddUser}>
              <div style={{ marginBottom: '10px' }}>
                <input
                  type="email"
                  placeholder="Email"
                  value={newUser.email}
                  onChange={(e) => setNewUser({...newUser, email: e.target.value})}
                  required
                  style={{ width: '200px', padding: '5px', marginRight: '10px' }}
                />
                <input
                  type="password"
                  placeholder="Password"
                  value={newUser.password}
                  onChange={(e) => setNewUser({...newUser, password: e.target.value})}
                  required
                  style={{ width: '200px', padding: '5px', marginRight: '10px' }}
                />
                <select
                  value={newUser.role}
                  onChange={(e) => setNewUser({...newUser, role: e.target.value})}
                  style={{ padding: '5px', marginRight: '10px' }}
                >
                  <option value="moderator">Moderator</option>
                  <option value="admin">Admin</option>
                </select>
                <button type="submit" style={{ padding: '5px 15px', backgroundColor: '#007bff', color: 'white', border: 'none' }}>
                  Add
                </button>
              </div>
            </form>
          </div>
        )}

        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ backgroundColor: '#f8f9fa' }}>
              <th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Email</th>
              <th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Role</th>
              <th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Status</th>
              <th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Sources Moderated</th>
              <th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Created</th>
              <th style={{ padding: '10px', textAlign: 'left', border: '1px solid #ddd' }}>Last Login</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user) => (
              <tr key={user.id}>
                <td style={{ padding: '10px', border: '1px solid #ddd' }}>{user.email}</td>
                <td style={{ padding: '10px', border: '1px solid #ddd' }}>
                  <span style={{ 
                    padding: '2px 6px', 
                    borderRadius: '3px',
                    backgroundColor: user.role === 'admin' ? '#dc3545' : '#17a2b8',
                    color: 'white',
                    fontSize: '12px'
                  }}>
                    {user.role}
                  </span>
                </td>
                <td style={{ padding: '10px', border: '1px solid #ddd' }}>
                  <span style={{ 
                    color: user.is_active ? 'green' : 'red' 
                  }}>
                    {user.is_active ? 'Active' : 'Inactive'}
                  </span>
                </td>
                <td style={{ padding: '10px', border: '1px solid #ddd' }}>{user.sources_moderated}</td>
                <td style={{ padding: '10px', border: '1px solid #ddd' }}>
                  {new Date(user.created_at).toLocaleDateString()}
                </td>
                <td style={{ padding: '10px', border: '1px solid #ddd' }}>
                  {user.last_login ? new Date(user.last_login).toLocaleDateString() : 'Never'}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        
        {users.length === 0 && (
          <p style={{ textAlign: 'center', marginTop: '20px', color: '#666' }}>
            No users found.
          </p>
        )}
      </div>
    </div>
  )
}

export default UsersManagement