"use client";

import { useState } from "react";
import Link from "next/link";
import { Search, Heart } from "lucide-react";
import { useMembers, useMember } from "@/lib/hooks/useMembers";
import { useFollows } from "@/lib/hooks/useFollows";
import { useAuthStore } from "@/stores/authStore";
import { FollowButton } from "@/components/shared/FollowButton";
import { cn, partyBadgeColor } from "@/lib/utils";

function FollowedMemberRow({ bioguideId }: { bioguideId: string }) {
  const { data: member } = useMember(bioguideId);
  if (!member) return null;
  return (
    <div className="bg-card border border-border rounded-lg p-4 flex items-start justify-between gap-3">
      <div className="flex-1 min-w-0">
        <Link href={`/members/${member.bioguide_id}`} className="font-medium text-sm hover:text-primary transition-colors">
          {member.name}
        </Link>
        <div className="flex items-center gap-1.5 mt-1">
          {member.party && (
            <span className={cn("px-1.5 py-0.5 rounded text-xs font-medium", partyBadgeColor(member.party))}>
              {member.party}
            </span>
          )}
          {member.state && <span className="text-xs text-muted-foreground">{member.state}</span>}
          {member.chamber && <span className="text-xs text-muted-foreground">{member.chamber}</span>}
        </div>
      </div>
      <FollowButton type="member" value={member.bioguide_id} />
    </div>
  );
}

export default function MembersPage() {
  const [q, setQ] = useState("");
  const [chamber, setChamber] = useState("");
  const [party, setParty] = useState("");
  const [page, setPage] = useState(1);

  const { data, isLoading } = useMembers({
    ...(q && { q }), ...(chamber && { chamber }), ...(party && { party }),
    page, per_page: 50,
  });

  const token = useAuthStore((s) => s.token);
  const { data: follows } = useFollows();
  const followedMemberIds = follows?.filter((f) => f.follow_type === "member").map((f) => f.follow_value) ?? [];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Members</h1>
        <p className="text-muted-foreground text-sm mt-1">Browse current Congress members</p>
      </div>

      <div className="flex gap-3 flex-wrap">
        <div className="relative flex-1 min-w-48">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <input
            type="text"
            placeholder="Search by name..."
            value={q}
            onChange={(e) => { setQ(e.target.value); setPage(1); }}
            className="w-full pl-9 pr-3 py-2 text-sm bg-card border border-border rounded-md focus:outline-none"
          />
        </div>
        <select value={chamber} onChange={(e) => { setChamber(e.target.value); setPage(1); }}
          className="px-3 py-2 text-sm bg-card border border-border rounded-md">
          <option value="">All Chambers</option>
          <option value="House of Representatives">House</option>
          <option value="Senate">Senate</option>
        </select>
        <select value={party} onChange={(e) => { setParty(e.target.value); setPage(1); }}
          className="px-3 py-2 text-sm bg-card border border-border rounded-md">
          <option value="">All Parties</option>
          <option value="Democratic">Democratic</option>
          <option value="Republican">Republican</option>
          <option value="Independent">Independent</option>
        </select>
      </div>

      {token && followedMemberIds.length > 0 && (
        <div className="space-y-3">
          <h2 className="font-semibold text-sm flex items-center gap-2">
            <Heart className="w-4 h-4 text-red-500 fill-red-500" />
            Following ({followedMemberIds.length})
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {followedMemberIds.map((id) => (
              <FollowedMemberRow key={id} bioguideId={id} />
            ))}
          </div>
          <div className="border-t border-border pt-2" />
        </div>
      )}

      {isLoading ? (
        <div className="text-center py-20 text-muted-foreground">Loading members...</div>
      ) : (
        <>
          <div className="text-sm text-muted-foreground">{data?.total ?? 0} members</div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {data?.items?.map((member) => (
              <div key={member.bioguide_id} className="bg-card border border-border rounded-lg p-4 flex items-start justify-between gap-3">
                <div className="flex-1 min-w-0">
                  <Link href={`/members/${member.bioguide_id}`} className="font-medium text-sm hover:text-primary transition-colors">
                    {member.name}
                  </Link>
                  <div className="flex items-center gap-1.5 mt-1">
                    {member.party && (
                      <span className={cn("px-1.5 py-0.5 rounded text-xs font-medium", partyBadgeColor(member.party))}>
                        {member.party}
                      </span>
                    )}
                    {member.state && <span className="text-xs text-muted-foreground">{member.state}</span>}
                    {member.chamber && <span className="text-xs text-muted-foreground">{member.chamber}</span>}
                  </div>
                </div>
                <FollowButton type="member" value={member.bioguide_id} />
              </div>
            ))}
          </div>
          {data && data.pages > 1 && (
            <div className="flex justify-center gap-2">
              <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page === 1}
                className="px-4 py-2 text-sm bg-card border border-border rounded-md disabled:opacity-40 hover:bg-accent">Previous</button>
              <button onClick={() => setPage((p) => Math.min(data.pages, p + 1))} disabled={page === data.pages}
                className="px-4 py-2 text-sm bg-card border border-border rounded-md disabled:opacity-40 hover:bg-accent">Next</button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
