import type { Job, SuitabilityAnalysis } from "@shared/types.js";
import {
  AlertTriangle,
  CheckCircle2,
  Lightbulb,
  Sparkles,
  XCircle,
} from "lucide-react";
import type React from "react";
import { useMemo } from "react";
import { cn } from "@/lib/utils";

interface FitAssessmentProps {
  job: Job;
  className?: string;
}

function parseAnalysis(raw: string | null): SuitabilityAnalysis | null {
  if (!raw) return null;
  try {
    const parsed = JSON.parse(raw);
    if (parsed && typeof parsed === "object" && Array.isArray(parsed.strengths))
      return parsed as SuitabilityAnalysis;
    return null;
  } catch {
    return null;
  }
}

function RoleMatchBadge({ score }: { score: number }) {
  const color =
    score >= 70
      ? "text-emerald-500 bg-emerald-500/10 border-emerald-500/20"
      : score >= 40
        ? "text-amber-500 bg-amber-500/10 border-amber-500/20"
        : "text-red-500 bg-red-500/10 border-red-500/20";

  const label =
    score >= 70
      ? "Strong role match"
      : score >= 40
        ? "Partial role match"
        : "Weak role match";

  return (
    <span
      className={cn(
        "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium",
        color,
      )}
    >
      {label} ({score}%)
    </span>
  );
}

function WorkArrangementBadge({ score }: { score: number }) {
  const color =
    score >= 70
      ? "text-emerald-500 bg-emerald-500/10 border-emerald-500/20"
      : score >= 40
        ? "text-amber-500 bg-amber-500/10 border-amber-500/20"
        : "text-red-500 bg-red-500/10 border-red-500/20";

  const label =
    score >= 70
      ? "Strong remote / location fit"
      : score >= 40
        ? "Partial location fit"
        : "Weak location fit";

  return (
    <span
      className={cn(
        "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium",
        color,
      )}
    >
      {label} ({score}%)
    </span>
  );
}

export const FitAssessment: React.FC<FitAssessmentProps> = ({
  job,
  className,
}) => {
  const analysis = useMemo(
    () => parseAnalysis(job.suitabilityAnalysis ?? null),
    [job.suitabilityAnalysis],
  );

  if (!job.suitabilityReason && !analysis) return null;

  return (
    <div className={cn("space-y-2", className)}>
      {/* Summary / Reason */}
      <div className="rounded-lg border border-primary/20 bg-primary/5 px-3 py-2.5">
        <div className="mb-1.5 flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-start sm:justify-between sm:gap-x-3 sm:gap-y-2">
          <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-primary/70">
            <Sparkles className="h-3 w-3 shrink-0" aria-hidden />
            <span className="leading-none">Fit assessment</span>
          </div>
          {analysis && (
            <div className="flex flex-wrap items-center gap-1.5">
              <RoleMatchBadge score={analysis.roleTypeMatch} />
              {typeof analysis.workArrangementMatch === "number" && (
                <WorkArrangementBadge score={analysis.workArrangementMatch} />
              )}
            </div>
          )}
        </div>
        {job.suitabilityReason && (
          <p className="text-xs text-foreground/90 leading-relaxed font-medium">
            {job.suitabilityReason}
          </p>
        )}
      </div>

      {analysis && (
        <div className="grid gap-2 sm:grid-cols-2">
          {/* Deal-Breaker Hits */}
          {analysis.dealBreakerHits.length > 0 && (
            <div className="sm:col-span-2 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2">
              <div className="text-[10px] font-medium uppercase tracking-wide text-destructive/80 mb-1 flex items-center gap-1">
                <AlertTriangle className="h-3 w-3" />
                Deal-breakers triggered
              </div>
              <ul className="space-y-0.5">
                {analysis.dealBreakerHits.map((hit) => (
                  <li
                    key={hit}
                    className="text-xs text-destructive/90 flex items-start gap-1.5"
                  >
                    <XCircle className="h-3 w-3 mt-0.5 shrink-0" />
                    {hit}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Strengths */}
          {analysis.strengths.length > 0 && (
            <div className="rounded-lg border border-emerald-500/20 bg-emerald-500/5 px-3 py-2">
              <div className="text-[10px] font-medium uppercase tracking-wide text-emerald-600/80 dark:text-emerald-400/80 mb-1 flex items-center gap-1">
                <CheckCircle2 className="h-3 w-3" />
                Strengths
              </div>
              <ul className="space-y-0.5">
                {analysis.strengths.map((s) => (
                  <li
                    key={s}
                    className="text-xs text-foreground/80 leading-relaxed"
                  >
                    {s}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Gaps */}
          {analysis.gaps.length > 0 && (
            <div className="rounded-lg border border-amber-500/20 bg-amber-500/5 px-3 py-2">
              <div className="text-[10px] font-medium uppercase tracking-wide text-amber-600/80 dark:text-amber-400/80 mb-1 flex items-center gap-1">
                <XCircle className="h-3 w-3" />
                Gaps
              </div>
              <ul className="space-y-0.5">
                {analysis.gaps.map((g) => (
                  <li
                    key={g}
                    className="text-xs text-foreground/80 leading-relaxed"
                  >
                    {g}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Suggestions */}
          {analysis.suggestions.length > 0 && (
            <div className="sm:col-span-2 rounded-lg border border-blue-500/20 bg-blue-500/5 px-3 py-2">
              <div className="text-[10px] font-medium uppercase tracking-wide text-blue-600/80 dark:text-blue-400/80 mb-1 flex items-center gap-1">
                <Lightbulb className="h-3 w-3" />
                Suggestions to improve fit
              </div>
              <ul className="space-y-0.5">
                {analysis.suggestions.map((s) => (
                  <li
                    key={s}
                    className="text-xs text-foreground/80 leading-relaxed"
                  >
                    {s}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  );
};
