"use client";

import { useEffect, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import type { RecentPost } from "@/lib/cms/fetcher";
import { CMS_LABEL, CMS_ICON } from "@/lib/sag/cms";
import type { CmsPlatform } from "@/lib/sag/types";

interface Props {
  slug: string;
  limit?: number;
}

interface ApiResp {
  posts: RecentPost[];
  platform: CmsPlatform;
  websiteUrl?: string | null;
  error?: string;
}

export function RecentCmsPosts({ slug, limit = 6 }: Props) {
  const [data, setData] = useState<ApiResp | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const resp = await fetch(`/api/cms/posts?slug=${slug}&limit=${limit}`);
        const json = (await resp.json()) as ApiResp;
        if (active) setData(json);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, [slug, limit]);

  if (loading) {
    return (
      <Card>
        <CardContent className="p-5">
          <h3 className="text-base font-semibold">Recent site posts</h3>
          <p className="mt-1 text-xs text-muted-foreground">Loading...</p>
        </CardContent>
      </Card>
    );
  }

  if (!data) return null;

  if (data.platform === "none" || data.platform === "custom" || !data.websiteUrl) {
    return (
      <Card>
        <CardContent className="p-5">
          <h3 className="text-base font-semibold">Recent site posts</h3>
          <p className="mt-1 text-xs text-muted-foreground">
            {data.platform === "custom"
              ? "Custom Next.js site — wire post-fetching directly if needed."
              : "No CMS configured for this entity."}
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardContent className="p-5">
        <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
          <div>
            <h3 className="text-base font-semibold">Recent site posts</h3>
            <p className="text-xs text-muted-foreground">
              <Badge variant="info" className="mr-1.5">{CMS_ICON[data.platform]} {CMS_LABEL[data.platform]}</Badge>
              {data.websiteUrl?.replace(/^https?:\/\//, "")}
            </p>
          </div>
          {data.websiteUrl && (
            <Button asChild variant="ghost" size="sm">
              <a href={data.websiteUrl} target="_blank" rel="noopener noreferrer">Visit site ↗</a>
            </Button>
          )}
        </div>

        {data.error && (
          <div className="rounded-md border border-yellow-500/30 bg-yellow-50 dark:bg-yellow-900/10 p-3 text-xs">
            <span className="font-medium">Couldn’t reach the site:</span> {data.error}
            <div className="mt-1 text-muted-foreground">
              Possible causes: site is offline, RSS/REST endpoint is custom, or the URL in <code>src/lib/sag/cms.ts</code> needs updating.
            </div>
          </div>
        )}

        {!data.error && data.posts.length === 0 && (
          <p className="text-sm text-muted-foreground">No published posts found.</p>
        )}

        {data.posts.length > 0 && (
          <ul className="space-y-2.5">
            {data.posts.map((p) => (
              <li key={p.id}>
                <a href={p.url} target="_blank" rel="noopener noreferrer" className="block rounded-md border bg-background p-3 hover:bg-accent transition-colors">
                  <div className="flex gap-3">
                    {p.imageUrl && (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={p.imageUrl}
                        alt=""
                        className="w-16 h-16 rounded-md object-cover shrink-0"
                      />
                    )}
                    <div className="min-w-0 flex-1">
                      <div className="font-medium text-sm line-clamp-1">{p.title}</div>
                      <div className="mt-0.5 text-[10px] text-muted-foreground">
                        {new Date(p.publishedAt).toLocaleDateString()}
                        {p.author && ` · ${p.author}`}
                      </div>
                      {p.excerpt && <p className="mt-1 text-xs text-muted-foreground line-clamp-2">{p.excerpt}</p>}
                    </div>
                  </div>
                </a>
              </li>
            ))}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
