// src/pages/RegisterPage.tsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useUser } from '../contexts/UserContext'; // custom hook to access user context
import api from '../utils/api';                 // centralized Axios instance

interface FormDataShape {
    username: string;
    email: string;
    password: string;
    profileImage: File | null;
    bio: string;
}

const RegisterPage: React.FC = () => {

    const navigate = useNavigate();
    const { loginWithCredentials } = useUser();

    const [formData, setFormData] = useState<FormDataShape>({
        username: '',
        email: '',
        password: '',
        profileImage: null,
        bio: '',
    });

    const handleChange = (
        e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>,
    ) => {
        const { id, value } = e.target as HTMLInputElement;

        if (id === 'profileImage' && e.target instanceof HTMLInputElement) {
            const file = e.target.files?.[0];
            if (file) {
                if (!file.type.startsWith('image/')) {
                    alert('Please upload a valid image file.');
                    return;
                }
                setFormData(prev => ({ ...prev, profileImage: file }));
            }
        } else {
            setFormData(prev => ({ ...prev, [id]: value }));
        }
    };

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

        try {
            // STEP 1: create user
            const userPayload = {
                username: formData.username,
                email: formData.email,
                password: formData.password,
                bio: formData.bio || ''
            };

            await api.post('/user/register', userPayload, {
                headers: { 'Content-Type': 'application/json' },
            }).then(async res => {
                if (res.status === 200) {
                    // STEP 2: upload profile image (optional)
                    if (formData.profileImage) {
                        const fileData = new FormData();
                        fileData.append('file', formData.profileImage);

                        await api.post('/profile/uploadprofileimage', fileData, {
                            headers: { 'Content-Type': 'multipart/form-data' },
                        });
                    }

                    // STEP 3: login via context
                    await loginWithCredentials({
                        username: formData.username,
                        password: formData.password,
                    });

                    navigate('/');
                }
            })
                .catch(error => {
                    if (error.response?.status === 401) {
                        alert("Neplatné uživatelské jméno nebo heslo");
                    }

                    else if (error.response?.status === 409) {
                        alert("Účet s uživatelským jménem nebo emailem již existuje");
                    }

                    else {
                        alert("Nastala chyba při přihlašování");
                    }
                });
            ;


        } catch (err) {
            console.error('Failed to register:', err);
            alert('Registrace se nezdařila. Zkuste to prosím znovu.');
        }
    };



    return (
        <div
            className="min-h-screen p-8 flex justify-center items-center"
            style={{
                backgroundImage:
                    "url('https://www.collegetransitions.com/wp-content/uploads/2024/03/math-formulas.jpg')",
                backgroundSize: 'cover',
                backgroundPosition: 'center',
            }}
        >
            <form
                onSubmit={handleSubmit}
                className="bg-white border border-gray-200 rounded-lg shadow-md p-8 w-full max-w-md"
            >
                <h2 className="text-2x1 font-bold text-center mb-6">Registrace</h2>

                {/* username */}
                <div className="flex flex-col mb-4">
                    <label htmlFor="username">Uživatelské jméno *</label>
                    <input
                        id="username"
                        type="text"
                        required
                        value={formData.username}
                        onChange={handleChange}
                        className="border border-gray-300 rounded px-3 py-2 focus:outline-none focus:border-green-800"
                    />
                </div>

                {/* email */}
                <div className="flex flex-col mb-4">
                    <label htmlFor="email">Email *</label>
                    <input
                        id="email"
                        type="email"
                        required
                        value={formData.email}
                        onChange={handleChange}
                        className="border border-gray-300 rounded px-3 py-2 focus:outline-none focus:border-green-800"
                    />
                </div>

                {/* password */}
                <div className="flex flex-col mb-4">
                    <label htmlFor="password">Heslo *</label>
                    <input
                        id="password"
                        type="password"
                        required
                        value={formData.password}
                        onChange={handleChange}
                        className="border border-gray-300 rounded px-3 py-2 focus:outline-none focus:border-green-800"
                    />
                </div>

                {/* profile image */}
                <div className="flex flex-col mb-4">
                    <label htmlFor="profileImage">Profilový obrázek</label>
                    <input
                        id="profileImage"
                        type="file"
                        accept="image/*"
                        onChange={handleChange}
                        className="border border-gray-300 rounded p-3 focus:outline-none"
                    />
                </div>

                {/* bio */}
                <div className="flex flex-col mb-4">
                    <label htmlFor="bio" className="mb-2 text-sm font-medium text-gray-700">
                        Bio
                    </label>
                    <textarea
                        id="bio"
                        rows={4}
                        value={formData.bio}
                        onChange={handleChange}
                        className="resize-none px-3 py-2 border border-gray-300 rounded focus:outline-none focus:border-green-800"
                    />
                </div>

                <button
                    type="submit"
                    className="w-full py-3 bg-green-900 text-white font-semibold rounded hover:bg-green-800 transition"
                >
                    Zaregistrovat
                </button>

                <p className="text-gray-400 mt-2">* - povinný údaj</p>
            </form>
        </div>
    );
};

export default RegisterPage;
