"use client";

import { useEffect } from "react";
import { useState } from "react";
import { CitySelect, Chip } from "@/components/life/Controls";
import { LifeNotice, LifeSkeleton } from "@/components/life/LifeStatus";
import Icon from "@/components/ui/Icon";
import { useNumbersStore } from "@/store/services";

const TITLE: Record<string, string> = { emergency: "Emergency", police: "Police", ambulance: "Ambulance", fire: "Fire", tourism: "Tourism police", utility: "Utilities and information" };
const title = (k: string) => TITLE[k] ?? k.charAt(0).toUpperCase() + k.slice(1);

/** Important phone numbers grouped by category. A city choice keeps the national numbers and that city's own. */
export default function NumbersDirectory() {
  const store = useNumbersStore();
  const [cityId, setCityId] = useState<number | undefined>();

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

  const shown = store.items.filter((n) => !cityId || !n.city_id || n.city_id === cityId);
  const groups = [...new Set(shown.map((n) => n.category))].map((k) => [k, shown.filter((n) => n.category === k)] as const);
  const loading = store.status === "idle" || store.status === "loading";

  return (
    <div className="lf">
      <div className="lf-tools sv-tools">
        <CitySelect value={cityId} onChange={setCityId} />
        {cityId && (
          <Chip pressed={false} onClick={() => setCityId(undefined)}>
            Clear city
          </Chip>
        )}
      </div>

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

      {loading && store.items.length === 0 ? (
        <LifeSkeleton />
      ) : (
        groups.map(([key, rows]) => (
          <section className="sv-group" key={key} aria-labelledby={`num-${key}`}>
            <h3 id={`num-${key}`} className="sv-h3">{title(key)}</h3>
            <ul className="sv-list">
              {rows.map((n) => (
                <li key={n.id}>
                  <div>
                    <strong>{n.name}</strong>
                    {(n.city || n.notes) && <small>{[n.city?.name, n.notes].filter(Boolean).join(", ")}</small>}
                  </div>
                  <a className="sv-call" href={`tel:${n.phone.replace(/\s/g, "")}`} aria-label={`Call ${n.name} on ${n.phone}`}>
                    <Icon name="call" />
                    {n.phone}
                  </a>
                </li>
              ))}
            </ul>
          </section>
        ))
      )}
    </div>
  );
}
