'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import Input from '../../components/Input';
import Image from "next/image";
import Button from '../../components/Button';
import Link from 'next/link';
import axios from 'axios';

export default function RegisterPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    fullName: '',
    email: '',
    password: '',
    confirmPassword: ''
  });
  const [errors, setErrors] = useState<{[key: string]: string}>({});
  const [isLoading, setIsLoading] = useState(false);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));

    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (validateForm()) {
      setIsLoading(true);
      
      try {
        await axios.post('/lib/api/auth/signup-step1', {
            email: formData.email,
            fullName: formData.fullName,
            password: formData.password,
          });

        router.push('/complete-registration');
        
      } catch (error) {
        console.error('Error during initial signup:', error);
      } finally {
        setIsLoading(false);
      }
    }
  };
    
  const validateForm = () => {
    const newErrors: {[key: string]: string} = {};

    if (!formData.fullName.trim()) {
      newErrors.fullName = 'Full name is required';
    }

    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Please enter a valid email address';
    }

    if (!formData.password) {
      newErrors.password = 'Password is required';
    } else if (formData.password.length < 8) {
      newErrors.password = 'Password must be at least 8 characters';
    } else if (!/(?=.*[0-9])(?=.*[!@#$%^&*])/.test(formData.password)) {
      newErrors.password = 'Password must include a number and a special character';
    }

    if (!formData.confirmPassword) {
      newErrors.confirmPassword = 'Please confirm your password';
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = 'Passwords do not match';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  return (
    <div className="min-h-screen flex flex-col md:flex-row bg-white">
      <div className="w-full md:w-[45%] relative h-64 md:h-auto ">
        <Image
          src="/assets/AuthImage.png"
          alt="Auth Image"
          fill
          sizes="(max-width: 768px) 100vw, 45vw"
          className="object-cover"
          priority
        />
      </div>

      <div className="w-full md:w-[55%] flex items-center justify-center mt-10">
        <div className="w-full max-w-[75%] px-6">
          {/* Progress indicator */}
          <div className="flex items-center justify-center mb-8">
            <div className="flex items-center">
              <div className="w-8 h-8 bg-[#521392] rounded-full flex items-center justify-center text-white text-sm font-medium">
                1
              </div>
              <div className="w-16 h-0.5 bg-gray-300"></div>
              <div className="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center text-gray-500 text-sm font-medium">
                2
              </div>
              <div className="w-16 h-0.5 bg-gray-300"></div>
              <div className="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center text-gray-500 text-sm font-medium">
                3
              </div>
              <div className="w-16 h-0.5 bg-gray-300"></div>
              <div className="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center text-gray-500 text-sm font-medium">
                4
              </div>
            </div>
          </div>

          <div className="mb-6">
            <h1 className="text-3xl font-semibold text-gray-900 mb-2">
              Create your account
            </h1>
            <p className="text-[#1C1C1C80]">
              Join thousands of people in building your own financial freedom and start living your life
            </p>
          </div>

          <form onSubmit={handleSubmit}>
            <Input
              label="Full name"
              name="fullName"
              type="text"
              placeholder="John Andrew"
              value={formData.fullName}
              onChange={handleInputChange}
              error={errors.fullName}
              disabled={isLoading}
            />

            <Input
              label="Email address"
              name="email"
              type="email"
              placeholder="e.g. johnandrew@gmail.com"
              value={formData.email}
              onChange={handleInputChange}
              error={errors.email}
              disabled={isLoading}
            />

            <Input
              label="Password"
              name="password"
              type="password"
              placeholder="••••••••••••••••"
              value={formData.password}
              onChange={handleInputChange}
              error={errors.password}
              disabled={isLoading}
            />

            <Input
              label="Confirm password"
              name="confirmPassword"
              type="password"
              placeholder="••••••••••••••••"
              value={formData.confirmPassword}
              onChange={handleInputChange}
              error={errors.confirmPassword}
              disabled={isLoading}
            />

            <p className="text-[12px] text-gray-500 mb-4">
              Password must be at least 8 characters, including a number and a special character
            </p>

            <Button 
              type="submit" 
              disabled={isLoading}
              width="w-full"
            >
              {isLoading ? 'Processing...' : 'Continue'}
            </Button>

            <div className="mt-6 text-center">
              <Link href="/" className="text-[#541592] hover:text-purple-500 font-medium">
                Login
              </Link>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}