"use client";

import { useTranslations, useLocale } from "next-intl";
import { useState, useMemo } from "react";
import { motion } from "framer-motion";
import DynamicButton from "@/components/button";
import DynamicInput from "@/components/input";
import ServiceListingCard from "@/components/service-listing-card/ServiceListingCard";
import ServiceDetailModal, {
  type ServiceDetailInfoRow,
} from "@/components/service-listing-card/ServiceDetailModal";
import {
  displayServiceField,
  normalizePackagesFromApi,
  type ServiceDetailPackage,
} from "@/components/service-listing-card/detailHelpers";
import type {
  MedicalServicesResponseData,
  MedicalService,
} from "@/models/medical-service";
import {
  normalizeSpecialty,
  normalizeState,
  resolveMedicalMediaUrls,
} from "@/models/medical-service";
import {
  cardThumbnailsFromGallery,
  withServiceImageFallback,
} from "@/lib/serviceMedia";
import { parseServiceLatLng } from "@/lib/serviceGeo";
import type { ServiceMapCoords } from "@/lib/serviceGeo";
import { formatRatingWithMax } from "@/lib/serviceRating";
import type { ReviewableType } from "@/lib/publicReviewsApi";

type DetailState = {
  images: string[];
  imageAlt: string;
  infoRows: ServiceDetailInfoRow[];
  description: string;
  mapCoords: ServiceMapCoords | null;
  phone: string;
  whatsapp: string;
  serviceRatingRaw: string | null | undefined;
  reviewableId: string;
  reviewableType: ReviewableType;
  packages: ServiceDetailPackage[] | null;
} | null;

