"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import Icon from "@/components/ui/Icon";
import Reveal from "@/components/ui/Reveal";
import { mapLegend } from "@/data/home";
import type { EventItem } from "@/lib/api/events";
import { useHomeEvents } from "@/store/home";

const TZ = "Asia/Damascus";
const mon = new Intl.DateTimeFormat("en-GB", { month: "short", timeZone: TZ });
const day = new Intl.DateTimeFormat("en-GB", { day: "2-digit", timeZone: TZ });

type Row = { key: string; mon: string; day: string; cat: string; name: string; city: string; price: string; href: string };

function fromApi(e: EventItem): Row {
  const d = e.starts_at ? new Date(e.starts_at) : null;
  return {
    key: `e-${e.id}`,
    mon: d ? mon.format(d).toUpperCase() : "",
    day: d ? day.format(d) : "",
    cat: e.category?.name ?? "",
    name: e.name,
    city: e.city?.name ?? "",
    price: e.is_free ? "Free" : e.price_from ? `From ${e.price_from}${e.currency ? ` ${e.currency}` : ""}` : "",
    href: `/life-and-fun/details/event?id=${e.id}`,
  };
}

export default function Events() {
  const [saved, setSaved] = useState<Record<string, boolean>>({});
  const { items, status, load } = useHomeEvents();
  useEffect(() => {
    if (status === "idle") void load();
  }, [status, load]);

  const pending = status === "idle" || status === "loading";
  const rows: Row[] = items.slice(0, 3).map(fromApi);

  return (
    <section className="ev" id="events">
      <div className="wrap ev-grid">
        <div>
          <Reveal>
            <span className="eyebrow">Events</span>
            <h2 className="h2">What's on this autumn</h2>
          </Reveal>
          <Reveal className="ev-list" delay={0.08}>
            {pending && [0, 1, 2].map((i) => (
              <div className="ev-row" key={i} aria-hidden="true">
                <span className="skel" style={{ width: 56, height: 64 }} />
                <span className="skel ev-thumb" />
                <div className="ev-info" style={{ flex: 1 }}>
                  <span className="skel skel-line w-40" />
                  <span className="skel skel-line w-70" />
                </div>
              </div>
            ))}
            {!pending && rows.length === 0 && <p className="ev-sub">No upcoming events right now.</p>}
            {rows.map((e) => (
              <div className="ev-row" key={e.key}>
                <div className="ev-date">
                  <b>{e.mon}</b>
                  <span>{e.day}</span>
                </div>
                <div className="ev-thumb" aria-hidden="true" />
                <Link className="ev-info" href={e.href}>
                  <span className="ev-cat">{e.cat}</span>
                  <span className="ev-name">{e.name}</span>
                  <span className="ev-sub">{[e.city, e.price].filter(Boolean).join(" · ")}</span>
                </Link>
                <button
                  className="ev-save"
                  aria-label={`Save ${e.name}`}
                  aria-pressed={!!saved[e.name]}
                  onClick={() => setSaved((s) => ({ ...s, [e.name]: !s[e.name] }))}
                >
                  <Icon name="bookmark" filled={!!saved[e.name]} />
                </button>
              </div>
            ))}
          </Reveal>
          <Reveal className="ev-more" delay={0.14}>
            <Link className="link-arrow" href="/life-and-fun/festivals-and-events">
              All events <Icon name="arrow_forward" />
            </Link>
          </Reveal>
        </div>

        <Reveal className="mapcard" delay={0.12}>
          <span className="mapcard-pin" aria-hidden="true">
            <Icon name="restaurant" />
          </span>
          <h3>See it all on the map</h3>
          <p>Every destination, stay, restaurant and event in one place, so three taps get you anywhere.</p>
          <div className="legend" style={{ marginBottom: 24 }}>
            {mapLegend.map((l) => (
              <span key={l.label}>
                <i style={{ background: l.color }} />
                {l.label}
              </span>
            ))}
          </div>
          <a className="btn btn-plum" href="#events">
            <Icon name="map" />
            View the map
          </a>
        </Reveal>
      </div>
    </section>
  );
}
