import { Flex, Input, Form, Button, Card, Space, Image } from 'antd';
import React from 'react';
import handleSignIn from '../../Utils/Auth/SignIn';
import sypiu_ggcp from 'assets/sypiu_ggcp.jpg';
import logo from 'assets/freepik/LOGOPIU.png';
import { useNavigate } from 'react-router-dom';
import { NotifAlert } from '../../components/Global/ToastNotif';
import { decryptData } from '../../components/Global/Formatter';

const SignIn = () => {
    const [captchaSvg, setCaptchaSvg] = React.useState('');
    const [userInput, setUserInput] = React.useState('');
    const [message, setMessage] = React.useState('');
    const [captchaText, setcaptchaText] = React.useState('');

    const navigate = useNavigate();
    // let url = `${import.meta.env.VITE_API_SERVER}/users`;

    React.useEffect(() => {
        fetchCaptcha();
    }, []);

    // Fetch the CAPTCHA SVG from the backend
    const fetchCaptcha = async () => {
        try {
            // let url = `${import.meta.env.VITE_API_SERVER}/operation`
            // const response = await fetch('http://localhost:9528/generate-captcha');
            const response = await fetch(
                `${import.meta.env.VITE_API_SERVER}/auth/generate-captcha`,
                {
                    credentials: 'include', // Wajib untuk mengirim cookie
                }
            );

            // Ambil header
            const captchaToken = response.headers.get('X-Captcha-Token');

            // console.log('Captcha Token:', decryptData(captchaToken));

            setcaptchaText(decryptData(captchaToken));

            const data = await response.text();
            setCaptchaSvg(data);
        } catch (error) {
            console.error('Error fetching CAPTCHA:', error);
        }
    };

    const handleOnSubmit = async (e) => {
        // console.log('Received values of form: ', e);
        // e.preventDefault();

        try {
            // const response = await fetch(`${import.meta.env.VITE_API_SERVER}/auth/verify-captcha`, {
            //     method: 'POST',
            //     headers: { 'Content-Type': 'application/json' },
            //     credentials: 'include', // WAJIB: Agar cookie CAPTCHA dikirim
            //     body: JSON.stringify({ captcha: userInput }),
            // });

            // const data = await response.json();
            // console.log(data);

            const data = {
                success: captchaText === userInput ? true : false,
            };

            if (data.success) {
                setMessage('CAPTCHA verified successfully!');
                await handleSignIn(e);
            } else {
                setMessage('CAPTCHA verification failed. Try again.');
                fetchCaptcha(); // Refresh CAPTCHA on failure
                NotifAlert({
                    icon: 'error',
                    title: 'Gagal',
                    message: data.message || 'CAPTCHA verification failed. Try again.',
                });
            }
        } catch (error) {
            console.error('Error verifying CAPTCHA:', error);
            setMessage('An error occurred. Please try again.');
        }

        setUserInput(''); // Clear the input field
    };

    const moveToRegistration = (e) => {
        // e.preventDefault();
        // navigate("/signup")
        navigate('/registration');
    };

    return (
        <>
            <Flex
                align="center"
                justify="center"
                // vertical
                style={{
                    height: '100vh',
                    // marginTop: '10vh',
                    // backgroundImage: `url('https://via.placeholder.com/300')`,
                    backgroundImage: `url(${sypiu_ggcp})`,
                    backgroundSize: 'cover',
                    backgroundPosition: 'center',
                }}
            >
                <Card
                    style={{
                        boxShadow: '0px 4px 8px rgba(0, 0, 0, 0.1)',
                    }}
                >
                    <Flex align="center" justify="center">
                        <Image
                            // src="/src/assets/freepik/LOGOPIU.png"
                            src={logo}
                            height={150}
                            width={220}
                            preview={false}
                            alt="signin"
                        />
                    </Flex>
                    <br />
                    <Form onFinish={handleOnSubmit} layout="vertical" style={{ width: '250px' }}>
                        <Form.Item
                            label="Username"
                            name="username"
                            rules={[
                                {
                                    required: true,
                                    // type: "email",
                                },
                            ]}
                        >
                            <Input placeholder="username" size="large" />
                        </Form.Item>

                        <Form.Item
                            label="Password"
                            name="password"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your password!',
                                },
                            ]}
                        >
                            <Input.Password placeholder="password" size="large" />
                        </Form.Item>
                        <div
                            style={{ marginLeft: 45 }}
                            dangerouslySetInnerHTML={{ __html: captchaSvg }}
                        />
                        {/* {message} */}
                        <Input
                            style={{ marginTop: 10, marginBottom: 15 }}
                            type="text"
                            placeholder="Enter CAPTCHA text"
                            size="large"
                            value={userInput}
                            onChange={(e) => setUserInput(e.target.value)}
                        />

                        <Form.Item>
                            <Space direction="vertical" style={{ width: '100%' }}>
                                <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
                                    Sign In
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                    <Button
                        type="primary"
                        htmlType="submit"
                        style={{ width: '100%' }}
                        onClick={() => moveToRegistration()}
                    >
                        Registration
                    </Button>
                </Card>
            </Flex>
        </>
    );
};

export default SignIn;
