import React, { useState } from "react";
import Layout from "../Partials/Layout";
import usersService from "../../services/UsersService";
import YourPageForm from "./YourPageForm";

const YourPage = () => {
  const [pageValues, setPageValues] = useState({
    intro: "",
    description: "",
  });

  const [response, setResponse] = useState({
    loading: false,
    data: {},
    error: "",
    msg: "",
  });

  const handleChange = (event) => {
    let { name, value } = event.target;
    setPageValues((prev) => ({ ...prev, [name]: value }));
  };

  const updateYourPageDetails = async () => {
    try {
      setResponse({ loading: true, error: "", msg: "" });

      let api = new usersService();
      const res = await api.MyPageIntro(pageValues);

      setTimeout(() => {
        setResponse({
          loading: false,
          data: res.data,
          msg: "Page updated successfully",
        });

        // Clear form after successful update
        setPageValues({ intro: "", description: "" });
      }, 2000);
    } catch (error) {
      setResponse({
        loading: false,
        data: {},
        error: "Error updating page",
        msg: "",
      });
    }
  };

  return (
    <Layout>
      <div className="notification-page w-full mb-10">
        <div className="notification-wrapper w-full">
          <div className="update-table w-full h-full p-4 bg-white dark:bg-dark-white overflow-y-auto rounded-2xl section-shadow min-h-[520px]">
            <h1 className="text-26 font-bold text-dark-gray dark:text-white tracking-wide mb-2">
              My page
            </h1>
            <hr />
            <YourPageForm
              values={pageValues}
              onChange={handleChange}
              onSubmit={updateYourPageDetails}
              loading={response.loading}
            />
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default YourPage;
