'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Input from '@/app/components/Input';
import AddressSuggestions from '@/app/components/AddressSuggestions';

const RegisterPage = () => {
  const [role, setRole] = useState<'PRIVATE' | 'BUSINESS' | null>(null); // Initially, no role is selected
  const [name, setName] = useState('');
  const [company, setCompany] = useState('');
  const [address, setAddress] = useState('');
  const [postcode, setPostcode] = useState('');
  const [city, setCity] = useState('');
  const [phone, setPhone] = useState('');
  const [privatePhone, setPrivatePhone] = useState('');
  const [email, setEmail] = useState('');
  const [cvr, setCvr] = useState('');
  const [password, setPassword] = useState('');
  const router = useRouter();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
  
    const userData: any = {
      name,
      address,
      postcode,
      city,
      phone,
      email,
      password,
      role,
    };
  
    if (role === 'BUSINESS') {
      userData.company = company;
      userData.privatePhone = privatePhone;
      userData.cvr = cvr;
    }
  
    console.log('Submitting user data:', userData); // Log form data before submission
  
    const res = await fetch('/api/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userData),
    });
  
    if (res.ok) {
      router.push('/user/login');
    } else {
      const errorData = await res.json();
      console.error('Failed to register:', errorData); // Log the error response from the server
    }
  };

  return (
    <div className="flex flex-col justify-center items-center h-screen bg-gray-100">
      {/* Registration Header */}
      <div className="mb-8 text-center">
        <h2 className="text-3xl font-bold mb-4">Register Here</h2>
        <p className="text-gray-600">Please select whether you're a Private or Business user to register.</p>
      </div>

      {/* Role Selection */}
      {role === null && (
        <div className="flex space-x-4 mb-6">
          <button
            className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-6 rounded focus:outline-none focus:shadow-outline"
            onClick={() => setRole('PRIVATE')}
          >
            Private
          </button>
          <button
            className="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-6 rounded focus:outline-none focus:shadow-outline"
            onClick={() => setRole('BUSINESS')}
          >
            Business
          </button>
        </div>
      )}

      {/* Registration Form */}
      {role && (
        <div className="bg-white p-8 rounded-lg shadow-md w-96">
          <h3 className="text-2xl font-bold mb-4">
            {role === 'PRIVATE' ? 'Private Registration' : 'Business Registration'}
          </h3>

          <form onSubmit={handleSubmit}>
            <Input 
              id="name"
              type="text"
              label="Name"
              required
              setChange={(e) => setName(e.target.value)}
              value={name}
            />

            {role === 'BUSINESS' && (
              <>
                <Input
                  id="company"
                  type="text"
                  label="Company"
                  required={role === 'BUSINESS'}
                  setChange={(e) => setCompany(e.target.value)}
                  value={company}
                />

                <Input 
                  id="privatePhone"
                  type="text"
                  label="Private Phone"
                  required={role === 'BUSINESS'}
                  setChange={(e) => setPrivatePhone(e.target.value)}
                  value={privatePhone}
                />

                <Input 
                  id="cvr"
                  type="text"
                  label="CVR"
                  required={role === 'BUSINESS'}
                  setChange={(e) => setCvr(e.target.value)}
                  value={cvr}
                />
              </>
            )}

            {/* Address Input */}
            <AddressSuggestions
              address={address}
              setAddress={setAddress}
              postcode={postcode}
              setPostcode={setPostcode}
              setCity={setCity}
            />
            {/* Postcode Input */}
            <Input
              id="postcode"
              label="Postcode"
              type="text"
              value={postcode}
              setChange={(e) => setPostcode(e.target.value)}
              required
            />
            {/* City Input */}
            <Input
              id="city"
              label="City"
              type="text"
              value={city}
              setChange={(e) => setCity(e.target.value)}
              required
            />

            <Input 
              id="phone"
              type="text"
              label="Phone"
              required
              setChange={(e) => setPhone(e.target.value)}
              value={phone}
            />

            <Input 
              id="email"
              type="email"
              label="Email"
              required
              setChange={(e) => setEmail(e.target.value)}
              value={email}
            />

            <Input 
              id="password"
              type="password"
              label="Password"
              required
              setChange={(e) => setPassword(e.target.value)}
              value={password}
            />

            <button
              type="submit"
              className="w-full bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
            >
              Register
            </button>
          </form>
        </div>
      )}

      {/* Already Registered */}
      <div className="mt-6">
        <p className="text-gray-600">
          Already registered?{' '}
          <Link href="/user/login" className="text-blue-500 hover:underline">
            Login here
          </Link>
        </p>
      </div>
    </div>
  );
};

export default RegisterPage;