import React, { useContext, useEffect, useState } from 'react'
import { ConfigContext } from '../Context/ConfigContext';
import axios from 'axios';
import { formatDate } from '../Components/GlobalFunctions';
import Swal from "sweetalert2"
import { ContentLoader } from '../Components/Shimmer';
import PageTitle from '../Components/PageTitle';
import { SubmitBtn } from '../Components/InputElements';

const AccountInformation = () => {

    const { apiURL, apiHeaderJson, apiHeaderFile, user_profile_id, user_id } = useContext(ConfigContext);

    const [formData, setFormData] = useState({
        profile_name: "",
        profile_about: "",
        qid: "",
        digitalSign: null,
        profile_picture: null,
        profile_address: "",
        profile_contact_number: "",
        profile_whatsapp: "",
        profile_email: ""
    });

    const [loginInfo, setLoginInfo] = useState({
        login_id: "",
        login_password: "",
        panel_type: "",
    });

    const [newPassword, setNewPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [showNewPass, setShowNewPass] = useState(false);
    const [showConfirmPass, setShowConfirmPass] = useState(false);

    const [showModal, setShowModal] = useState(false);
    const [errors, setErrors] = useState({});
    const [loading, setLoading] = useState(true);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleDigitalSignUpload = (e) => {
        const file = e.target.files[0];
        if (!file) return;

        if (!file.type.startsWith("image/")) {
            return Swal.fire("Error", "Please upload an image file", "error");
        }

        if (file.size > 2 * 1024 * 1024) {
            return Swal.fire("Error", "File size must be less than 2MB", "error");
        }

        setFormData(prev => ({
            ...prev,
            digitalSign: file
        }));
    };

    const handleLogoUpload = (e) => {
        const file = e.target.files[0];
        if (!file) return;

        if (!file.type.startsWith("image/")) {
            return Swal.fire("Error", "Please upload an image file", "error");
        }

        if (file.size > 2 * 1024 * 1024) {
            return Swal.fire("Error", "File size must be less than 2MB", "error");
        }

        setFormData(prev => ({
            ...prev,
            profile_picture: file
        }));
    };

    const validateForm = () => {
        const err = {};

        if (!formData.profile_name?.trim())
            err.profile_name = "Client name is required";

        if (!formData.profile_email?.trim())
            err.profile_email = "Email is required";
        else if (!/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(formData.profile_email))
            err.profile_email = "Enter a valid email address";

        if (!formData.profile_contact_number?.trim())
            err.profile_contact_number = "Contact number is required";

        if (!formData.qid?.trim())
            err.qid = "QID is required";

        if (!formData.profile_address?.trim())
            err.profile_address = "Address is required";

        if (!formData.profile_about?.trim())
            err.profile_about = "About is required";

        if (!formData.profile_whatsapp?.trim())
            err.profile_whatsapp = "Whatsapp is required";

        setErrors(err);
        return Object.keys(err).length > 0;
    };

    const GetInfo = async () => {
        try {
            const { data } = await axios.get(`${apiURL}api/profiles/${user_profile_id}`, {
                headers: apiHeaderJson,
            });

            if (data.success) {
                const d = data.data;

                setFormData({
                    profile_name: d.profile_name,
                    profile_email: d.profile_email,
                    qid: d.qid,
                    profile_contact_number: d.profile_contact_number,
                    profile_whatsapp: d.profile_whatsapp,
                    profile_address: d.profile_address,
                    profile_about: d.profile_about,
                    digitalSign: null,
                    profile_picture: null
                });
            }
        } catch (error) {
            console.error(error);
        } finally {
            setLoading(false)
        }
    };

    const GetLoginInfo = async () => {
        try {
            const response = await axios.get(`${apiURL}api/users/${user_id}`, {
                headers: apiHeaderJson,
            });

            const d = response.data;
            setLoginInfo({
                login_id: d.login_id,
                login_password: d.login_password,
                panel_type: d.panel_type
            });
        } catch (error) {
            console.error(error);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (validateForm()) return;

        try {
            const fd = new FormData();
            fd.append("profile_name", formData.profile_name);
            fd.append("profile_about", formData.profile_about);
            fd.append("profile_address", formData.profile_address);
            fd.append("qid", formData.qid);
            fd.append("profile_contact_number", formData.profile_contact_number);
            fd.append("profile_whatsapp", formData.profile_whatsapp);
            fd.append("profile_email", formData.profile_email);
            fd.append("profile_category_id", "6");
            fd.append("pc_profile_type", "2");
            fd.append("profile_type", "3");
            fd.append("_method", "PUT");
            fd.append("created_by", user_id);
            fd.append("created_date", formatDate());

            if (formData.digitalSign) {
                fd.append("digital_signature", formData.digitalSign);
            }

            if (formData.profile_picture) {
                fd.append("profile_picture", formData.profile_picture);
            }

            const url = `${apiURL}api/profiles/${user_profile_id}`;

            const { data } = await axios.post(url, fd, {
                headers: apiHeaderFile,
            });

            Swal.fire(
                data.success ? "Success" : "Failed",
                data.message,
                data.success ? "success" : "error"
            );

        } catch (error) {
            Swal.fire("Error", "Unexpected error occurred!", "error");
        }
    };

    const handleChangePassword = async (e) => {
        e.preventDefault();

        if (!newPassword.trim()) {
            return Swal.fire("Error", "New password cannot be empty", "error");
        }

        if (newPassword !== confirmPassword) {
            return Swal.fire("Error", "Passwords do not match", "error");
        }

        try {
            const body = {
                user_id,
                user_profile_id,
                login_id: loginInfo.login_id,
                login_password: newPassword,
                panel_type: loginInfo.panel_type,
                created_by: user_id,
                created_date: formatDate(),
            };

            await axios.put(`${apiURL}api/users/${user_id}`, body, {
                headers: apiHeaderJson
            });

            Swal.fire("Success", "Pasword Changed Successfully!", "success");
            GetLoginInfo()

            setShowModal(false);
            setNewPassword("");
            setConfirmPassword("");

        } catch (error) {
            Swal.fire("Error", "Unable to update password", "error");
        }
    };

    useEffect(() => {
        GetInfo();
        GetLoginInfo();
    }, [user_profile_id, user_id]);

    return (
        <>
            {showModal && <div className="modal-backdrop fade show"></div>}

            {showModal && (
                <div className="modal fade show d-block" tabIndex="-1">
                    <div className="modal-dialog modal-dialog-centered">
                        <div className="modal-content">

                            <div className="modal-header">
                                <h5 className="modal-title">Change Password</h5>
                                <button className="btn-close" onClick={() => setShowModal(false)}></button>
                            </div>

                            <div className="modal-body">
                                <form onSubmit={handleChangePassword}>

                                    <div className="mb-3">
                                        <label className="form-label">Old Password</label>
                                        <input
                                            type="text"
                                            className="form-control"
                                            value={loginInfo.login_password}
                                            disabled
                                        />
                                    </div>

                                    <div className="mb-3 position-relative">
                                        <label className="form-label">New Password</label>
                                        <input
                                            type={showNewPass ? "text" : "password"}
                                            className="form-control"
                                            placeholder="Enter new password"
                                            value={newPassword}
                                            onChange={(e) => setNewPassword(e.target.value)}
                                        />
                                        <i
                                            className={`ri-${showNewPass ? "eye-off-line" : "eye-line"} position-absolute`}
                                            style={{ right: "10px", top: "70%", cursor: "pointer", transform: "translateY(-50%)" }}
                                            onClick={() => setShowNewPass(!showNewPass)}
                                        ></i>
                                    </div>

                                    <div className="mb-3 position-relative">
                                        <label className="form-label">Confirm Password</label>
                                        <input
                                            type={showConfirmPass ? "text" : "password"}
                                            className="form-control"
                                            placeholder="Re-enter new password"
                                            value={confirmPassword}
                                            onChange={(e) => setConfirmPassword(e.target.value)}
                                        />
                                        <i
                                            className={`ri-${showConfirmPass ? "eye-off-line" : "eye-line"} position-absolute`}
                                            style={{ right: "10px", top: "70%", cursor: "pointer", transform: "translateY(-50%)" }}
                                            onClick={() => setShowConfirmPass(!showConfirmPass)}
                                        ></i>
                                    </div>

                                    <div className="text-end">
                                        <SubmitBtn text="Update Password" icon="ri-lock-password-line" type="primary" />
                                    </div>

                                </form>
                            </div>

                        </div>
                    </div>
                </div>
            )}

            <div className="main-content">
                <div className="page-content">

                    {!loading ? (
                        <div className="container-fluid">
                            <br />
                            <PageTitle title="My Account" primary="Home" />

                            <div className="row">
                                <div className="col-md-12">
                                    <div className="card shadow">

                                        <div className="card-header d-flex align-items-center justify-content-between" style={{ backgroundColor: "#257180" }}>
                                            <h4 className="card-title text-white mb-0">Account Information</h4>

                                            <button
                                                className='btn btn-light'
                                                onClick={() => setShowModal(true)}
                                            >
                                                Change Password
                                            </button>
                                        </div>

                                        <div className="card-body">

                                            <form onSubmit={handleSubmit}>
                                                <div className="row g-3">

                                                    {/* ROW 1 */}
                                                    <div className="col-lg-6 col-md-6">
                                                        <label className="form-label">Full Name</label>
                                                        <input
                                                            type="text"
                                                            className={`form-control ${errors.profile_name ? "is-invalid" : ""}`}
                                                            name="profile_name"
                                                            placeholder="Enter full name"
                                                            value={formData.profile_name}
                                                            onChange={handleChange}
                                                        />
                                                        {errors.profile_name && <div className="invalid-feedback">{errors.profile_name}</div>}
                                                    </div>

                                                    <div className="col-lg-6 col-md-6">
                                                        <label className="form-label">Email</label>
                                                        <input
                                                            type="email"
                                                            className={`form-control ${errors.profile_email ? "is-invalid" : ""}`}
                                                            name="profile_email"
                                                            placeholder="Enter email address"
                                                            value={formData.profile_email}
                                                            onChange={handleChange}
                                                        />
                                                        {errors.profile_email && <div className="invalid-feedback">{errors.profile_email}</div>}
                                                    </div>

                                                    <div className="col-lg-4 col-md-6">
                                                        <label className="form-label">Contact Number</label>
                                                        <input
                                                            type="text"
                                                            className={`form-control ${errors.profile_contact_number ? "is-invalid" : ""}`}
                                                            name="profile_contact_number"
                                                            placeholder="Enter contact number"
                                                            value={formData.profile_contact_number}
                                                            onChange={handleChange}
                                                        />
                                                        {errors.profile_contact_number && <div className="invalid-feedback">{errors.profile_contact_number}</div>}
                                                    </div>

                                                    {/* ROW 2 */}
                                                    <div className="col-lg-4 col-md-6">
                                                        <label className="form-label">Whatsapp Number</label>
                                                        <input
                                                            type="text"
                                                            className={`form-control ${errors.profile_whatsapp ? "is-invalid" : ""}`}
                                                            name="profile_whatsapp"
                                                            placeholder="Enter whatsapp number"
                                                            value={formData.profile_whatsapp}
                                                            onChange={handleChange}
                                                        />
                                                        {errors.profile_whatsapp && <div className="invalid-feedback">{errors.profile_whatsapp}</div>}
                                                    </div>

                                                    <div className="col-lg-4 col-md-6">
                                                        <label className="form-label">QID</label>
                                                        <input
                                                            type="text"
                                                            className={`form-control ${errors.qid ? "is-invalid" : ""}`}
                                                            name="qid"
                                                            placeholder="Enter QID"
                                                            value={formData.qid}
                                                            onChange={handleChange}
                                                        />
                                                        {errors.qid && <div className="invalid-feedback">{errors.qid}</div>}
                                                    </div>

                                                    <div className="col-lg-6 col-md-6">
                                                        <label className="form-label">Digital Signature</label>
                                                        <input
                                                            type="file"
                                                            className="form-control"
                                                            name="digitalSign"
                                                            onChange={handleDigitalSignUpload}
                                                        />
                                                    </div>

                                                    {/* ROW 3 */}
                                                    <div className="col-lg-6 col-md-6">
                                                        <label className="form-label">Logo</label>
                                                        <input
                                                            type="file"
                                                            className="form-control"
                                                            name="profile_picture"
                                                            onChange={handleLogoUpload}
                                                        />
                                                    </div>

                                                    <div className="col-lg-6 col-md-12">
                                                        <label className="form-label">Address</label>
                                                        <textarea
                                                            className={`form-control ${errors.profile_address ? "is-invalid" : ""}`}
                                                            name="profile_address"
                                                            rows="2"
                                                            placeholder="Enter your complete address..."
                                                            value={formData.profile_address}
                                                            onChange={handleChange}
                                                        ></textarea>
                                                        {errors.profile_address && <div className="invalid-feedback">{errors.profile_address}</div>}
                                                    </div>

                                                    {/* FULL WIDTH */}
                                                    <div className="col-lg-6 col-md-12">
                                                        <label className="form-label">About</label>
                                                        <textarea
                                                            className={`form-control ${errors.profile_about ? "is-invalid" : ""}`}
                                                            name="profile_about"
                                                            rows="2"
                                                            placeholder="Write a short profile description..."
                                                            value={formData.profile_about}
                                                            onChange={handleChange}
                                                        ></textarea>
                                                        {errors.profile_about && <div className="invalid-feedback">{errors.profile_about}</div>}
                                                    </div>

                                                    <div className="col-md-12 text-end mt-3">
                                                        <SubmitBtn text="Update" icon="ri-save-line" type="primary" />
                                                    </div>

                                                </div>
                                            </form>

                                        </div>

                                    </div>
                                </div>
                            </div>

                        </div>
                    ) : <ContentLoader />}
                </div>
            </div>
        </>
    )
}

export default AccountInformation;
