"use client";

import { useEffect, useState } from "react";
import Head from "./Head";
import List from "./List";
import { request } from "@/services/response";
import Cookies from "js-cookie";
import IsTurnsDetails from "./isTurnsDetails";

function Turns({ user, setIsTurnsDetails, loading }) {
  const [status, setStatus] = useState("confirmed");
  const [appointments, setAppointments] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedAppointment, setSelectedAppointment] = useState(null);

  useEffect(() => {
    const fetchAppointments = async () => {
      setIsLoading(true);
      try {
        const userInfo = Cookies.get("userInfo");
        if (!userInfo) {
          setIsLoading(false);
          return;
        }

        const params = {
          page,
          limit: 10,
        };

        if (status) {
          params.status = status;
        }

        const response = await request.getMyAppointments(params);
        const items = response?.data?.data;

        if (Array.isArray(items)) {
          setAppointments(items);
        } else {
          setAppointments([]);
        }
        setTotalPages(response?.meta?.totalPages || 1);
      } catch (error) {
        console.error("Error fetching appointments:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchAppointments();
  }, [page, status]);

  const handlePageChange = (event, value) => {
    setPage(value);
  };

  const handleStatusChange = (newStatus) => {
    setStatus(newStatus);
    setPage(1); // Reset to first page when status changes
  };

  return (
    <div className="opacity-page">
      {selectedAppointment ? (
        <IsTurnsDetails
          appointmentData={selectedAppointment}
          setIsTurnsDetails={setSelectedAppointment}
        />
      ) : (
        <>
          <p className="text-[#3B3B3B] hidden md:flex text-[16px] font-bold">
            تاریخچه نوبت ها
          </p>
          <Head status={status} setStatus={handleStatusChange} />
          <List
            loading={isLoading}
            setIsTurnsDetails={setSelectedAppointment}
            user={appointments}
            page={page}
            totalPages={totalPages}
            onPageChange={handlePageChange}
          />
        </>
      )}
    </div>
  );
}

export default Turns;
