import { ExternalLink } from "lucide-react";
import { ContentBlock, sanitizeBlocks } from "./contentBlockTypes";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  type CarouselApi,
} from "@/components/ui/carousel";
import { useEffect, useState } from "react";

function PhotoCarousel({ images, isSidebar }: { images: { url: string; alt?: string; caption?: string }[]; isSidebar: boolean }) {
  const valid = images.filter((i) => i?.url?.trim());
  const [api, setApi] = useState<CarouselApi>();
  const [current, setCurrent] = useState(0);

  useEffect(() => {
    if (!api) return;
    setCurrent(api.selectedScrollSnap());
    const onSelect = () => setCurrent(api.selectedScrollSnap());
    api.on("select", onSelect);
    return () => { api.off("select", onSelect); };
  }, [api]);

  if (valid.length === 0) return null;

  return (
    <div className={isSidebar ? "px-8" : "px-10"}>
      <Carousel setApi={setApi} opts={{ loop: valid.length > 1 }}>
        <CarouselContent>
          {valid.map((img, idx) => (
            <CarouselItem key={idx}>
              <figure className="space-y-1.5">
                <img
                  src={img.url}
                  alt={img.alt || ""}
                  className={`w-full rounded-lg border border-gray-200 object-cover ${isSidebar ? "max-h-64" : "max-h-[28rem]"}`}
                  loading="lazy"
                />
                {img.caption ? (
                  <figcaption className="text-xs text-gray-500 italic text-center">{img.caption}</figcaption>
                ) : null}
              </figure>
            </CarouselItem>
          ))}
        </CarouselContent>
        {valid.length > 1 && (
          <>
            <CarouselPrevious className="left-0 -translate-x-0" type="button" />
            <CarouselNext className="right-0 translate-x-0" type="button" />
          </>
        )}
      </Carousel>
      {valid.length > 1 && (
        <div className="flex justify-center gap-1.5 pt-2">
          {valid.map((_, idx) => (
            <button
              key={idx}
              type="button"
              aria-label={`Go to photo ${idx + 1}`}
              onClick={() => api?.scrollTo(idx)}
              className={`h-1.5 rounded-full transition-all ${current === idx ? "w-5 bg-gray-700" : "w-1.5 bg-gray-300"}`}
            />
          ))}
        </div>
      )}
    </div>
  );
}

interface Props {
  blocks: unknown;
  accent?: string;
  variant?: "main" | "sidebar";
  className?: string;
}

export default function ContentBlocksRenderer({ blocks, accent, variant = "main", className }: Props) {
  const items = sanitizeBlocks(blocks);
  if (items.length === 0) return null;

  const isSidebar = variant === "sidebar";

  return (
    <div className={["space-y-4", className].filter(Boolean).join(" ")}>
      {items.map((b) => {
        switch (b.type) {
          case "heading": {
            const text = b.text || "";
            if (!text.trim()) return null;
            const sizeClass =
              b.level === 2
                ? isSidebar ? "text-lg font-bold" : "text-2xl font-bold"
                : b.level === 4
                ? "text-sm font-semibold"
                : isSidebar ? "text-base font-semibold" : "text-xl font-bold";
            return (
              <div key={b.id} className={`${sizeClass} tracking-tight`} style={accent ? { color: accent } : undefined}>
                {text}
              </div>
            );
          }
          case "paragraph": {
            if (!b.text?.trim()) return null;
            return (
              <p key={b.id} className={`whitespace-pre-wrap leading-relaxed text-gray-700 ${isSidebar ? "text-sm" : "text-base"}`}>
                {b.text}
              </p>
            );
          }
          case "image": {
            if (!b.url?.trim()) return null;
            return (
              <figure key={b.id} className="space-y-1.5">
                <img
                  src={b.url}
                  alt={b.alt || ""}
                  className="w-full rounded-lg border border-gray-200 object-cover"
                  loading="lazy"
                />
                {b.caption ? (
                  <figcaption className="text-xs text-gray-500 italic">{b.caption}</figcaption>
                ) : null}
              </figure>
            );
          }
          case "link": {
            if (!b.url?.trim() || !b.label?.trim()) return null;
            const isExternal = /^https?:\/\//i.test(b.url);
            return (
              <a
                key={b.id}
                href={b.url}
                target={isExternal ? "_blank" : undefined}
                rel={isExternal ? "noopener noreferrer" : undefined}
                className="inline-flex items-center gap-1.5 text-sm font-semibold underline-offset-4 hover:underline"
                style={accent ? { color: accent } : undefined}
              >
                {b.label}
                {isExternal ? <ExternalLink className="h-3.5 w-3.5" /> : null}
              </a>
            );
          }
          case "divider":
            return <hr key={b.id} className="border-t border-gray-200" />;
          case "carousel": {
            return <PhotoCarousel key={b.id} images={b.images || []} isSidebar={isSidebar} />;
          }
          case "callout": {
            if (!b.text?.trim() && !b.title?.trim()) return null;
            return (
              <div
                key={b.id}
                className="rounded-lg border-l-4 bg-gray-50 p-4 space-y-1"
                style={accent ? { borderLeftColor: accent } : undefined}
              >
                {b.title ? (
                  <p className="text-sm font-semibold text-gray-900">{b.title}</p>
                ) : null}
                {b.text ? (
                  <p className="text-sm text-gray-700 whitespace-pre-wrap leading-relaxed">{b.text}</p>
                ) : null}
              </div>
            );
          }
          default:
            return null;
        }
      })}
    </div>
  );
}
