import { useState, useEffect, useMemo } from 'react';
import { Box, Button, TextField, MenuItem } from '@mui/material';
import UserApi from '../../api/userApi';
import { useAuth } from '../../context/AuthContext';

export default function AddOrEditUserForm({ onAdd, initialData, onCancel }) {
  const { user } = useAuth();
  const thalosToken = user?.thalosToken || localStorage.getItem('thalosToken');
  const api = useMemo(() => (thalosToken ? new UserApi(thalosToken) : null), [thalosToken]);

  const [formData, setFormData] = useState({
    _Id: '',
    email: '',
    name: '',
    middleName: '',
    lastName: '',
    tenantId: '',
    roleId: '',
    status: 'Active',
    sendInvitation: true,
  });

  useEffect(() => {
    if (initialData) {
      setFormData({
        _Id: initialData._id || initialData._Id || '',
        email: initialData.email ?? '',
        name: initialData.name ?? '',
        middleName: initialData.middleName ?? '',
        lastName: initialData.lastName ?? '',
        tenantId: initialData.tenantId ?? '',
        roleId: initialData.roleId ?? '',
        status: initialData.status ?? 'Active',
        sendInvitation: true,
      });
    } else {
      setFormData({
        _Id: '',
        email: '',
        name: '',
        middleName: '',
        lastName: '',
        tenantId: '6894f9ddfb7072bdfc881613',
        roleId: '68407642ec46a0e6fe1e8ec9',
        status: 'Active',
        sendInvitation: true,
      });
    }
  }, [initialData]);

  const handleChange = (e) => {
    const { name, value } = e.target;
      setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async () => {
    try {
      if (!api) throw new Error('Missing Thalos token');

      if (initialData) {
        // UPDATE (PUT /User/Update) — API requires _Id, remove Id, displayName, tenantId
        const payload = {
          _Id: formData._Id,
          email: formData.email,
          name: formData.name,
          middleName: formData.middleName,
          lastName: formData.lastName,
          tenantId: formData.tenantId,
          roleId: formData.roleId,
          status: formData.status || 'Active',
        };
        await api.updateUser(payload);
      } else {
        // CREATE (POST /User/Create)
        const payload = {
          email: formData.email,
          name: formData.name,
          middleName: formData.middleName,
          lastName: formData.lastName,
          roleId: formData.roleId,
          tenantId: formData.tenantId,
          sendInvitation: !!formData.sendInvitation,
        };
        await api.createUser(payload);
      }

      onAdd?.();
    } catch (error) {
      console.error('Error submitting form:', error);
    }
  };

  return (
    <Box sx={{ py: 2 }}>
      <TextField
        fullWidth
        label="Email"
        name="email"
        value={formData.email}
        onChange={handleChange}
        margin="normal"
      />
      <TextField
        fullWidth 
        label="Name"
        name="name"
        value={formData.name}
        onChange={handleChange}
        margin="normal"
      />
      <TextField
        fullWidth
        label="Middle Name"
        name="middleName"
        value={formData.middleName}
        onChange={handleChange}
        margin="normal"
      />
      <TextField
        fullWidth
        label="Last Name"
        name="lastName"
        value={formData.lastName}
        onChange={handleChange}
        margin="normal"
      />
      <TextField
        fullWidth
        label="Tenant Id"
        name="tenantId"
        value={formData.tenantId}
        onChange={handleChange}
        margin="normal"
        disabled={!initialData}
      />
      <TextField
        fullWidth
        label="Role Id"
        name="roleId"
        value={formData.roleId}
        onChange={handleChange}
        margin="normal"
        disabled={!initialData}
      />
      <TextField
        fullWidth
        select
        label="Status"
        name="status"
        value={formData.status}
        onChange={handleChange}
        margin="normal"
      >
        <MenuItem value="Active">Active</MenuItem>
        <MenuItem value="Inactive">Inactive</MenuItem>
      </TextField>

      <Box display="flex" justifyContent="flex-end" mt={3} gap={1}>
        <Button onClick={onCancel} className="button-transparent">Cancel</Button>
        <Button variant="contained" onClick={handleSubmit} className="button-gold">Save</Button>
      </Box>
    </Box>
  );
}