"use client";
import DenyAccess from "@/components/DenyAccess";
import CreateDoctorForm from "@/components/forms/doctor/create/CreateDoctorForm";
import Loader from "@/components/Loader";
import SectionTitle from "@/components/SectionTitle";
import {API_URL} from "@/constants";
import {Expertise, Language} from "@/types";
import Link from "next/link";
import {useRouter} from "next/navigation";
import {Suspense, useEffect, useState} from "react";

async function fetchLanguages() {
  const res = await fetch(`${API_URL}/language/get/all`,{cache:"no-cache"});


  
  if (!res.ok && res.status==500) {
    throw new Error("Failed to get data");
  }

  if(!res.ok && res.status==404){
    return []
  }

  const data = await res.json();

  return data;
}
async function fetchExpertise() {
  const res = await fetch(`${API_URL}/expertise/fa/get/all/list`,{cache:"no-cache"});

  if (!res.ok && res.status==500) {
    throw new Error("Failed to get data");
  }

  if(!res.ok && res.status==404){
    return []
  }

  const data = await res.json();

  return data;
}

export default function Page() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Language[]>([]);

  const [expertises, setExpertises] = useState<Expertise[]>([]);
  useEffect(() => {
    let active = true;

    setLoading(true);
    fetchExpertise()
      .then((res) => {
        if (!active) return;
        setExpertises(res.data);
      })
      .catch(console.error)
      .finally(() => active && setLoading(false));

    return () => {
      active = false;
    };
  }, []);
  useEffect(() => {
    let active = true;

    setLoading(true);
    fetchLanguages()
      .then((res) => {
        if (!active) return;
        setData(res.data);
      })
      .catch(console.error)
      .finally(() => active && setLoading(false));

    return () => {
      active = false;
    };
  }, []);

  if (loading) {
    return <Loader />;
  }
  return (
    <div>
      <div className="flex items-center justify-between mb-10">
        <SectionTitle label="فرم افزودن پزشک جدید"  />
        <Link href={`/doctors`} className="text-sm bg-primary px-4 py-2 rounded-lg text-white">مشاهده لیست پزشکان</Link>
      </div>
      <Suspense fallback={<Loader />}>
      {data?.length > 0 ? expertises?.length > 0 ?  <CreateDoctorForm
          expertises={expertises}
          router={router}
          languages={data}
        /> : <DenyAccess label="تخصص" link="/expertise/new"/> : <DenyAccess label="زبان" link="/languages"/> }
        
      </Suspense>
    </div>
  );
}
