import React, { useEffect } from 'react';
import {
  Modal,
  TextInput,
  Select,
  Button,
  Group,
  Stack,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import { userService } from '../services/userService';
import { User, CreateUserRequest, UpdateUserRequest, UserRole, UserStatus } from '../types/user';

interface UserFormProps {
  opened: boolean;
  onClose: () => void;
  onSuccess: () => void;
  editUser?: User | null;
}

const UserForm: React.FC<UserFormProps> = ({
  opened,
  onClose,
  onSuccess,
  editUser,
}) => {
  const isEditing = !!editUser;

  const form = useForm({
    initialValues: {
      email: '',
      first_name: '',
      last_name: '',
      display_name: '',
      avatar: '',
      role: 'user' as UserRole,
      status: 'pending' as UserStatus,
    },
    validate: {
      email: (value) => (/^\S+@\S+$/.test(value) ? null : 'Invalid email'),
      first_name: (value) => (value.trim().length < 1 ? 'First name is required' : null),
      last_name: (value) => (value.trim().length < 1 ? 'Last name is required' : null),
    },
  });

  // Update form values when editUser changes
  useEffect(() => {
    if (editUser) {
      form.setValues({
        email: editUser.email || '',
        first_name: editUser.first_name || '',
        last_name: editUser.last_name || '',
        display_name: editUser.display_name || '',
        avatar: editUser.avatar || '',
        role: editUser.role || 'user' as UserRole,
        status: editUser.status || 'pending' as UserStatus,
      });
    } else {
      // Reset to default values when not editing
      form.setValues({
        email: '',
        first_name: '',
        last_name: '',
        display_name: '',
        avatar: '',
        role: 'user' as UserRole,
        status: 'pending' as UserStatus,
      });
    }
  }, [editUser, opened]);

  const handleSubmit = async (values: typeof form.values) => {
    try {
      if (isEditing && editUser) {
        const updateRequest: UpdateUserRequest = {
          email: values.email !== editUser.email ? values.email : undefined,
          first_name: values.first_name !== editUser.first_name ? values.first_name : undefined,
          last_name: values.last_name !== editUser.last_name ? values.last_name : undefined,
          display_name: values.display_name !== editUser.display_name ? values.display_name : undefined,
          avatar: values.avatar !== editUser.avatar ? values.avatar : undefined,
          role: values.role !== editUser.role ? values.role : undefined,
          status: values.status !== editUser.status ? values.status : undefined,
        };

        // Only send fields that have changed
        const hasChanges = Object.values(updateRequest).some(value => value !== undefined);
        if (!hasChanges) {
          notifications.show({
            title: 'No Changes',
            message: 'No changes detected',
            color: 'blue',
          });
          onClose();
          return;
        }

        await userService.updateUser(editUser.id, updateRequest);
        notifications.show({
          title: 'Success',
          message: 'User updated successfully',
          color: 'green',
        });
      } else {
        const createRequest: CreateUserRequest = {
          email: values.email,
          first_name: values.first_name,
          last_name: values.last_name,
          display_name: values.display_name || undefined,
          avatar: values.avatar || undefined,
          role: values.role,
          status: values.status,
        };

        await userService.createUser(createRequest);
        notifications.show({
          title: 'Success',
          message: 'User created successfully',
          color: 'green',
        });
      }

      onSuccess();
      onClose();
      form.reset();
    } catch (error: any) {
      console.error('Failed to save user:', error);
      notifications.show({
        title: 'Error',
        message: error.message || 'Failed to save user',
        color: 'red',
      });
    }
  };

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      title={isEditing ? 'Edit User' : 'Create User'}
      size="md"
    >
      <form onSubmit={form.onSubmit(handleSubmit)}>
        <Stack gap="md">
          <Group grow>
            <TextInput
              label="First Name"
              placeholder="Enter first name"
              required
              {...form.getInputProps('first_name')}
            />
            <TextInput
              label="Last Name"
              placeholder="Enter last name"
              required
              {...form.getInputProps('last_name')}
            />
          </Group>

          <TextInput
            label="Display Name"
            placeholder="Enter display name (optional)"
            {...form.getInputProps('display_name')}
          />

          <TextInput
            label="Email"
            placeholder="Enter email address"
            required
            type="email"
            {...form.getInputProps('email')}
          />

          <TextInput
            label="Avatar URL"
            placeholder="Enter avatar URL (optional)"
            {...form.getInputProps('avatar')}
          />

          <Group grow>
            <Select
              label="Role"
              placeholder="Select role"
              required
              data={[
                { value: 'admin', label: 'Admin' },
                { value: 'moderator', label: 'Moderator' },
                { value: 'user', label: 'User' },
                { value: 'viewer', label: 'Viewer' },
              ]}
              {...form.getInputProps('role')}
            />
            <Select
              label="Status"
              placeholder="Select status"
              required
              data={[
                { value: 'active', label: 'Active' },
                { value: 'inactive', label: 'Inactive' },
                { value: 'suspended', label: 'Suspended' },
                { value: 'pending', label: 'Pending' },
              ]}
              {...form.getInputProps('status')}
            />
          </Group>

          <Group justify="flex-end" mt="md">
            <Button variant="light" onClick={onClose}>
              Cancel
            </Button>
            <Button type="submit">
              {isEditing ? 'Update' : 'Create'} User
            </Button>
          </Group>
        </Stack>
      </form>
    </Modal>
  );
};

export default UserForm;