import React, { useState, useEffect } from "react";
import { Api } from "../client/auth_client";
import {UnAuthorized} from './Auth.tsx'
import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/style.css';
import './AccountSettings.css';
import {useNavigate} from "react-router-dom";

const AccountSettings: React.FC = () => {
    const [email, setEmail] = useState<string | null>();
    const [dialCodeAndPhoneNumber, setDialCodeAndPhoneNumber] = useState<string>("");
    const [dialCode, setDialCode] = useState<string | null>();
    const [phoneNumber, setPhoneNumber] = useState<string |null>();
    const [currentPassword, setCurrentPassword] = useState("");
    const [newPassword, setNewPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [problem, setProblem] = useState<string | null>(null);
    const [view, setView] = useState<"profile" | "password">("profile");
    const [isOk, setOk] = useState<boolean>(false);
    const navigate = useNavigate();

    useEffect(() => {
        const getUserDetail = async () => {
            const token = localStorage.getItem("authToken");
            const client = new Api({
                baseUrl: "/auth",
                securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
            });

            const result = await client.account.getMyDetailCreate();

            if (result?.data) {
                const dialCode = result.data.dialCode ?? "";
                const phoneNumber = result.data.phone ?? "";

                setDialCode(dialCode);
                setPhoneNumber(phoneNumber);
                setDialCodeAndPhoneNumber(dialCode + phoneNumber);
                setEmail(result.data.email);
            }
            setOk(true);
        };

        getUserDetail().then();
    }, []);

    const handleSaveEmailChanges = async () => {
        try {
            setProblem(null);

            const token = localStorage.getItem("authToken");
            const client = new Api({
                baseUrl: "/auth",
                securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
            });

            const emailResponse = await client.account.updateUserEmailCreate({ newEmail: email });

            if(emailResponse.status === 401) await UnAuthorized(navigate)

            if (!emailResponse.data.updateSuccess) {
                setProblem("Failed to update email: " + JSON.stringify(emailResponse.data.problems));
                return;
            }

            alert("Email changes saved successfully!");
        } catch (error) {
            setProblem("An error occurred while saving email changes. Please try again.");
            console.error("Error saving email changes", error);
        }
    };

    const handleSavePhoneChanges = async () => {
        try {
            setProblem(null);

            const token = localStorage.getItem("authToken");
            const client = new Api({
                baseUrl: "/auth",
                securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
            });

            const phoneResponse = await client.account.updatePhoneNumberCreate({
                prefix: dialCode,
                number: phoneNumber,
            });

            if(phoneResponse.status === 401) await UnAuthorized(navigate)

            if (!phoneResponse.data.updateSuccess) {
                setProblem("Failed to update phone: " + JSON.stringify(phoneResponse.data.problems));
                return;
            }

            alert("Phone changes saved successfully!");
        } catch (error) {
            setProblem("An error occurred while saving phone changes. Please try again.");
            console.error("Error saving phone changes", error);
        }
    };

    const handleChangePassword = async () => {
        const token = localStorage.getItem("authToken");
        const client = new Api({
            baseUrl: "/auth",
            securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
        });

        try {
            setProblem(null);

            if (newPassword && newPassword === confirmPassword) {
                const passwordResponse = await client.account.changePasswordCreate({
                    password: currentPassword,
                    newPassword1: newPassword,
                    newPassword2: confirmPassword,
                    logOutAllSession: false
                });

                setCurrentPassword("")
                setConfirmPassword("")
                setNewPassword("")

                if(passwordResponse.status === 401) await UnAuthorized(navigate)

                if (!passwordResponse.data.isSuccess) {
                    setProblem("Failed to change password: " + passwordResponse.data.mess);
                    return;
                }

                alert("Password changed successfully!");
            } else if (newPassword !== confirmPassword) {
                setProblem("New password and confirm password do not match.");
            }
        } catch (error) {
            setProblem("An error occurred while changing the password. Please try again.");
            console.error("Error changing password", error);
        }
    };

    if (!isOk) {
        return (
            <div className="loading-screen">
                <div className="spinner">
                    <div className="lds-ring">
                        <div></div>
                        <div></div>
                        <div></div>
                        <div></div>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="settings-container">
            <div className="settings-sidebar">
                <h2>Account Settings</h2>

                <div className="toggle-buttons">
                    <button
                        className={`btn ${view === "profile" ? "btn-selected" : ""}`}
                        onClick={() => setView("profile")}
                    >
                        Profile Changes
                    </button>
                    <button
                        className={`btn ${view === "password" ? "btn-selected" : ""}`}
                        onClick={() => setView("password")}
                    >
                        Password Changes
                    </button>
                </div>
            </div>

            <div className="settings-content">
                <div className="toggle-form-container">
                    <div className="divider-line-vertical"></div>

                    {view === "profile" && (
                        <div className="settings-section">
                            <h4>Profile Information</h4>

                            <div className="form-group">
                                <label>Email</label>
                                <div className="input-button-container">
                                    <input
                                        type="email"
                                        value={email ?? ""}
                                        onChange={(e) => setEmail(e.target.value)}
                                        className="form-control compact-input"
                                    />
                                    <button className="btn btn-primary" onClick={handleSaveEmailChanges}>
                                        Save Email Changes
                                    </button>
                                </div>
                            </div>


                            <div className="form-group">
                                <label>Phone</label>
                                <PhoneInput
                                    country={'pl'}
                                    value={dialCodeAndPhoneNumber}
                                    onChange={(phone, data) => {
                                        let lenOfDialCode : number = 0;
                                        if ("dialCode" in data) {
                                            lenOfDialCode = data.dialCode.length;
                                            setDialCode(data.dialCode);
                                        }

                                        const phoneNumber = phone.slice(lenOfDialCode, phone.length);

                                        setPhoneNumber(phoneNumber);

                                        setDialCodeAndPhoneNumber(phone)

                                    }}
                                    inputProps={{
                                        name: 'phone',
                                        required: true,
                                    }}
                                />
                                <button className="btn btn-primary" onClick={handleSavePhoneChanges}>
                                    Save Phone Changes
                                </button>
                            </div>

                        </div>
                        )}

                    {view === "password" && (
                        <div className="settings-section">
                            <h4>Change Password</h4>
                            <div className="form-group">
                                <label>Current Password</label>
                                <input
                                    type="password"
                                    value={currentPassword}
                                    onChange={(e) => setCurrentPassword(e.target.value)}
                                    className="form-control compact-input"
                                />
                            </div>

                            <div className="form-group">
                                <label>New Password</label>
                                <input
                                    type="password"
                                    value={newPassword}
                                    onChange={(e) => setNewPassword(e.target.value)}
                                            className="form-control compact-input"
                                        />
                                    </div>

                                    <div className="form-group">
                                        <label>Confirm New Password</label>
                                        <input
                                            type="password"
                                            value={confirmPassword}
                                            onChange={(e) => setConfirmPassword(e.target.value)}
                                            className="form-control compact-input"
                                        />
                                    </div>

                                    <button className="btn btn-primary compact-button" onClick={handleChangePassword}>
                                        Change Password
                                    </button>

                                    {problem && <div className="problem-field">{problem}</div>}
                                </div>
                            )}
                </div>
            </div>
        </div>
    );
};

export default AccountSettings;
