'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { apiClient } from '@/lib/api';
import { ROLE_ADMINISTRATOR } from '@/lib/authRedirect';
import '../workstation-detail.css';

interface User {
  id: number;
  username: string;
  roles: string[];
  groups: string[];
  is_admin: boolean;
  is_super_admin?: boolean;
}

export default function AdministratorWorkstation() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState('users');
  const [users, setUsers] = useState<User[]>([]);
  const [roles, setRoles] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [showRoleModal, setShowRoleModal] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newRoleName, setNewRoleName] = useState('');
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [createUsername, setCreateUsername] = useState('');
  const [createPassword, setCreatePassword] = useState('');
  const [createPasswordConfirm, setCreatePasswordConfirm] = useState('');
  const [createRoles, setCreateRoles] = useState<string[]>([]);
  const [createSubmitting, setCreateSubmitting] = useState(false);

  // Restrict access to admins only (login stores user as user_info). Redirect to dashboard, not workstation.
  useEffect(() => {
    try {
      const userStr = localStorage.getItem('user_info') || localStorage.getItem('user');
      if (!userStr) {
        router.replace('/dashboard?section=overview');
        return;
      }
      const user = JSON.parse(userStr);
      const roles: string[] = user.roles || [];
      const isAdmin = user.is_admin || user.is_super_admin || roles.includes(ROLE_ADMINISTRATOR);
      if (!isAdmin) {
        router.replace('/dashboard?section=overview');
      }
    } catch {
      router.replace('/dashboard?section=overview');
    }
  }, [router]);

  useEffect(() => {
    if (activeTab === 'users') {
      loadUsers();
    } else if (activeTab === 'roles') {
      loadRoles();
    }
  }, [activeTab]);

  useEffect(() => {
    if (showCreateModal && roles.length === 0) {
      loadRoles();
    }
  }, [showCreateModal]);

  const loadUsers = async () => {
    try {
      setLoading(true);
      const response = await apiClient.get('/auth/users');
      setUsers(response.data || []);
    } catch (error: any) {
      showMessage('error', `Error loading users: ${error.response?.data?.detail || error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const loadRoles = async () => {
    try {
      setLoading(true);
      const response = await apiClient.get('/auth/roles');
      setRoles(response.data?.roles || []);
    } catch (error: any) {
      showMessage('error', `Error loading roles: ${error.response?.data?.detail || error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const assignRole = async (username: string, roleName: string) => {
    try {
      await apiClient.post(`/auth/users/${username}/roles/${roleName}`);
      showMessage('success', `Role '${roleName}' assigned to '${username}'`);
      await loadUsers();
      setShowRoleModal(false);
      setSelectedUser(null);
    } catch (error: any) {
      showMessage('error', `Error assigning role: ${error.response?.data?.detail || error.message}`);
    }
  };

  const removeRole = async (username: string, roleName: string) => {
    if (!confirm(`Remove role '${roleName}' from user '${username}'?`)) {
      return;
    }
    try {
      await apiClient.delete(`/auth/users/${username}/roles/${roleName}`);
      showMessage('success', `Role '${roleName}' removed from '${username}'`);
      await loadUsers();
    } catch (error: any) {
      showMessage('error', `Error removing role: ${error.response?.data?.detail || error.message}`);
    }
  };

  const handleCreateUser = async () => {
    const username = createUsername.trim();
    if (!username) {
      showMessage('error', 'Username is required');
      return;
    }
    if (!createPassword) {
      showMessage('error', 'Password is required');
      return;
    }
    if (createPassword.length < 6) {
      showMessage('error', 'Password must be at least 6 characters');
      return;
    }
    if (createPassword !== createPasswordConfirm) {
      showMessage('error', 'Passwords do not match');
      return;
    }
    setCreateSubmitting(true);
    try {
      await apiClient.post('/auth/users', {
        username,
        password: createPassword,
        roles: createRoles,
      });
      showMessage('success', `User '${username}' created successfully`);
      setShowCreateModal(false);
      setCreateUsername('');
      setCreatePassword('');
      setCreatePasswordConfirm('');
      setCreateRoles([]);
      await loadUsers();
    } catch (error: any) {
      const detail = error.response?.data?.detail || error.message;
      showMessage('error', typeof detail === 'string' ? detail : 'Failed to create user');
    } finally {
      setCreateSubmitting(false);
    }
  };

  const toggleCreateRole = (role: string) => {
    setCreateRoles((prev) =>
      prev.includes(role) ? prev.filter((r) => r !== role) : [...prev, role]
    );
  };

  const showMessage = (type: 'success' | 'error', text: string) => {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 5000);
  };

  const tabs = [
    { id: 'users', label: '👥 User Management', icon: '👥' },
    { id: 'roles', label: '🔐 Roles & Permissions', icon: '🔐' },
    { id: 'config', label: '⚙️ System Configuration', icon: '⚙️' },
    { id: 'audit', label: '📋 Audit Logs', icon: '📋' },
    { id: 'reports', label: '📊 Reports', icon: '📊' },
    { id: 'database', label: '🗄️ Database Admin', icon: '🗄️' }
  ];

  return (
    <div className="workstation-detail">
      <div className="workstation-header-bar">
        <div>
          <h1>⚙️ Administrator Workstation</h1>
          <p>System administration and configuration</p>
        </div>
        <button onClick={() => router.push('/workstation')} className="btn-secondary">
          ← Back to Workstations
        </button>
      </div>

      {message && (
        <div className={`alert alert-${message.type}`} style={{ margin: '10px 20px', padding: '10px' }}>
          {message.text}
        </div>
      )}

      <div className="workstation-tabs">
        {tabs.map(tab => (
          <button
            key={tab.id}
            className={`workstation-tab ${activeTab === tab.id ? 'active' : ''}`}
            onClick={() => setActiveTab(tab.id)}
          >
            <span className="tab-icon">{tab.icon}</span>
            <span className="tab-label">{tab.label}</span>
          </button>
        ))}
      </div>

      <div className="workstation-content">
        {activeTab === 'users' && (
          <div className="workstation-section">
            <h2>User Management</h2>
            <div className="section-actions">
              <button className="btn-primary" onClick={() => setShowCreateModal(true)}>
                + Create User
              </button>
              <button className="btn-secondary" onClick={loadUsers}>🔄 Refresh</button>
            </div>
            {loading ? (
              <div className="loading">Loading users...</div>
            ) : (
              <div className="data-table">
                <table>
                  <thead>
                    <tr>
                      <th>Username</th>
                      <th>Roles</th>
                      <th>Groups</th>
                      <th>Status</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.length === 0 ? (
                      <tr>
                        <td colSpan={5} style={{ textAlign: 'center', padding: '20px' }}>
                          No users found
                        </td>
                      </tr>
                    ) : (
                      users.map((user) => (
                        <tr key={user.id}>
                          <td>
                            <strong>{user.username}</strong>
                            {(user.is_admin || user.is_super_admin) && (
                                <span className="badge badge-success" style={{ marginLeft: '8px' }}>Super Admin</span>
                              )}
                          </td>
                          <td>
                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                              {user.roles && user.roles.length > 0 ? (
                                user.roles.map((role) => (
                                  <span key={role} className="badge badge-info" style={{ fontSize: '11px' }}>
                                    {role}
                                  </span>
                                ))
                              ) : (
                                <span style={{ color: '#999' }}>No roles</span>
                              )}
                            </div>
                          </td>
                          <td>{user.groups?.join(', ') || '—'}</td>
                          <td>
                            <span className="badge badge-success">Active</span>
                          </td>
                          <td>
                            <button 
                              className="btn-sm btn-primary"
                              onClick={() => {
                                setSelectedUser(user);
                                setShowRoleModal(true);
                              }}
                            >
                              Manage Roles
                            </button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}

        {activeTab === 'roles' && (
          <div className="workstation-section">
            <h2>Roles & Permissions</h2>
            <div className="section-actions">
              <input
                type="text"
                placeholder="New role name (e.g., ROLE_NEW_ROLE)"
                value={newRoleName}
                onChange={(e) => setNewRoleName(e.target.value)}
                style={{ padding: '8px', marginRight: '10px', minWidth: '300px' }}
              />
              <button 
                className="btn-primary"
                onClick={async () => {
                  const name = newRoleName.trim();
                  if (!name) {
                    showMessage('error', 'Please enter a role name');
                    return;
                  }
                  if (!name.startsWith('ROLE_')) {
                    showMessage('error', 'Role names must start with ROLE_');
                    return;
                  }
                  try {
                    await apiClient.post('/auth/roles', { role_name: name });
                    showMessage('success', `Role '${name}' created successfully`);
                    setNewRoleName('');
                    await loadRoles();
                  } catch (error: any) {
                    const detail = error.response?.data?.detail || error.message;
                    showMessage('error', typeof detail === 'string' ? detail : 'Failed to create role');
                  }
                }}
              >
                + Create Role
              </button>
              <button className="btn-secondary" onClick={loadRoles}>🔄 Refresh</button>
            </div>
            
            {loading ? (
              <div className="loading">Loading roles...</div>
            ) : (
              <div className="data-table">
                <table>
                  <thead>
                    <tr>
                      <th>Role Name</th>
                      <th>Description</th>
                      <th>Users with Role</th>
                    </tr>
                  </thead>
                  <tbody>
                    {roles.length === 0 ? (
                      <tr>
                        <td colSpan={3} style={{ textAlign: 'center', padding: '20px' }}>
                          No roles found
                        </td>
                      </tr>
                    ) : (
                      roles.map((role) => {
                        const usersWithRole = users.filter(u => u.roles?.includes(role));
                        const roleDescriptions: Record<string, string> = {
                          'ROLE_ADMINISTRATOR': 'Super Administrator – full system access',
                          'ROLE_CASHIER': 'Payment processing',
                          'ROLE_INDEXING_OFFICER': 'Property/document indexing',
                          'ROLE_SCANNING_OPERATOR': 'Document scanning and archiving',
                          'ROLE_ARCHIVING_OFFICER': 'Document archiving',
                          'ROLE_GIS_VIEWER': 'GIS operations',
                          'ROLE_VIEWER': 'Read-only access'
                        };
                        return (
                          <tr key={role}>
                            <td><strong>{role}</strong></td>
                            <td>{roleDescriptions[role] || 'Custom role'}</td>
                            <td>
                              {usersWithRole.length > 0 ? (
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                                  {usersWithRole.map(u => (
                                    <span key={u.id} className="badge badge-info" style={{ fontSize: '11px' }}>
                                      {u.username}
                                    </span>
                                  ))}
                                </div>
                              ) : (
                                <span style={{ color: '#999' }}>No users</span>
                              )}
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}

        {activeTab === 'config' && (
          <div className="workstation-section">
            <h2>System Configuration</h2>
            <div className="config-grid">
              <div className="config-card">
                <h3>Database Settings</h3>
                <p>Configure database connections and settings</p>
                <button className="btn-primary">Configure</button>
              </div>
              <div className="config-card">
                <h3>Contentstore Settings</h3>
                <p>Manage document storage paths and settings</p>
                <button className="btn-primary">Configure</button>
              </div>
              <div className="config-card">
                <h3>API Settings</h3>
                <p>Configure API endpoints and security</p>
                <button className="btn-primary">Configure</button>
              </div>
              <div className="config-card">
                <h3>GIS Settings</h3>
                <p>Configure GIS integration and QGIS settings</p>
                <button className="btn-primary">Configure</button>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'audit' && (
          <div className="workstation-section">
            <h2>Audit Logs</h2>
            <p>View system activity and audit trails</p>
            <div className="info-card">
              <p>Audit logging feature coming soon...</p>
            </div>
          </div>
        )}

        {activeTab === 'reports' && (
          <div className="workstation-section">
            <h2>System Reports</h2>
            <div className="report-grid">
              <div className="report-card">
                <h3>User Activity Report</h3>
                <p>Generate user activity reports</p>
                <button className="btn-primary">Generate</button>
              </div>
              <div className="report-card">
                <h3>System Usage Report</h3>
                <p>View system usage statistics</p>
                <button className="btn-primary">Generate</button>
              </div>
              <div className="report-card">
                <h3>Database Statistics</h3>
                <p>View database statistics and health</p>
                <button className="btn-primary">Generate</button>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'database' && (
          <div className="workstation-section">
            <h2>Database Administration</h2>
            <div className="info-card">
              <h3>Database Information</h3>
              <p>Database: LRS43</p>
              <p>Type: MySQL</p>
              <p>Status: Connected</p>
              <div className="section-actions" style={{ marginTop: '20px' }}>
                <button className="btn-primary">Run Query</button>
                <button className="btn-secondary">Backup Database</button>
                <button className="btn-secondary">Restore Database</button>
              </div>
            </div>
          </div>
        )}
      </div>

      {showCreateModal && (
        <div className="modal-overlay" onClick={() => setShowCreateModal(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '520px' }}>
            <div className="modal-header">
              <h3>Create User</h3>
              <button className="modal-close" onClick={() => setShowCreateModal(false)}>×</button>
            </div>
            <div className="modal-body">
              <div className="form-group" style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', marginBottom: '6px', fontWeight: 600 }}>Username *</label>
                <input
                  type="text"
                  value={createUsername}
                  onChange={(e) => setCreateUsername(e.target.value)}
                  placeholder="Enter username"
                  style={{ width: '100%', padding: '8px 12px', borderRadius: '6px', border: '1px solid #ccc' }}
                  autoComplete="off"
                />
              </div>
              <div className="form-group" style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', marginBottom: '6px', fontWeight: 600 }}>Password * (min 6 characters)</label>
                <input
                  type="password"
                  value={createPassword}
                  onChange={(e) => setCreatePassword(e.target.value)}
                  placeholder="Enter password"
                  style={{ width: '100%', padding: '8px 12px', borderRadius: '6px', border: '1px solid #ccc' }}
                  autoComplete="new-password"
                />
              </div>
              <div className="form-group" style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', marginBottom: '6px', fontWeight: 600 }}>Confirm Password *</label>
                <input
                  type="password"
                  value={createPasswordConfirm}
                  onChange={(e) => setCreatePasswordConfirm(e.target.value)}
                  placeholder="Confirm password"
                  style={{ width: '100%', padding: '8px 12px', borderRadius: '6px', border: '1px solid #ccc' }}
                  autoComplete="new-password"
                />
              </div>
              <div className="form-group" style={{ marginBottom: '8px' }}>
                <label style={{ display: 'block', marginBottom: '8px', fontWeight: 600 }}>Roles</label>
                <p style={{ fontSize: '13px', color: '#666', marginBottom: '10px' }}>
                  Select one or more roles for this user. They will be able to access features according to these roles.
                </p>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                  {roles.map((role) => (
                    <label key={role} style={{ display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer' }}>
                      <input
                        type="checkbox"
                        checked={createRoles.includes(role)}
                        onChange={() => toggleCreateRole(role)}
                      />
                      <span style={{ fontSize: '13px' }}>{role}</span>
                    </label>
                  ))}
                </div>
                {roles.length === 0 && <span style={{ color: '#999' }}>Loading roles...</span>}
              </div>
            </div>
            <div className="modal-footer">
              <button className="btn-secondary" onClick={() => setShowCreateModal(false)}>Cancel</button>
              <button className="btn-primary" onClick={handleCreateUser} disabled={createSubmitting}>
                {createSubmitting ? 'Creating...' : 'Create User'}
              </button>
            </div>
          </div>
        </div>
      )}

      {showRoleModal && selectedUser && (
        <div className="modal-overlay" onClick={() => { setShowRoleModal(false); setSelectedUser(null); }}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '600px' }}>
            <div className="modal-header">
              <h3>Manage Roles for {selectedUser.username}</h3>
              <button className="modal-close" onClick={() => { setShowRoleModal(false); setSelectedUser(null); }}>×</button>
            </div>
            <div className="modal-body">
              <div style={{ marginBottom: '20px' }}>
                <h4>Current Roles:</h4>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginTop: '10px' }}>
                  {selectedUser.roles && selectedUser.roles.length > 0 ? (
                    selectedUser.roles.map((role) => (
                      <span key={role} className="badge badge-info" style={{ fontSize: '12px', padding: '6px 12px' }}>
                        {role}
                        <button
                          onClick={() => removeRole(selectedUser.username, role)}
                          style={{ marginLeft: '8px', background: 'none', border: 'none', color: '#fff', cursor: 'pointer', fontSize: '14px' }}
                        >
                          ×
                        </button>
                      </span>
                    ))
                  ) : (
                    <span style={{ color: '#999' }}>No roles assigned</span>
                  )}
                </div>
              </div>
              
              <div>
                <h4>Assign New Role:</h4>
                <select
                  onChange={(e) => {
                    if (e.target.value) {
                      assignRole(selectedUser.username, e.target.value);
                      e.target.value = '';
                    }
                  }}
                  style={{ width: '100%', padding: '8px', marginTop: '10px' }}
                >
                  <option value="">Select a role to assign...</option>
                  {roles
                    .filter(role => !selectedUser.roles?.includes(role))
                    .map(role => (
                      <option key={role} value={role}>{role}</option>
                    ))}
                </select>
              </div>
            </div>
            <div className="modal-footer">
              <button className="btn-secondary" onClick={() => { setShowRoleModal(false); setSelectedUser(null); }}>
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
