"use client";

import SearchD from "@/components/icons/SearchD";
import { Search } from "@mui/icons-material";
import { Button, CircularProgress } from "@mui/material";
import { useRouter } from "next/navigation";
import specialties from "@/data/specialties.json";
import { useState } from "react";

function RedirectLink({ data }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  const handleRedirect = (e) => {
    loading && e.preventDefault()
    const filters = {};
    if (data.city && data.city !== "نوبت 724") filters.city = data.city;
    if (data.province) filters.state = data.province;
    if (data.search) {
      const specialtyItem = specialties.find((item) =>
        item.name.includes(data.search)
      );
      if (specialtyItem) {
        filters.specialty = specialtyItem.name;
      } else {
        filters.name = data.search;
      }
    }

    const queryParams = new URLSearchParams(filters).toString();
    setLoading(true);
    router.push(`/doctors?${queryParams}`);
  };

  return (
    <>
      {/* <div className="min-w-[20px] min-h-[20px]">
        <Search />
        </div> */}
      <Button
        onClick={handleRedirect}
        className="!hidden lg:!flex !rounded-[4px] !h-[40px] sm:!h-[42px] md:!h-[45px] lg:!h-[48px] !gap-2.5 !min-w-[114px]"
      >
        <div className="min-w-[20px] min-h-[20px] grid place-items-center">
          {loading ? (
            <CircularProgress
              className="!w-[24px] !h-[24px]"
              sx={{ color: "#FFFFFF" }}
            />
          ) : (
            <Search />
          )}
        </div>
        <p>جستجو</p>
      </Button>
      <Button
        onClick={handleRedirect}
        className="!flex lg:!hidden !rounded-[4px] !w-[40px] sm:!w-[42px] md:!w-[45px] lg:!w-[48px] !h-[40px] sm:!h-[42px] md:!h-[45px] lg:!h-[48px] !min-w-[40px] sm:!min-w-[42px] md:!min-w-[45px] lg:!min-w-[48px] !min-h-[40px] sm:!min-h-[42px] md:!min-h-[45px] lg:!min-h-[48px] !gap-2.5 !p-2.5"
      >
        <div className="w-[24px] h-[24px] min-w-[24px] min-h-[24px]">
          <SearchD />
        </div>
      </Button>
    </>
  );
}

export default RedirectLink;
