"use client";

import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";

import { Card, CardContent } from "@/components/shadcn/card/card";
import { Progress } from "@/components/shadcn/progress";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/shadcn/tooltip";
import { getReportTypeForCompliance } from "@/lib/compliance/compliance-report-types";
import {
  getScoreIndicatorClass,
  type ScoreColorVariant,
} from "@/lib/compliance/score-utils";
import { ScanEntity } from "@/types/scans";

import { getComplianceIcon } from "../icons";
import { ComplianceDownloadContainer } from "./compliance-download-container";

interface ComplianceCardProps {
  title: string;
  version: string;
  passingRequirements: number;
  totalRequirements: number;
  prevPassingRequirements: number;
  prevTotalRequirements: number;
  scanId: string;
  complianceId: string;
  id: string;
  selectedScan?: ScanEntity;
  /**
   * True when this compliance_id is the highest CIS version for its provider.
   * Only the latest CIS variant per provider has a PDF generated by the
   * backend, so older variants must not expose the PDF download button.
   * Ignored for non-CIS frameworks.
   */
  isLatestCisForProvider?: boolean;
}

export const ComplianceCard: React.FC<ComplianceCardProps> = ({
  title,
  version,
  passingRequirements,
  totalRequirements,
  scanId,
  complianceId,
  id,
  isLatestCisForProvider = false,
}) => {
  const searchParams = useSearchParams();
  const router = useRouter();
  const hasRegionFilter = searchParams.has("filter[region__in]");

  const formatTitle = (title: string) => {
    return title.split("-").join(" ");
  };

  const ratingPercentage = Math.floor(
    (passingRequirements / totalRequirements) * 100,
  );

  const getRatingVariant = (value: number): ScoreColorVariant => {
    if (value <= 10) return "danger";
    if (value <= 40) return "warning";
    return "success";
  };

  const navigateToDetail = () => {
    const formattedTitleForUrl = encodeURIComponent(title);
    const path = `/compliance/${formattedTitleForUrl}`;
    const params = new URLSearchParams();

    params.set("complianceId", id);
    params.set("version", version);
    params.set("scanId", scanId);

    const regionFilter = searchParams.get("filter[region__in]");
    if (regionFilter) {
      params.set("filter[region__in]", regionFilter);
    }

    router.push(`${path}?${params.toString()}`);
  };

  return (
    <Card
      variant="base"
      padding="md"
      className="relative cursor-pointer transition-shadow hover:shadow-md"
      onClick={navigateToDetail}
    >
      <div
        className="absolute top-2 right-2 z-10"
        onClick={(e) => e.stopPropagation()}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.stopPropagation();
          }
        }}
        role="group"
        tabIndex={0}
      >
        <ComplianceDownloadContainer
          compact
          orientation="column"
          buttonWidth="icon"
          presentation="dropdown"
          scanId={scanId}
          complianceId={complianceId}
          reportType={getReportTypeForCompliance(
            title,
            complianceId,
            isLatestCisForProvider,
          )}
          disabled={hasRegionFilter}
        />
      </div>
      <CardContent className="p-0">
        <div className="flex w-full flex-col gap-3">
          <div className="flex items-center gap-3 pr-9">
            {getComplianceIcon(title) && (
              <div className="flex h-10 w-10 min-w-10 shrink-0 items-center justify-center rounded-md border border-gray-300 bg-white">
                <Image
                  src={getComplianceIcon(title)}
                  alt={`${title} logo`}
                  width={32}
                  height={32}
                  className="h-8 w-8 object-contain"
                />
              </div>
            )}
            <div className="flex min-w-0 flex-1 flex-col">
              <Tooltip>
                <TooltipTrigger asChild>
                  <h4 className="text-small truncate leading-5 font-bold">
                    {formatTitle(title)}
                    {version ? ` - ${version}` : ""}
                  </h4>
                </TooltipTrigger>
                <TooltipContent>
                  {formatTitle(title)}
                  {version ? ` - ${version}` : ""}
                </TooltipContent>
              </Tooltip>
              <small className="truncate">
                <span className="mr-1 text-xs font-semibold">
                  {passingRequirements} / {totalRequirements}
                </span>
                Passing Requirements
              </small>
            </div>
          </div>
          <div className="flex flex-col gap-2">
            <div className="flex items-center justify-between gap-3 text-xs">
              <span className="text-text-neutral-secondary font-medium tracking-wider">
                Score:
              </span>
              <span className="text-text-neutral-secondary">
                {ratingPercentage}%
              </span>
            </div>
            <Progress
              aria-label="Compliance score"
              value={ratingPercentage}
              className="border-border-neutral-secondary h-2.5 border drop-shadow-sm"
              indicatorClassName={getScoreIndicatorClass(
                getRatingVariant(ratingPercentage),
              )}
            />
          </div>
        </div>
      </CardContent>
    </Card>
  );
};
