"use client";

import { useEffect, useState } from "react";
import doctors from "@/data/doctors.json";
import { request } from "@/services/response";
import Cookies from "js-cookie";
import Container from "./Container";

const defaultData = {
  phone: { value: "", isEdit: false },
  national_code: { value: "", isEdit: false },
  name: { value: "", isEdit: false },
  basic_insurance: { value: "", isEdit: false },
};

function AppointmentPage({ slug, matchedCity }) {
  const doctor = doctors.find((item) => item.id === +slug);

  const [step, setStep] = useState(0);
  const [isForAnother, setIsForAnother] = useState(false);

  const [prevData, setPrevData] = useState(defaultData);
  const [data, setData] = useState(defaultData);

  useEffect(() => {
    const userInfo = Cookies.get("userInfo");
    const parsedData = userInfo && JSON.parse(userInfo);

    if (userInfo && parsedData) {
      request
        .getUserProfile(parsedData.uuid)
        .then((res) => {
          if (res) {
            const newData = {
              uuid: res.uuid,
              phone: { value: parsedData.username || "", isEdit: false },
              national_code: {
                value: res.national_code || "",
                isEdit: res.national_code ? false : true,
              },
              name: { value: `${res.name} ${res.family}`, isEdit: true },
              basic_insurance: {
                value: res.basic_insurance,
                isEdit: true,
              },
            };
            setData(newData);
            setPrevData(newData);
          } else {
            const emptyData = {
              uuid: res.uuid,
              phone: { value: parsedData.username || "", isEdit: false },
              national_code: { value: "", isEdit: true },
              name: { value: "", isEdit: true },
              basic_insurance: {
                value: res.basic_insurance,
                isEdit: true,
              },
            };
            setData(emptyData);
            setPrevData(emptyData);
          }
        })
        .catch(() => {
          //
        });
    }
  }, []);

  return (
    <Container
      step={step}
      data={data}
      doctor={doctor}
      setData={setData}
      setStep={setStep}
      prevData={prevData}
      matchedCity={matchedCity}
      isForAnother={isForAnother}
      setIsForAnother={setIsForAnother}
    />
  );
}

export default AppointmentPage;
