"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { alignmentAPI } from "@/lib/api";
import { useAuthStore } from "@/stores/authStore";
import type { AlignmentScore } from "@/lib/types";

function partyColor(party?: string) {
  if (!party) return "bg-muted text-muted-foreground";
  const p = party.toLowerCase();
  if (p.includes("republican") || p === "r") return "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400";
  if (p.includes("democrat") || p === "d") return "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400";
  return "bg-muted text-muted-foreground";
}

function AlignmentBar({ pct }: { pct: number }) {
  const color =
    pct >= 66 ? "bg-emerald-500" : pct >= 33 ? "bg-amber-500" : "bg-red-500";
  return (
    <div className="flex-1 h-1.5 bg-muted rounded overflow-hidden">
      <div className={`h-full rounded ${color}`} style={{ width: `${pct}%` }} />
    </div>
  );
}

function MemberRow({ member }: { member: AlignmentScore }) {
  const pct = member.alignment_pct;
  return (
    <Link
      href={`/members/${member.bioguide_id}`}
      className="flex items-center gap-3 py-3 hover:bg-accent/50 rounded-md px-2 -mx-2 transition-colors"
    >
      {member.photo_url ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src={member.photo_url}
          alt={member.name}
          className="w-9 h-9 rounded-full object-cover shrink-0 border border-border"
        />
      ) : (
        <div className="w-9 h-9 rounded-full bg-muted flex items-center justify-center shrink-0 border border-border text-xs font-medium text-muted-foreground">
          {member.name.charAt(0)}
        </div>
      )}

      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-2">
          <span className="text-sm font-medium truncate">{member.name}</span>
          <span className="text-sm font-mono font-semibold shrink-0">
            {pct != null ? `${Math.round(pct)}%` : "—"}
          </span>
        </div>

        <div className="flex items-center gap-2 mt-1">
          {member.party && (
            <span className={`text-xs px-1.5 py-0.5 rounded font-medium ${partyColor(member.party)}`}>
              {member.party.charAt(0)}
            </span>
          )}
          {member.state && (
            <span className="text-xs text-muted-foreground">{member.state}</span>
          )}
          {pct != null && <AlignmentBar pct={pct} />}
        </div>

        <p className="text-xs text-muted-foreground mt-0.5">
          {member.aligned} aligned · {member.opposed} opposed · {member.total} overlapping vote{member.total !== 1 ? "s" : ""}
        </p>
      </div>
    </Link>
  );
}

export default function AlignmentPage() {
  const currentUser = useAuthStore((s) => s.user);

  const { data, isLoading } = useQuery({
    queryKey: ["alignment"],
    queryFn: () => alignmentAPI.get(),
    enabled: !!currentUser,
    staleTime: 5 * 60 * 1000,
  });

  if (!currentUser) {
    return (
      <div className="text-center py-20 space-y-3">
        <p className="text-muted-foreground">Sign in to see your representation alignment.</p>
        <Link href="/login" className="text-sm text-primary hover:underline">Sign in →</Link>
      </div>
    );
  }

  if (isLoading) {
    return <div className="text-center py-20 text-muted-foreground text-sm">Loading alignment data…</div>;
  }

  const members = data?.members ?? [];
  const hasStance = (data?.total_bills_with_stance ?? 0) > 0;
  const hasFollowedMembers = members.length > 0 || (data?.total_bills_with_votes ?? 0) > 0;

  return (
    <div className="space-y-6 max-w-xl">
      <div>
        <h1 className="text-2xl font-bold">Representation Alignment</h1>
        <p className="text-sm text-muted-foreground mt-1">
          How often do your followed members vote with your bill positions?
        </p>
      </div>

      {/* How it works */}
      <div className="bg-card border border-border rounded-lg p-4 text-sm space-y-1.5">
        <p className="font-medium">How this works</p>
        <p className="text-muted-foreground leading-relaxed">
          For every bill you follow with <strong>Pocket Boost</strong> or <strong>Pocket Veto</strong>, we check
          how each of your followed members voted on that bill. A Yea vote on a boosted bill counts as
          aligned; a Nay vote on a vetoed bill counts as aligned. All other combinations count as opposed.
          Not Voting and Present are excluded.
        </p>
        {data && (
          <p className="text-xs text-muted-foreground pt-1">
            {data.total_bills_with_stance} bill{data.total_bills_with_stance !== 1 ? "s" : ""} with a stance ·{" "}
            {data.total_bills_with_votes} had roll-call votes
          </p>
        )}
      </div>

      {/* Empty states */}
      {!hasStance && (
        <div className="text-center py-12 text-muted-foreground space-y-2">
          <p className="text-sm">No bill stances yet.</p>
          <p className="text-xs">
            Follow some bills with{" "}
            <Link href="/bills" className="text-primary hover:underline">Pocket Boost or Pocket Veto</Link>{" "}
            to start tracking alignment.
          </p>
        </div>
      )}

      {hasStance && members.length === 0 && (
        <div className="text-center py-12 text-muted-foreground space-y-2">
          <p className="text-sm">No overlapping votes found yet.</p>
          <p className="text-xs">
            Make sure you&apos;re{" "}
            <Link href="/members" className="text-primary hover:underline">following some members</Link>
            , and that those members have voted on bills you&apos;ve staked a position on.
          </p>
        </div>
      )}

      {/* Member list */}
      {members.length > 0 && (
        <div className="bg-card border border-border rounded-lg p-4">
          <div className="divide-y divide-border">
            {members.map((m) => (
              <MemberRow key={m.bioguide_id} member={m} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
