import { useEffect, useState } from 'react';
import axios from 'axios';

function CreateUser() {
  const [employees, setEmployees] = useState([]);
  const [selectedEmployeeId, setSelectedEmployeeId] = useState('');
  const [password, setPassword] = useState('');
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [user, setUser] = useState(null);

  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }

    axios
      .get('/api/auth/me', {
        withCredentials: true,
      })
      .then((response) => {
        setUser(response.data.user);
        localStorage.setItem('user', JSON.stringify(response.data.user));
      })
      .catch((err) => {
        setError(err.response?.data?.message || 'Unable to verify admin rights');
      });
  }, []);

  useEffect(() => {
    if (!user || user.role !== 'admin') return;

    axios
      .get('/api/employees/list', {
        withCredentials: true,
      })
      .then((response) => setEmployees(response.data))
      .catch((err) => setError(err.response?.data?.message || 'Could not load employees'));
  }, [user]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setMessage('');

    if (!selectedEmployeeId) {
      setError('Please select an existing employee.');
      return;
    }

    if (password.length < 6) {
      setError('Password must be at least 6 characters long.');
      return;
    }

    setLoading(true);

    try {
      const response = await axios.post(
        '/api/auth/users',
        {
          employeeId: selectedEmployeeId,
          password,
        },
        {
          withCredentials: true,
        }
      );

      setMessage(`User account created for ${response.data.user.name}.`);
      setSelectedEmployeeId('');
      setPassword('');
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to create user account');
      console.error(err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  if (!user) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm">
        <h1 className="mb-4 text-2xl font-bold">Create User</h1>
        <p className="text-sm text-gray-600">Loading your account...</p>
      </div>
    );
  }

  if (user.role !== 'admin') {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm">
        <h1 className="mb-4 text-2xl font-bold">Access Denied</h1>
        <p className="text-sm text-gray-600">Only admins can create dashboard users.</p>
      </div>
    );
  }

  return (
    <div className="rounded-xl bg-white p-6 shadow-sm">
      <h1 className="mb-4 text-2xl font-bold">Create Dashboard User</h1>
      <p className="mb-4 text-sm text-gray-600">
        Choose an existing employee and assign a password. New users will be created with the <strong>user</strong> role.
      </p>

      {message && <p className="alert-success mb-4">{message}</p>}
      {error && <p className="alert-error mb-4">{error}</p>}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="mb-1 block text-sm font-medium">Employee</label>
          <select
            value={selectedEmployeeId}
            onChange={(e) => setSelectedEmployeeId(e.target.value)}
            className="input-field w-full"
          >
            <option value="">Select an employee</option>
            {employees.map((employee) => (
              <option key={employee._id} value={employee._id}>
                {employee.firstName} {employee.lastName} — {employee.email}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="mb-1 block text-sm font-medium">Password</label>
          <input
            type="password"
            required
            minLength={6}
            placeholder="Enter a password for this user"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="input-field w-full"
          />
        </div>

        <button type="submit" disabled={loading} className="btn-primary w-full">
          {loading ? 'Creating user...' : 'Create User'}
        </button>
      </form>
    </div>
  );
}

export default CreateUser;

