'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { updateUser, deleteUser } from '@/lib/api';
import type { UserAccount } from '@/types';

type StatusFilter = 'all' | 'enabled' | 'disabled';

interface UserManagementProps {
  users: UserAccount[];
  loading: boolean;
  error?: string | null;
  onRefresh: () => void | Promise<void>;
  currentUserIsAdmin: boolean;
  isCheckingAccess: boolean;
}

export default function UserManagement({
  users,
  loading,
  error,
  onRefresh,
  currentUserIsAdmin,
  isCheckingAccess,
}: UserManagementProps) {
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 20;
  const [editUser, setEditUser] = useState<UserAccount | null>(null);
  const [editPassword, setEditPassword] = useState('');
  const [editSubmitting, setEditSubmitting] = useState(false);
  const [editError, setEditError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  const totalUsers = useMemo(() => users.length, [users]);
  const totalPages = useMemo(
    () => (totalUsers === 0 ? 1 : Math.ceil(totalUsers / pageSize)),
    [totalUsers],
  );

  const paginatedUsers = useMemo(() => {
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    return users.slice(start, end);
  }, [users, currentPage]);

  const handleEditClick = (user: UserAccount) => {
    setEditUser(user);
    setEditPassword('');
    setEditError(null);
  };

  const handleEditSubmit = async () => {
    if (!editUser || !editPassword.trim()) {
      setEditError('Enter a new password (min 6 characters)');
      return;
    }
    if (editPassword.length < 6) {
      setEditError('Password must be at least 6 characters');
      return;
    }
    setEditSubmitting(true);
    setEditError(null);
    try {
      await updateUser(editUser.username, { password: editPassword });
      setMessage(`Password updated for ${editUser.username}`);
      setEditUser(null);
      onRefresh();
      setTimeout(() => setMessage(null), 4000);
    } catch (err: any) {
      setEditError(err?.response?.data?.detail || err?.message || 'Failed to update user');
    } finally {
      setEditSubmitting(false);
    }
  };

  const handleDeleteClick = async (user: UserAccount) => {
    if (!confirm(`Delete user "${user.username}"? This cannot be undone.`)) return;
    try {
      await deleteUser(user.username);
      setMessage(`User ${user.username} deleted`);
      onRefresh();
      setTimeout(() => setMessage(null), 4000);
    } catch (err: any) {
      setMessage(err?.response?.data?.detail || err?.message || 'Failed to delete user');
      setTimeout(() => setMessage(null), 5000);
    }
  };

  if (isCheckingAccess) {
    return (
      <div className="loading" style={{ minHeight: 200 }}>
        <div className="spinner" />
      </div>
    );
  }

  if (!currentUserIsAdmin) {
    return (
      <div className="empty-state">
        <div className="empty-state-icon">🔐</div>
        <div className="empty-state-text">Admin privileges required to view user management.</div>
        <div className="empty-state-subtext">Please contact an administrator for access.</div>
      </div>
    );
  }

  return (
    <section className="user-management-section">
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 16 }}>
        <h2 className="section-title" style={{ color: '#ffffff', margin: 0 }}>
          User Management &amp; Roles
        </h2>
        <Link
          href="/workstation/administrator"
          style={{
            padding: '8px 16px',
            background: 'linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%)',
            color: 'white',
            borderRadius: 8,
            fontWeight: 600,
            textDecoration: 'none',
            fontSize: 14,
          }}
        >
          Create User &amp; Assign Roles →
        </Link>
      </div>

      {message && (
        <div className="alert alert-success" style={{ marginBottom: 16 }}>
          {message}
        </div>
      )}
      {error && (
        <div className="alert alert-error" style={{ marginBottom: 20 }}>
          {error}
        </div>
      )}

      {loading ? (
        <div className="loading">
          <div className="spinner" />
        </div>
      ) : (
        <>
          <div className="table-wrapper user-management-table-wrapper">
            <table className="overview-table user-management-table">
              <thead>
                <tr>
                  <th>Username</th>
                  <th>Roles</th>
                  <th style={{ width: 140 }}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {paginatedUsers.map((user) => (
                  <tr key={user.id}>
                    <td>{user.username}</td>
                    <td>
                      <div className="user-chip-list">
                        {user.roles?.length
                          ? user.roles.map((role) => (
                              <span key={role} className="user-chip">
                                {role}
                              </span>
                            ))
                          : '—'}
                      </div>
                    </td>
                    <td>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                        <button
                          type="button"
                          className="pagination-btn"
                          style={{ padding: '6px 10px', fontSize: 13 }}
                          onClick={() => handleEditClick(user)}
                        >
                          Edit
                        </button>
                        <button
                          type="button"
                          className="pagination-btn"
                          style={{ padding: '6px 10px', fontSize: 13, background: '#b91c1c', color: 'white', border: 'none' }}
                          onClick={() => handleDeleteClick(user)}
                        >
                          Delete
                        </button>
                        <Link
                          href="/workstation/administrator"
                          style={{ padding: '6px 10px', fontSize: 13, color: '#7c3aed', textDecoration: 'none' }}
                        >
                          Manage roles
                        </Link>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {totalUsers > 0 && (
            <div className="user-management-pagination">
              <div className="user-management-page-info">
                Showing{' '}
                <strong>
                  {(currentPage - 1) * pageSize + 1}-
                  {Math.min(currentPage * pageSize, totalUsers)}
                </strong>{' '}
                of <strong>{totalUsers}</strong> users
              </div>
              <div className="user-management-page-buttons">
                <button
                  type="button"
                  className="pagination-btn"
                  onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                >
                  Previous
                </button>
                <button
                  type="button"
                  className="pagination-btn"
                  onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                >
                  Next
                </button>
              </div>
            </div>
          )}

          {totalUsers === 0 && (
            <div className="empty-state" style={{ marginTop: 20 }}>
              <div className="empty-state-icon">📭</div>
              <div className="empty-state-text">No users found.</div>
            </div>
          )}

          {editUser && (
            <div
              style={{
                position: 'fixed',
                inset: 0,
                background: 'rgba(0,0,0,0.5)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 1000,
              }}
              onClick={() => !editSubmitting && setEditUser(null)}
            >
              <div
                style={{
                  background: 'var(--card-bg, #fff)',
                  padding: 24,
                  borderRadius: 12,
                  maxWidth: 400,
                  width: '90%',
                  boxShadow: '0 4px 20px rgba(0,0,0,0.2)',
                }}
                onClick={(e) => e.stopPropagation()}
              >
                <h3 style={{ marginTop: 0 }}>Edit user: {editUser.username}</h3>
                <p style={{ fontSize: 14, color: '#666', marginBottom: 16 }}>
                  Reset password. To assign or remove roles, use{' '}
                  <Link href="/workstation/administrator">Administrator Workstation</Link>.
                </p>
                <div style={{ marginBottom: 12 }}>
                  <label style={{ display: 'block', marginBottom: 4, fontWeight: 600 }}>New password</label>
                  <input
                    type="password"
                    value={editPassword}
                    onChange={(e) => setEditPassword(e.target.value)}
                    placeholder="Min 6 characters"
                    style={{ width: '100%', padding: '8px 12px', borderRadius: 6, border: '1px solid #ccc' }}
                    autoComplete="new-password"
                  />
                </div>
                {editError && <div style={{ color: '#b91c1c', fontSize: 14, marginBottom: 12 }}>{editError}</div>}
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                  <button type="button" className="pagination-btn" onClick={() => setEditUser(null)} disabled={editSubmitting}>
                    Cancel
                  </button>
                  <button type="button" className="pagination-btn" onClick={handleEditSubmit} disabled={editSubmitting} style={{ background: '#7c3aed', color: 'white', border: 'none' }}>
                    {editSubmitting ? 'Saving...' : 'Save password'}
                  </button>
                </div>
              </div>
            </div>
          )}
        </>
      )}
    </section>
  );
}


