import React, { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "./ui/dialog";
import { CandidateSummary } from "../types/heatmap";
import { LEADERBOARD_SIZE } from "../constants/organizations";

interface TrackedOrgsDialogProps {
  allCandidates: CandidateSummary[];
}

const TrackedOrgsDialog: React.FC<TrackedOrgsDialogProps> = ({
  allCandidates,
}) => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <button className="text-sm text-foreground hover:text-blue-500 transition-colors duration-200">
          Tracked Orgs
        </button>
      </DialogTrigger>
      <DialogContent className="w-full max-w-[95vw] sm:max-w-2xl p-4 sm:p-6 max-h-[85vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="text-lg sm:text-xl mb-2">
            Tracked Organizations
          </DialogTitle>
          <p className="text-sm text-muted-foreground">
            Tracking {allCandidates.length} organizations, showing top{" "}
            {LEADERBOARD_SIZE} by activity on the leaderboard.
          </p>
        </DialogHeader>
        <div className="flex-grow overflow-y-auto mt-4">
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            {allCandidates.map((candidate) => (
              <a
                key={candidate.author}
                href={`https://huggingface.co/${candidate.author}`}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-background/60 hover:bg-muted/50 hover:border-blue-500/40 transition-all duration-200"
              >
                {candidate.avatarUrl ? (
                  <img
                    src={candidate.avatarUrl}
                    alt={candidate.fullName}
                    className="w-7 h-7 rounded-md flex-shrink-0"
                  />
                ) : (
                  <div className="w-7 h-7 rounded-md bg-muted flex items-center justify-center text-xs font-bold text-muted-foreground flex-shrink-0">
                    {candidate.fullName.charAt(0).toUpperCase()}
                  </div>
                )}
                <span className="text-sm font-medium text-foreground truncate">
                  {candidate.fullName}
                </span>
              </a>
            ))}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default TrackedOrgsDialog;
