"use client";

import { useState, useMemo } from "react";
import Image from "next/image";
import Link from "next/link";
import useSWR from "swr";

import { Button } from "@/components/ui/button";
import { Search, SlidersHorizontal } from "lucide-react";
import MaterialSymbolsArrowRightAltIcon from "@/components/icons/material-symbols/arrow-right-alt";
import DoctorsService from "@/services/doctors.service";
import type { Doctor, Poli } from "@/types/doctor.type";

const FILTER_OPTIONS = [
  { label: "Semua", value: "ALL" },
  { label: "Poli Umum", value: "poli-umum" },
  { label: "Poli KIA", value: "poli-kia" },
  { label: "Poli Gigi", value: "poli-gigi" },
  { label: "Poli KB", value: "poli-kb" },
  { label: "Sunat Racing", value: "sunat-racing" },
  { label: "Home Care", value: "home-care" },
];

const fetcher = (key: string) => {
  const [endpoint, param] = key.split("?");
  const params = new URLSearchParams(param);
  const poli = params.get("poli");
  return poli && poli !== "ALL"
    ? DoctorsService.getAll(poli)
    : DoctorsService.getAll();
};

const DokterListSection = () => {
  const [filter, setFilter] = useState("ALL");
  const [searchQuery, setSearchQuery] = useState("");

  const queryKey = filter === "ALL"
    ? "/doctors"
    : `/doctors?poli=${filter}`;

  const { data: doctors = [], isLoading } = useSWR<Doctor[]>(
    queryKey,
    fetcher
  );

  const filteredDoctors = useMemo(() => {
    if (!searchQuery) return doctors;
    return doctors.filter((doctor) =>
      doctor.name.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [doctors, searchQuery]);

  return (
    <section className="bg-[#E6F1FF] py-8">
      <div className="max-w-[1311px] mx-auto">
        <div className="flex flex-col gap-[31px]">
          {/* Section Header */}
          <div className="flex flex-col items-center">
            <div className="p-[10px]">
              <h2 className="font-semibold text-[#3F7BFF] text-[60px] leading-[1.2] text-center whitespace-nowrap">
                Dokter Terpercaya dan berprestasi
              </h2>
            </div>
            <div className="p-[10px]">
              <p className="font-normal text-[rgba(56,54,54,0.8)] text-[24px] leading-[1.2] text-center whitespace-nowrap">
                Lorem Ipsum is simply dummy text of the printing and typesetting industry.
              </p>
            </div>
          </div>

          {/* Search & Filter */}
          <div className="flex gap-[18px] items-center justify-center">
            <div className="bg-white rounded-[29px] shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] flex items-center gap-[8px] px-[61px] py-[21px] w-[624px] h-[64px]">
              <Search className="size-[18px] text-[#38363680]" />
              <input
                type="text"
                placeholder="Cari Dokter"
                className="font-normal text-[20px] text-[rgba(56,54,54,0.8)] w-full outline-none bg-transparent"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>
            <div className="bg-[#003DD8] rounded-[29px] shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] flex items-center gap-[8px] px-[16px] py-[16px] h-[64px]">
              <SlidersHorizontal className="size-[29px] text-white" />
              <span className="font-normal text-white text-[24px] leading-[1.2]">
                Filter
              </span>
            </div>
          </div>

          {/* Doctor Grid */}
          {isLoading ? (
            <div className="flex justify-center py-12">
              <div className="animate-pulse text-gray-500">Memuat dokter...</div>
            </div>
          ) : filteredDoctors.length === 0 ? (
            <div className="flex justify-center py-12">
              <div className="text-gray-500">Belum ada dokter</div>
            </div>
          ) : (
            <div className="flex flex-wrap gap-[20px_32px] content-start w-[1252px]">
              {filteredDoctors.map((doctor) => (
                <div
                  key={doctor.id}
                  className="bg-white rounded-[8px] p-[12px] flex flex-col gap-[12px] w-[396px]"
                >
                  <div className="relative w-full h-[215px] rounded-tl-[8px] rounded-tr-[8px] bg-white overflow-hidden">
                    <Image
                      src={doctor.imageUrl || "/assets/dokter/dokter.jpg"}
                      alt={doctor.name}
                      fill
                      className="object-cover object-top"
                    />
                  </div>

                  <div className="flex flex-wrap gap-[16px_11px] items-end w-[355px]">
                    <div className="flex flex-col gap-[12px] w-[355px]">
                      <div className="flex flex-col gap-[6px] w-full">
                        <div className="flex gap-[4px] items-center">
                          {doctor.isOnline && (
                            <div className="bg-[#26FB9B] rounded-[6px] h-[15px] flex items-center justify-center py-[10px] px-[10px]">
                              <span className="font-medium text-[#1E6B48] text-[11px] leading-[1.2]">
                                Online
                              </span>
                            </div>
                          )}
                          {doctor.isDirect && (
                            <div className="bg-[#54ADFF] rounded-[6px] h-[15px] flex items-center justify-center py-[10px] px-[10px]">
                              <span className="font-medium text-[#0F5391] text-[11px] leading-[1.2]">
                                Temu langsung
                              </span>
                            </div>
                          )}
                        </div>
                        <div className="flex items-center w-full">
                          <span className="font-medium text-[#202020] text-[20px] leading-[1.2] whitespace-nowrap">
                            {doctor.name}
                          </span>
                        </div>
                        <div className="flex items-center">
                          <span className="font-medium text-[#202020] text-[14px] leading-[1.2] whitespace-nowrap">
                            {doctor.polis.map((p) => p.name).join(", ")}
                          </span>
                        </div>
                      </div>

                      <p className="h-[75px] overflow-hidden font-normal text-[#6D6D6D] text-[14px] leading-[1.2] text-ellipsis w-full">
                        {doctor.description ||
                          "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,"}
                      </p>
                    </div>

                    <div className="flex items-center justify-between w-[355px]">
                      <Button
                        size="lg"
                        className="bg-[#003DD8] rounded-[44px] h-[41px] w-[172px] flex items-center justify-center gap-[10px] px-[108px] py-[21px] font-bold text-white text-[14px] leading-[1.2]"
                      >
                        Book appointment
                        <MaterialSymbolsArrowRightAltIcon className="size-[17px]" />
                      </Button>
                      <Link href={`/dokter/${doctor.id}`}>
                        <Button
                          size="lg"
                          variant="outline"
                          className="border-2 border-[#003DD8] rounded-[44px] h-[41px] w-[172px] flex items-center justify-center px-[108px] py-[21px] font-bold text-[#003DD8] text-[14px] leading-[1.2] bg-transparent"
                        >
                          Lihat Profil
                        </Button>
                      </Link>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

export default DokterListSection;