import { Field, Formik } from 'formik';
import Image from 'next/image';
import React, { Fragment, useEffect, useRef, useState } from 'react';
import { Button, Form, Table } from 'react-bootstrap';
import * as Yup from "yup";
import { renderImage } from '../../services/imageHandling';

const MyProfile = () => {
    let formikUploadImage;
    const [readOnly, setReadOnly] = useState(true);

    const profileValidationSchema = Yup.object().shape({
        first_name: Yup.string()
            .required("First Name is Required"),
        last_name: Yup.string()
            .required("Last Name is Required"),
        email: Yup.string()
            .required("Email Id is Required")
            .email("Please Enter An Valid Email Id"),
        country_code: Yup.string()
            .required("Country Code is Required"),
        mobile: Yup.string()
            .required("Mobile Number is Required")
            .matches(/^[0-9\s]+$/, "Please Enter Correct Mobile No."),
        password: Yup.string()
    });

    const addressesValidationSchema = Yup.object().shape({
        addresses: Yup.array().of(
            Yup.object().shape({
                pincode: Yup.string().required('Pincode is required'),
                country: Yup.string().required('Country is required'),
                state: Yup.string().required('State is required'),
                city: Yup.string().required('City is required'),
                addressLine1: Yup.string().required('Address Line1 is required'),
                addressLine2: Yup.string().required('Adrress Line2 is required')
            })
        )
    });

    const profileInitialValue = {
        first_name: "John",
        last_name: "Doe",
        email: "john@gmail.com",
        country_code: "+1 (406)",
        mobile: "785-9909",
        password: "*********"
    }

    // Ref for the first input field
    const firstFieldRef = useRef(null);

    // Effect to focus on the first field when entering edit mode
    useEffect(() => {
        console.log("firstFieldRef", readOnly, firstFieldRef.current)
        if (!readOnly && firstFieldRef.current) {
            firstFieldRef.current.focus();
        }
    }, [readOnly]);

    const handleProfileUploadChange = (event) => {
        console.log(event)
        console.log(event?.currentTarget?.files[0])
        formikUploadImage.setFieldValue("profile_image", event.currentTarget.files[0]);
        formikUploadImage.submitForm()
    }

    return (
        <Fragment>
            <div className="container">
                <div className="row">
                    <div className="col-12 col-lg-12">
                        <div className="form-container content-wraaper">
                            <div className='px-5'>
                                <h2>My Profile</h2>


                                <Table className='abc'>
                                    <thead>
                                        <tr>
                                            <th>1</th>
                                            <th>2</th>
                                            <th>3</th>
                                            <th>4</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr className='main'>
                                            <td rowSpan={3}>1</td>
                                        </tr>
                                        <tr className='sub1'>
                                            <td>11</td>
                                            <td>22</td>
                                            <td>33</td>
                                        </tr>
                                        <tr className='sub2'>
                                            <td>11</td>
                                            <td>22</td>
                                            <td>33</td>
                                        </tr>

                                        <tr className='main'>
                                            <td rowSpan={3}>1</td>
                                        </tr>
                                        <tr className='sub'>
                                            <td>11</td>
                                            <td>22</td>
                                            <td>33</td>
                                        </tr>
                                        <tr className='sub'>
                                            <td>11</td>
                                            <td>22</td>
                                            <td>33</td>
                                        </tr>
                                    </tbody>
                                </Table>
                                <div className="bg-white border-div">
                                    <Formik
                                        initialValues={{ profile_image: null }}
                                        validationSchema={Yup.object().shape({
                                            profile_image: Yup.mixed().required("Profile Image is Required")
                                        })}
                                        enableReinitialize={true}
                                        onSubmit={values => {
                                            console.log("profile image", values)

                                            // onSubmit: async (values, { setSubmitting }) => {
                                            //     setSubmitting(true);
                                            //     try {
                                            //       const formData = new FormData();
                                            //       formData.append("file", values.file);

                                            //       // Use Axios to send the file data to the server
                                            //       const response = await axios.post("/upload", formData, {
                                            //         headers: {
                                            //           "Content-Type": "multipart/form-data"
                                            //         }
                                            //       });

                                            //       console.log("File uploaded successfully:", response.data);
                                            //     } catch (error) {
                                            //       console.error("Error uploading file:", error);
                                            //     }
                                            //     setSubmitting(false);
                                            //   }
                                        }}
                                        innerRef={formik => {
                                            // Store Formik instance in a variable
                                            formikUploadImage = formik;
                                        }}
                                    >
                                        {({ values, errors, touched, handleChange, handleBlur, handleSubmit }) => (
                                            <Form
                                                onSubmit={e => {
                                                    e.preventDefault();
                                                    handleSubmit();
                                                    console.log(errors)
                                                }}
                                            >
                                                <div className="d-flex align-items-center justify-content-between">
                                                    <div className="col-lg-6 d-flex align-items-center">
                                                        <span className="image-container me-4">
                                                        <Image layout="fill" alt="" src="/images/user/user-big.jpg" className="image" />
                                                        </span>
                                                        <p className="username">John Doe</p>
                                                    </div>
                                                    <div className="col-lg-4">
                                                        <label className="uploadProfileImage" htmlFor="file-upload">
                                                            <p className="mb-0">Upload Profile Photo</p>
                                                            <Image alt="" src="/images/user/icon-upload.svg" width="24" height="24" className="pb-1" />
                                                        </label>
                                                        <input
                                                            type="file"
                                                            id="file-upload"
                                                            name="profile_image"
                                                            onChange={handleProfileUploadChange}
                                                            // onBlur={handleBlur}
                                                            style={{ display: "none" }}
                                                            onClick={event => {
                                                                const { target = {} } = event || {};
                                                                target.value = "";
                                                            }}
                                                        />
                                                        {errors.profile_image && touched.profile_image && (<span className="form-error">{errors.profile_image}</span>)}
                                                    </div>
                                                </div>
                                            </Form>
                                        )}
                                    </Formik>
                                </div>
                                <div className="bg-white border-div">
                                    <Formik
                                        initialValues={profileInitialValue}
                                        validationSchema={profileValidationSchema}
                                        enableReinitialize={true}
                                        onSubmit={values => {
                                            console.log("profile personal details", values)
                                        }}
                                    >
                                        {({ values, errors, touched, handleChange, handleBlur, handleSubmit }) => (
                                            <Form
                                                onSubmit={e => {
                                                    e.preventDefault();
                                                    handleSubmit();
                                                }}
                                            >
                                                <>
                                                    <div className="d-flex justify-content-between mb-4">
                                                        <h2 className="mb-0">Personal Information</h2>
                                                        {/* onClick={() => setReadOnly(prevState => !prevState)} */}
                                                        {readOnly && (
                                                            <div className="btn-edit">
                                                                <span className="me-3">Edit</span>
                                                                <i className="fa fa-edit"></i>
                                                            </div>
                                                        )}
                                                    </div>
                                                    <div className="row">
                                                        <div className="col-12 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Your First Name</label>
                                                                <Field
                                                                    type="text"
                                                                    name="first_name"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                    value={values.first_name}
                                                                    readOnly={readOnly}
                                                                    innerRef={firstFieldRef}
                                                                />
                                                                {errors.first_name && touched.first_name && (<span className="form-error">{errors.first_name}</span>)}
                                                            </div>
                                                        </div>
                                                        <div className="col-12 offset-lg-1 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Your Last Name</label>
                                                                <Field
                                                                    type="text"
                                                                    name="last_name"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                    value={values.last_name}
                                                                    readOnly={readOnly}
                                                                />
                                                                {errors.last_name && touched.last_name && (<span className="form-error">{errors.last_name}</span>)}
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div className="row">
                                                        <div className="col-12 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Email Id</label>
                                                                <Field
                                                                    type="text"
                                                                    name="email"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                    value={values.email}
                                                                    readOnly={readOnly}
                                                                />
                                                                {errors.email && touched.email && (<span className="form-error">{errors.email}</span>)}
                                                            </div>
                                                        </div>
                                                        <div className="col-12 offset-lg-1 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Mobile Number</label>
                                                                <div className="contact-number">
                                                                    {readOnly && (
                                                                        <Field
                                                                            type="text"
                                                                            name="country_code"
                                                                            onChange={handleChange}
                                                                            onBlur={handleBlur}
                                                                            value={values.country_code}
                                                                            readOnly={readOnly}
                                                                            style={{ width: "80px" }}
                                                                        />
                                                                    )}
                                                                    {!readOnly && (
                                                                        <select
                                                                            id="country_code"
                                                                            name="country_code"
                                                                            onChange={handleChange}
                                                                            onBlur={handleBlur}
                                                                            style={{ width: "80px" }}
                                                                        >
                                                                            <option value="+91">+91</option>
                                                                            <option value="+44">+44</option>
                                                                        </select>
                                                                    )}
                                                                    <Field
                                                                        type="text"
                                                                        name="mobile"
                                                                        onChange={handleChange}
                                                                        onBlur={handleBlur}
                                                                        value={values.mobile}
                                                                        readOnly={readOnly}
                                                                    />
                                                                </div>
                                                                {errors.mobile && touched.mobile && (<span className="form-error">{errors.mobile}</span>)}
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div className="row">
                                                        <div className="col-12 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Current Password</label>
                                                                <input
                                                                    type="text"
                                                                    name="password"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                    value={values.password}
                                                                    readOnly={readOnly}
                                                                    disabled={true}
                                                                />
                                                            </div>
                                                        </div>
                                                    </div>
                                                </>
                                            </Form>
                                        )}
                                    </Formik>
                                </div>


                                <div className="bg-white border-div">
                                    <Formik
                                        initialValues={{
                                            addresses: [
                                                {
                                                    pincode: "",

                                                }
                                            ]
                                        }}
                                        validationSchema={addressesValidationSchema}
                                        // enableReinitialize={true}
                                        onSubmit={values => {
                                            console.log("profile address details", values)
                                        }}
                                    >
                                        {({ values, errors, touched, handleChange, handleBlur, handleSubmit }) => (
                                            <Form
                                                onSubmit={e => {
                                                    e.preventDefault();
                                                    handleSubmit();
                                                }}
                                            >
                                                <>
                                                    <div className="d-flex justify-content-between mb-4">
                                                        <h2 className='mb-0'>Address</h2>
                                                        <div className="btn-edit">
                                                            <span className="me-3">Add</span>
                                                            <i className="fa fa-plus"></i>
                                                        </div>
                                                    </div>
                                                    <div className="row">
                                                        <div className="col-12 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Pincode</label>
                                                                <input
                                                                    type="text"
                                                                    name="pincode"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                    value={values.pincode}
                                                                />
                                                                {errors.pincode && touched.pincode && (<span className="form-error">{errors.pincode}</span>)}
                                                            </div>
                                                        </div>
                                                        <div className="col-12 offset-lg-1 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Country</label>
                                                                <select
                                                                    id="country"
                                                                    name="country"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                >
                                                                    <option value="India">India</option>
                                                                    <option value="America">America</option>
                                                                </select>
                                                                {errors.country && touched.country && (<span className="form-error">{errors.country}</span>)}
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div className="row">
                                                        <div className="col-12 col-lg-5">
                                                            <div className="input-group">
                                                                <label>State</label>
                                                                <select
                                                                    id="state"
                                                                    name="state"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                >
                                                                    <option value="India">India</option>
                                                                    <option value="America">America</option>
                                                                </select>
                                                                {errors.state && touched.state && (<span className="form-error">{errors.state}</span>)}
                                                            </div>
                                                        </div>
                                                        <div className="col-12 offset-lg-1 col-lg-5">
                                                            <div className="input-group">
                                                                <label>City</label>
                                                                <select
                                                                    id="city"
                                                                    name="city"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                >
                                                                    <option value="India">India</option>
                                                                    <option value="America">America</option>
                                                                </select>
                                                                {errors.city && touched.city && (<span className="form-error">{errors.city}</span>)}
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div className="row">
                                                        <div className="col-12 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Address Line 1</label>
                                                                <input
                                                                    type="text"
                                                                    name="addressLine1"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                    value={values.addressLine1}
                                                                />
                                                                {errors.addressLine1 && touched.addressLine1 && (<span className="form-error">{errors.addressLine1}</span>)}
                                                            </div>
                                                        </div>
                                                        <div className="col-12 offset-lg-1 col-lg-5">
                                                            <div className="input-group">
                                                                <label>Address Line 2</label>
                                                                <input
                                                                    type="text"
                                                                    name="addressLine2"
                                                                    onChange={handleChange}
                                                                    onBlur={handleBlur}
                                                                    value={values.addressLine2}
                                                                />
                                                                {errors.addressLine2 && touched.addressLine2 && (<span className="form-error">{errors.addressLine2}</span>)}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </>
                                            </Form>
                                        )}
                                    </Formik>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </Fragment>
    )
}

export default MyProfile;