"use client";

import Link from "next/link";
import { Heart, X } from "lucide-react";
import { useFollows, useRemoveFollow } from "@/lib/hooks/useFollows";
import { billLabel } from "@/lib/utils";

export default function FollowingPage() {
  const { data: follows = [], isLoading } = useFollows();
  const remove = useRemoveFollow();

  const bills = follows.filter((f) => f.follow_type === "bill");
  const members = follows.filter((f) => f.follow_type === "member");
  const topics = follows.filter((f) => f.follow_type === "topic");

  const Section = ({ title, items, renderValue }: {
    title: string;
    items: typeof follows;
    renderValue: (v: string) => React.ReactNode;
  }) => (
    <div>
      <h2 className="font-semibold mb-3">{title} ({items.length})</h2>
      {!items.length ? (
        <p className="text-sm text-muted-foreground">Nothing followed yet.</p>
      ) : (
        <div className="space-y-2">
          {items.map((f) => (
            <div key={f.id} className="bg-card border border-border rounded-lg p-3 flex items-center justify-between">
              <div>{renderValue(f.follow_value)}</div>
              <button
                onClick={() => remove.mutate(f.id)}
                className="text-muted-foreground hover:text-destructive transition-colors p-1"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );

  if (isLoading) return <div className="text-center py-20 text-muted-foreground">Loading...</div>;

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold flex items-center gap-2">
          <Heart className="w-5 h-5" /> Following
        </h1>
        <p className="text-muted-foreground text-sm mt-1">Manage what you follow</p>
      </div>

      <Section
        title="Bills"
        items={bills}
        renderValue={(v) => {
          const [congress, type, num] = v.split("-");
          return (
            <Link href={`/bills/${v}`} className="text-sm font-medium hover:text-primary transition-colors">
              {type && num ? billLabel(type, parseInt(num)) : v}
            </Link>
          );
        }}
      />

      <Section
        title="Members"
        items={members}
        renderValue={(v) => (
          <Link href={`/members/${v}`} className="text-sm font-medium hover:text-primary transition-colors">
            {v}
          </Link>
        )}
      />

      <Section
        title="Topics"
        items={topics}
        renderValue={(v) => (
          <Link href={`/bills?topic=${v}`} className="text-sm font-medium hover:text-primary transition-colors capitalize">
            {v.replace("-", " ")}
          </Link>
        )}
      />
    </div>
  );
}
