"use client";

import { useState } from "react";
import Link from "next/link";
import { MapPin, Search, Heart } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
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 { membersAPI } from "@/lib/api";
import { cn, partyBadgeColor } from "@/lib/utils";
import type { Member } from "@/lib/types";

function MemberCard({ member }: { member: Member }) {
  return (
    <div className="bg-card border border-border rounded-lg p-4 flex items-start justify-between gap-3">
      <div className="flex items-start gap-3 flex-1 min-w-0">
        {member.photo_url ? (
          <img src={member.photo_url} alt={member.name} className="w-10 h-10 rounded-full object-cover shrink-0 border border-border" />
        ) : (
          <div className="w-10 h-10 rounded-full bg-muted flex items-center justify-center text-sm font-semibold text-muted-foreground shrink-0">
            {member.name[0]}
          </div>
        )}
        <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 flex-wrap">
            {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>
          {(member.phone || member.official_url) && (
            <div className="flex items-center gap-2 mt-1">
              {member.phone && (
                <a href={`tel:${member.phone.replace(/\D/g, "")}`} className="text-xs text-muted-foreground hover:text-foreground transition-colors">
                  {member.phone}
                </a>
              )}
              {member.official_url && (
                <a href={member.official_url} target="_blank" rel="noopener noreferrer" className="text-xs text-primary hover:underline">
                  Contact
                </a>
              )}
            </div>
          )}
        </div>
      </div>
      <FollowButton type="member" value={member.bioguide_id} />
    </div>
  );
}

function FollowedMemberRow({ bioguideId }: { bioguideId: string }) {
  const { data: member } = useMember(bioguideId);
  if (!member) return null;
  return <MemberCard member={member} />;
}

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

  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) ?? [];

  const isValidZip = /^\d{5}$/.test(submittedZip);
  const { data: myReps, isFetching: repsFetching, error: repsError } = useQuery({
    queryKey: ["members-by-zip", submittedZip],
    queryFn: () => membersAPI.byZip(submittedZip),
    enabled: isValidZip,
    staleTime: 24 * 60 * 60 * 1000,
    retry: false,
  });

  function handleZipSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmittedZip(zipInput.trim());
  }

  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>

      {/* Zip lookup */}
      <div className="bg-card border border-border rounded-lg p-4 space-y-3">
        <p className="text-sm font-medium flex items-center gap-2">
          <MapPin className="w-4 h-4 text-primary" />
          Find your representatives
        </p>
        <form onSubmit={handleZipSubmit} className="flex gap-2">
          <input
            type="text"
            value={zipInput}
            onChange={(e) => setZipInput(e.target.value)}
            placeholder="Enter ZIP code"
            maxLength={5}
            className="px-3 py-2 text-sm bg-background border border-border rounded-md focus:outline-none focus:ring-1 focus:ring-primary w-40"
          />
          <button
            type="submit"
            disabled={!/^\d{5}$/.test(zipInput.trim())}
            className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50 transition-colors"
          >
            Find
          </button>
        </form>

        {repsFetching && (
          <p className="text-sm text-muted-foreground">Looking up representatives…</p>
        )}
        {repsError && (
          <p className="text-sm text-destructive">Could not look up representatives. Check your ZIP and try again.</p>
        )}
        {isValidZip && !repsFetching && myReps && myReps.length === 0 && (
          <p className="text-sm text-muted-foreground">No representatives found for {submittedZip}.</p>
        )}
        {myReps && myReps.length > 0 && (
          <div className="space-y-2 pt-1">
            <p className="text-xs text-muted-foreground">Representatives for ZIP {submittedZip}</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {myReps.map((rep) => (
                <MemberCard key={rep.bioguide_id} member={rep} />
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Filters */}
      <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) => (
              <MemberCard key={member.bioguide_id} member={member} />
            ))}
          </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>
  );
}
