// components/UserRegistration.js
import { useState } from 'react';
import { useToast } from '@chakra-ui/toast';
import { FormControl, FormLabel, } from '@chakra-ui/form-control';
import { Input, Button, Stack, Heading } from '@chakra-ui/react';
import { drizzle } from 'drizzle-orm/node-postgres';

export default function UserRegistration() {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
  });

  const toast = useToast();

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

  const handleSubmit = async (e) => {
    e.preventDefault();
  
    // Example of database interaction using drizzle-orm:
    const db = drizzle(/* your database connection logic */);

    try {
      // Replace 'users' with your actual table name
      await db.insert('users').values(formData);
      toast({
        title: 'Account created.',
        description: "We've created your account successfully!",
        status: 'success',
        duration: 5000,
        isClosable: true,
      });

      // Reset the form
      setFormData({ username: '', email: '', password: '' });
    } catch (error) {
      toast({
        title: 'An error occurred.',
        description: error.message,
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    }
  };

  return (
    <Stack spacing={4} w="400px" mx="auto" mt={10}>
      <Heading as="h2" size="lg">User Registration</Heading>
      <form onSubmit={handleSubmit}>
        <FormControl isRequired>
          <FormLabel>Username</FormLabel>
          <Input 
            name="username" 
            value={formData.username} 
            onChange={handleChange} 
            placeholder="Enter your username" 
          />
        </FormControl>
        
        <FormControl isRequired>
          <FormLabel>Email</FormLabel>
          <Input 
            type="email" 
            name="email" 
            value={formData.email} 
            onChange={handleChange} 
            placeholder="Enter your email" 
          />
        </FormControl>
        
        <FormControl isRequired>
          <FormLabel>Password</FormLabel>
          <Input 
            type="password" 
            name="password" 
            value={formData.password} 
            onChange={handleChange} 
            placeholder="Enter your password" 
          />
        </FormControl>
        
        <Button 
          mt={4} 
          colorScheme="teal" 
          type="submit">
          Create Account
        </Button>
      </form>
    </Stack>
  );
}
