import { $, component$, useSignal, useStore, noSerialize , type NoSerialize } from "@builder.io/qwik";
import type { DocumentHead } from "@builder.io/qwik-city";
import "./auth.css";
import axios from "axios";
import { useNavigate } from "@builder.io/qwik-city";
import { setCookie } from "~/utils/cookie";
export default component$(() => {
    const navigate = useNavigate();
    const isRegistering = useSignal(false);
    const userState = useStore({
        username:  '',
        password: '',
        error: '',
        email: '',
        profile_file: null as NoSerialize<File> | null,
    });     
    const fileInputRef = useSignal<HTMLInputElement>();

    const handleFileInput = $((event: Event) => {
        const file = (event.target as HTMLInputElement).files?.[0] ?? null;
        userState.profile_file = file ? noSerialize(file) : null;
    });
    const handleSubmit = $(async () => {
        console.log(userState);
        if (isRegistering.value) {
            try {
                console.log('Register start');
                const formData = new FormData();
                if (!userState.username.trim()) {
                    userState.error = "이름을 입력해주세요.";
                    return;
                  }
                  if (!userState.password.trim()) {
                    userState.error = "비밀번호를 입력해주세요.";
                    return;
                  }
                  if (!userState.email.trim()) {
                    userState.error = "이메일을 입력해주세요.";
                    return;
                  }
                formData.append('username', userState.username.trim());
                formData.append('password', userState.password.trim());
                formData.append('email', userState.email.trim());
                if (userState.profile_file) {
                    formData.append('profile_file', userState.profile_file);
                }
                console.log(formData);
                const res = await axios.post('http://localhost:8000/api/user/register', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },  
                });
                console.log(res.data);
                console.log('Register success');
                userState.error = '';
                userState.username = '';
                userState.password = '';
                userState.email = '';
                userState.profile_file = null;
                isRegistering.value = false;
            } catch (error : any) {
                console.error('Register failed:', error);
                userState.error = error.response?.data?.detail || 'Register failed';
            }  
        } else {
            try {
                console.log('Login start');
                if (!userState.username.trim()) {
                    userState.error = "이름을 입력해주세요.";
                    return;
                  }
                  if (!userState.password.trim()) {
                    userState.error = "비밀번호를 입력해주세요.";
                    return;
                  }
                console.log(userState.username.trim(), userState.password.trim());
                const res = await axios.post('http://localhost:8000/api/user/login', {
                    username: userState.username.trim(),
                    password: userState.password.trim(),
                })
                
                const why = await axios.get('http://localhost:8000/api/avatar', {
                    headers: {
                        Authorization: `Bearer ${res.data.access_token}`,
                    },
                });
                console.log(why.data);
                console.log('Login success');
                userState.username = '';
                userState.password = '';
                userState.error = '';
                userState.email = '';
                userState.profile_file = null;
                setCookie('access_token', res.data.access_token);
                isRegistering.value = false;
                navigate('/');
            } catch (error : any) {
                console.error('Login failed:', error);
                userState.error = error.response?.data?.detail || 'Login failed';
            }
        }
    });
    return (
        <div class="flex items-center w-full h-full justify-center min-h-screen">
            <div class={`form-container flex h-full min-h-[720px] justify-center ${isRegistering.value ? 'form-expanded' : 'form-initial'} shadow-[0_6px_12px_-2px_rgba(0,0,0, 0.2)]`}>
                {isRegistering.value ? (
                    // 회원가입 
                    <div class="w-full flex flex-col lg:flex-row">
                        <div class="greeting-side"> 
                            <h1 class="md:text-4xl text-3xl font-bold mb-4">등록하기</h1>
                            <p class="mb-3 text-xs font-bold text-gray-custom opacity-70">나만의 작은 세상, 지금 만들어보세요.</p>
                            <i class="bi bi-people h-auto leading-none bg-clip-text text-transparent bg-signup-icon md:text-[15rem] text-[10rem]"></i>
                        </div>
                        <div class="form-side flex-auto ">
                            <form class="space-y-4" onSubmit$={handleSubmit} preventdefault:submit>
                                <div >
                                    <label for="email" class="block text-sm font-medium text-default">이메일 <i class="bi bi-envelope text-input-icon-color"></i></label>
                                    <input id="email" onInput$={(e) => userState.email = (e.target as HTMLInputElement).value} type="email" class="w-full p-3 border border-input-border-color rounded-xl" placeholder="이메일 입력" />
                                </div>
                                <div>
                                    <label for="username" class="block text-sm font-medium text-default">이름 <i class="bi bi-person text-input-icon-color"></i></label>
                                    <input id="username" onInput$={(e) => userState.username = (e.target as HTMLInputElement).value} type="text" class="w-full p-3 border border-input-border-color rounded-xl" placeholder="이름 입력" />
                                </div>
                                <div>
                                    <label for="password" class="block text-sm font-medium text-default">비밀번호 <i class="bi bi-lock text-input-icon-color"></i></label>
                                    <input id="password" autocomplete="new-password" onInput$={(e) => userState.password = (e.target as HTMLInputElement).value} type="password" class="w-full p-3 border border-input-border-color rounded-xl" placeholder="8~20자 영문 대소문자, 숫자, 특수문자 비밀번호 입력" />
                                </div>
                                <div>
                                    <label for="profileImage" class="block text-sm font-medium text-default">프로필 이미지 <i class="bi bi-image text-input-icon-color"></i></label>
                                    <input id="profileImage" type="file" ref={fileInputRef} onChange$={handleFileInput} accept="image/*" class="w-full p-3 border border-input-border-color rounded-xl" />
                                    
                                </div>
                                {/* <div>
                                    <label for="confirm-password"  class="block text-sm font-medium text-default">비밀번호 확인 <i class="bi bi-lock text-input-icon-color"></i></label>
                                    <input id="confirm-password" autocomplete="new-password" onInput$={(e) => userState.password = (e.target as HTMLInputElement).value} type="password" class="w-full p-3 border border-input-border-color rounded-xl" placeholder="비밀번호 다시 입력" />
                                </div> */}
                                <button type="submit" class="w-full bg-button-color-1 h-12 text-default py-3 px-4 rounded-xl hover:bg-button-color-1/1 transition-colors">
                                    회원가입
                                </button>
                                {userState.error && <p class="text-center w-full text-red-500 ">{userState.error}</p>}
                            </form>
                            <div class="mt-4 text-center flex flex-row justify-center gap-2">
                                <p> 이미 계정이 있으신가요?</p>
                                <button onClick$={() => {isRegistering.value = false; userState.username = ''; userState.password = ''; userState.email = ''; userState.profile_file = null}} class="text-gray-500 hover:text-gray-500/80 text-sm font-medium">로그인하기</button>
                            </div>
                        </div>
                    </div>
                ) : (
                    // 로그인
                    <div class="w-auto flex flex-col justify-center items-center">
                        <h1 class="text-5xl font-bold mb-2 text-center inline-block">Hello, CyWorld!</h1>
                        <p class="mb-2 text-xs font-semibold text-gray-custom opacity-70 text-center inline-block">나만의 작은 세상, 지금 만들어보세요. <i class="bi bi-emoji-smile"></i></p>
                        <div class="form-side w-full inline-block">
                            <form class="space-y-4" onSubmit$={handleSubmit} preventdefault:submit>
                            <div>
                                <label for="username" class="block text-sm font-medium text-default text-left">이름 <i class="bi bi-person text-input-icon-color"></i></label>
                                <input id="username" onInput$={(e) => userState.username = (e.target as HTMLInputElement).value} type="text" class="w-full p-3 border border-input-border-color rounded-xl" placeholder="이름 입력" />
                            </div>
                            <div>
                                <label for="password" class="block text-sm font-medium text-default text-left">비밀번호 <i class="bi bi-lock text-input-icon-color"></i></label>
                                <input id="password" autocomplete="new-password" onInput$={(e) => userState.password = (e.target as HTMLInputElement).value} type="password" class="w-full p-3 border border-input-border-color rounded-xl" placeholder="비밀번호 입력" />
                            </div>
                            <button type="submit" class="w-full bg-button-color-1 h-12 text-default py-3 px-4 rounded-xl hover:bg-opacity-80 transition-colors">로그인
                            </button>
                            {userState.error && <p class="text-center w-full text-red-500">{userState.error}</p>}
                        </form>
                        <div class="mt-4 text-center flex flex-row justify-center gap-2">
                            <p class="text-default">계정이 없으신가요?</p>
                            <button onClick$={() => {isRegistering.value = true; userState.username = ''; userState.password = ''; userState.email = ''; userState.profile_file = null}} class="text-gray-500 hover:text-gray-500/80 text-sm font-medium">회원가입하기</button>
                        </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
});

export const head: DocumentHead = {
    title: "Login / Sign Up",
    meta: [
        {
            name: "description",
            content: "Login or create a new account",
        },
    ],
};