"use client";

import { useEffect, useState } from "react";
import { motion, AnimatePresence, useReducedMotion } from "motion/react";
import { CitySelect, Chip } from "@/components/life/Controls";
import { LifeNotice, LifeSkeleton } from "@/components/life/LifeStatus";
import PlaceCard from "@/components/life/PlaceCard";
import { useMedicalCentersStore, useSpecialtiesStore } from "@/store/services";

/** Medical centers with a city picker and specialty chips. Both filters run on the client over the full list (see listMedicalCenters). */
export default function MedicalCenters() {
  const reduce = useReducedMotion();
  const store = useMedicalCentersStore();
  const specialties = useSpecialtiesStore();
  const [cityId, setCityId] = useState<number | undefined>();
  const [specialty, setSpecialty] = useState<number | undefined>();

  useEffect(() => {
    if (store.status === "idle") void store.load();
  }, [store.status, store.load]);
  useEffect(() => {
    if (specialties.status === "idle") void specialties.load();
  }, [specialties.status, specialties.load]);

  const shown = store.items.filter((c) => (!cityId || c.city_id === cityId) && (!specialty || c.subtype.specialties.some((s) => s.id === specialty)));
  const loading = store.status === "idle" || store.status === "loading";
  const filtered = Boolean(cityId || specialty);
  const clear = () => {
    setCityId(undefined);
    setSpecialty(undefined);
  };

  return (
    <div className="lf">
      <div className="lf-toolbar">
        <div className="lf-tools">
          <CitySelect value={cityId} onChange={setCityId} />
        </div>
        {specialties.items.length > 0 && (
          <div className="lf-group" role="group" aria-label="Specialty">
            <Chip pressed={!specialty} onClick={() => setSpecialty(undefined)}>
              All specialties
            </Chip>
            {specialties.items.map((s) => (
              <Chip key={s.id} pressed={specialty === s.id} onClick={() => setSpecialty(s.id)}>
                {s.name}
              </Chip>
            ))}
          </div>
        )}
      </div>

      <LifeNotice status={store.status} error={store.error} hasFallback={false} onRetry={() => void store.load()} />

      <p className="lf-count" aria-live="polite">{loading ? "Loading" : `${shown.length} ${shown.length === 1 ? "center" : "centers"}`}</p>

      {loading && store.items.length === 0 ? (
        <LifeSkeleton />
      ) : shown.length > 0 ? (
        <motion.div layout className="lf-grid">
          <AnimatePresence mode="popLayout">
            {shown.map((c, i) => (
              <PlaceCard
                key={c.id}
                index={reduce ? 0 : Math.min(i, 6)}
                item={{
                  key: `medical-center-${c.id}`,
                  name: c.name,
                  meta: c.address ?? c.city?.name ?? "",
                  tags: c.subtype.specialties.map((s) => s.name),
                  src: c.cover?.url ?? null,
                  href: `/services/place?kind=medical-center&id=${c.id}`,
                }}
              />
            ))}
          </AnimatePresence>
        </motion.div>
      ) : store.status === "ready" ? (
        <div className="lf-empty">
          <p>{filtered ? "No centers match these filters." : "No medical centers are listed yet."}</p>
          {filtered && (
            <Chip pressed={false} onClick={clear}>
              Clear filters
            </Chip>
          )}
        </div>
      ) : null}
    </div>
  );
}
