"use client";

import { AnimatePresence, motion } from "framer-motion";
import Image from "next/image";
import { useEffect, useState } from "react";
import { ArrowUpRight, InstagramIcon } from "@/components/icons";
import { Reveal, SectionLabel } from "@/components/motion";
import { studio } from "@/lib/content";

type Post = {
  id: string;
  permalink: string;
  imageUrl: string;
  caption: string;
  likes: number | null;
  comments: number | null;
  timestamp: string | null;
  mediaType: string;
};

type Feed = {
  handle: string;
  profileUrl: string;
  followers: number | null;
  posts: Post[];
  source: string;
  live: boolean;
  fetchedAt: string;
};

function Skeleton() {
  return (
    <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
      {[0, 1, 2, 3].map((i) => (
        <div
          key={i}
          className="relative aspect-square overflow-hidden rounded-[3px] bg-[#f4f4f4]"
        >
          <div className="absolute inset-0 animate-[shimmer_2.4s_ease-in-out_infinite] bg-gradient-to-br from-[#f4f4f4] via-[#ececec] to-[#f4f4f4]" />
        </div>
      ))}
    </div>
  );
}

function formatCount(n: number) {
  return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);
}

export default function InstagramFeed() {
  const [feed, setFeed] = useState<Feed | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch("/api/instagram", { cache: "no-store" });
        const data = (await res.json()) as Feed;
        if (!cancelled) setFeed(data);
      } catch {
        if (!cancelled) setFeed(null);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const posts = feed?.posts ?? [];

  return (
    <section id="journal" className="relative border-t border-[#efefef] py-24 md:py-32">
      <div className="mx-auto max-w-[1600px] px-5 md:px-10">
        <Reveal className="flex flex-col gap-6 md:flex-row md:items-end md:justify-between">
          <div>
            <SectionLabel>Latest from the studio</SectionLabel>
            <h2 className="mt-6 flex items-center gap-4 text-[clamp(1.8rem,3.8vw,3.2rem)] font-medium leading-[1.05] tracking-display">
              <InstagramIcon className="h-8 w-8 text-[#c9c9c9] md:h-10 md:w-10" />
              {studio.instagramHandle}
            </h2>
            <p className="mt-4 max-w-[52ch] text-[15px] leading-relaxed text-mute">
              Work in progress, prototypes, fair visits and new releases — straight
              from the studio floor in Barcelona.
            </p>
          </div>

          <div className="flex flex-col items-start gap-3 md:items-end">
            <a
              href={studio.instagram}
              target="_blank"
              rel="noopener noreferrer"
              className="group inline-flex items-center gap-3 rounded-full border border-[#e0e0e0] px-6 py-3.5 text-[11px] font-medium uppercase tracking-[0.2em] text-ink-soft transition-all duration-300 hover:border-[#0a0a0a]"
            >
              Follow on Instagram
              <ArrowUpRight className="h-4 w-4 transition-transform duration-300 group-hover:-translate-y-0.5 group-hover:translate-x-0.5" />
            </a>
            <p className="text-[11px] uppercase tracking-[0.18em] text-faint">
              {loading
                ? "Loading feed"
                : feed?.live
                  ? `Live · ${feed.source}`
                  : "Latest studio projects"}
              {feed?.followers ? ` · ${formatCount(feed.followers)} followers` : ""}
            </p>
          </div>
        </Reveal>

        <div className="mt-12">
          {loading && !posts.length ? (
            <Skeleton />
          ) : (
            <motion.div
              layout
              className="grid grid-cols-2 gap-4 lg:grid-cols-4"
            >
              <AnimatePresence mode="popLayout">
                {posts.map((post, i) => {
                  const isLocal = post.imageUrl.startsWith("/");
                  return (
                    <motion.a
                      key={post.id}
                      href={post.permalink}
                      target="_blank"
                      rel="noopener noreferrer"
                      initial={{ opacity: 0, y: 26 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -14 }}
                      transition={{
                        duration: 0.7,
                        delay: i * 0.08,
                        ease: [0.16, 1, 0.3, 1],
                      }}
                      className="group relative block overflow-hidden rounded-[3px] bg-[#f4f4f4]"
                    >
                      <div className="relative aspect-square w-full">
                        {isLocal ? (
                          <Image
                            src={post.imageUrl}
                            alt={`${studio.instagramHandle} post — ${post.caption}`}
                            fill
                            sizes="(max-width: 1024px) 50vw, 25vw"
                            quality={85}
                            className="object-contain p-1 transition-transform duration-[1100ms] ease-[cubic-bezier(0.16,1,0.3,1)] group-hover:scale-[1.03]"
                          />
                        ) : (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img
                            src={post.imageUrl}
                            alt={`${studio.instagramHandle} post — ${post.caption}`}
                            loading="lazy"
                            referrerPolicy="no-referrer"
                            className="absolute inset-0 h-full w-full object-cover transition-transform duration-[1100ms] ease-[cubic-bezier(0.16,1,0.3,1)] group-hover:scale-[1.06]"
                            onError={(e) => {
                              (e.currentTarget as HTMLImageElement).style.objectFit = "contain";
                            }}
                          />
                        )}
                      </div>

                      <div className="absolute inset-0 flex flex-col justify-end bg-gradient-to-t from-black/65 via-black/0 to-black/0 p-4 opacity-0 transition-opacity duration-500 group-hover:opacity-100">
                        <p className="line-clamp-3 text-[11.5px] leading-relaxed text-white/90">
                          {post.caption || "View on Instagram"}
                        </p>
                        <div className="mt-2 flex items-center gap-4 text-[10px] uppercase tracking-[0.18em] text-white/70">
                          {post.likes !== null && <span>♥ {formatCount(post.likes)}</span>}
                          {post.comments !== null && (
                            <span>◎ {formatCount(post.comments)}</span>
                          )}
                          <span className="ml-auto flex items-center gap-1">
                            Open <ArrowUpRight className="h-3 w-3" />
                          </span>
                        </div>
                      </div>

                      <span className="absolute right-3 top-3 flex h-8 w-8 items-center justify-center rounded-full bg-white/85 text-ink opacity-0 backdrop-blur transition-all duration-500 group-hover:opacity-100">
                        <InstagramIcon className="h-4 w-4" />
                      </span>
                    </motion.a>
                  );
                })}
              </AnimatePresence>
            </motion.div>
          )}
        </div>
      </div>
    </section>
  );
}