export default function ClientMedicalServices({
  data,
}: {
  data: MedicalServicesResponseData;
}) {
  const t = useTranslations("MEDICAL_SERVICES");
  const tCard = useTranslations("SERVICE_LISTING_CARD");
  const tDetail = useTranslations("SERVICE_DETAIL_MODAL");
  const locale = useLocale();
  const currencySuffix = locale.startsWith("ar") ? " ر.س" : " SAR";

  const [visibleCount, setVisibleCount] = useState(12);
  const [activeSpecialty, setActiveSpecialty] = useState("all");
  const [activeState, setActiveState] = useState("all");
  const [detail, setDetail] = useState<DetailState>(null);

  const states = useMemo(
    () => [{ id: "all", name: t("all") }, ...(data.states ?? [])],
    [data.states, t],
  );

  const specialties = useMemo(
    () => [{ id: "all", name: t("all") }, ...(data.specialties ?? [])],
    [data.specialties, t],
  );

  const filteredDoctors = (data.medical_services ?? []).filter(
    (doc: MedicalService) => {
      const sp = normalizeSpecialty(doc.specialty);
      const st = normalizeState(doc.state);
      const matchSpecialty =
        activeSpecialty === "all" || (sp != null && sp.id === activeSpecialty);
      const matchState =
        activeState === "all" || (st != null && st.id === activeState);
      return matchSpecialty && matchState;
    },
  );

  return (
    <main className="bg-[#FBF9F6] min-h-screen">
      <section className="py-4 sm:py-6">
        <div className="max-w-7xl mx-auto px-4 sm:px-6">
          <div className="filter-container p-3 sm:p-4 space-y-3 sm:space-y-0 sm:flex sm:items-center sm:justify-between">
            <div className="mobile-filter-scroll sm:flex sm:flex-wrap sm:gap-2 sm:items-center sm:flex-1">
              {specialties.map((spec) => (
                <button
                  key={spec.id}
                  type="button"
                  className={`filter-chip whitespace-nowrap flex-shrink-0 ${
                    activeSpecialty === spec.id ? "active" : ""
                  }`}
                  onClick={() => setActiveSpecialty(spec.id)}
                >
                  {spec.name}
                </button>
              ))}
            </div>

            <div className="flex items-end gap-2 mt-3 sm:mt-0 sm:justify-end sm:w-auto">
              <DynamicInput
                field={{
                  name: "stateFilter",
                  value: activeState,
                  onChange: (
                    e: React.ChangeEvent<HTMLSelectElement> | string,
                  ) => {
                    if (typeof e === "string") {
                      setActiveState(e);
                    } else {
                      const selected = (e.target as HTMLSelectElement).value;
                      setActiveState(selected);
                    }
                  },
                }}
                label={t("stateLabel")}
                type="select"
                options={states.map((state) => ({
                  value: state.id,
                  label: state.name,
                }))}
                variant="bordered"
                size="sm"
                className="w-full sm:w-40"
              />
            </div>
          </div>
        </div>
      </section>

      <section className="max-w-7xl mx-auto px-4 sm:px-6 pb-12 sm:pb-16">
        {filteredDoctors.length === 0 ? (
          <p className="text-center text-slate-600 py-16 text-sm sm:text-base">
            {t("empty")}
          </p>
        ) : (
          <>
            <motion.div
              className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 sm:gap-6 lg:gap-8"
              initial="hidden"
              animate="show"
              variants={{
                hidden: {},
                show: { transition: { staggerChildren: 0.15 } },
              }}
            >
              {filteredDoctors.slice(0, visibleCount).map((doc, i) => {
                const sp = normalizeSpecialty(doc.specialty);
                const st = normalizeState(doc.state);
                const gallery = resolveMedicalMediaUrls(doc.media_files);
                const cardImages = withServiceImageFallback(
                  cardThumbnailsFromGallery(gallery),
                );
                const modalImages = withServiceImageFallback(gallery);
                const secondaryParts = [sp?.name, st?.name]
                  .filter((s) => s != null && String(s).trim() !== "")
                  .join(" — ");
                const docRec = doc as unknown as Record<string, unknown>;
                const packagesModal = normalizePackagesFromApi(
                  docRec.packages,
                  locale,
                  currencySuffix,
                );
                const ratingLine = formatRatingWithMax(doc.rating);
                const specialtyText =
                  sp?.name ?? displayServiceField(doc.specialty);
                const stateText = st?.name ?? displayServiceField(doc.state);
                const infoRows: ServiceDetailInfoRow[] = [
                  {
                    label: tCard("label_doctor"),
                    value: displayServiceField(doc.doctor_name),
                  },
                  {
                    label: tCard("label_specialty"),
                    value: specialtyText,
                  },
                  { label: tDetail("label_state"), value: stateText },
                  {
                    label: tDetail("label_animal_type"),
                    value: displayServiceField(doc.animal_type),
                  },
                  {
                    label: tDetail("label_phone"),
                    value: displayServiceField(doc.phone_number),
                  },
                  {
                    label: tDetail("label_whatsapp"),
                    value: displayServiceField(doc.whatsapp_number),
                  },
                ];
                return (
                  <motion.div
                    key={doc.id != null ? String(doc.id) : i}
                    variants={{
                      hidden: { opacity: 0, y: 20 },
                      show: { opacity: 1, y: 0, transition: { duration: 0.5 } },
                    }}
                  >
                    <ServiceListingCard
                      images={cardImages}
                      imageAlt={doc.doctor_name}
                      primaryLabel={tCard("label_doctor")}
                      primaryValue={doc.doctor_name}
                      secondaryLabel={tCard("label_specialty")}
                      secondaryValue={secondaryParts || "—"}
                      phone={doc.phone_number}
                      whatsapp={doc.whatsapp_number}
                      ratingRaw={doc.rating}
                      ratingLine={ratingLine}
                      onDetailsClick={() =>
                        setDetail({
                          images: modalImages,
                          imageAlt: doc.doctor_name,
                          infoRows,
                          description: String(doc.description ?? "").trim(),
                          mapCoords: parseServiceLatLng(doc.lat, doc.lng),
                          phone: doc.phone_number,
                          whatsapp: doc.whatsapp_number,
                          serviceRatingRaw: doc.rating,
                          reviewableId: String(doc.id),
                          reviewableType: "medical_service",
                          packages: packagesModal,
                        })
                      }
                    />
                  </motion.div>
                );
              })}
            </motion.div>

            {visibleCount < filteredDoctors.length && (
              <div className="mt-8 text-center">
                <DynamicButton
                  className="px-6 py-3 rounded-xl text-white bg-[#1B7A50] hover:bg-[#14623c] transition-colors"
                  onClick={() => setVisibleCount((prev) => prev + 8)}
                >
                  {t("loadMore")}
                </DynamicButton>
              </div>
            )}
          </>
        )}
      </section>

      <ServiceDetailModal
        isOpen={detail != null}
        onOpenChange={(open) => {
          if (!open) setDetail(null);
        }}
        images={detail?.images ?? []}
        imageAlt={detail?.imageAlt ?? ""}
        infoRows={detail?.infoRows ?? []}
        descriptionLabel={tDetail("label_description")}
        description={detail?.description}
        mapCoords={detail?.mapCoords ?? null}
        serviceRatingRaw={detail?.serviceRatingRaw}
        reviewableId={detail?.reviewableId}
        reviewableType={detail?.reviewableType}
        packages={detail?.packages ?? null}
        phone={detail?.phone}
        whatsapp={detail?.whatsapp}
      />
    </main>
  );
}
