import type { Job } from "@shared/types.js";
import { Check, Copy, FileText } from "lucide-react";
import type React from "react";
import { useCallback, useState } from "react";
import { cn } from "@/lib/utils";

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

export const CoverLetterDisplay: React.FC<CoverLetterDisplayProps> = ({
  job,
  className,
}) => {
  const [copied, setCopied] = useState(false);
  const [expanded, setExpanded] = useState(false);

  const handleCopy = useCallback(async () => {
    if (!job.coverLetter) return;
    await navigator.clipboard.writeText(job.coverLetter);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }, [job.coverLetter]);

  if (!job.coverLetter) return null;

  const lines = job.coverLetter.split("\n");
  const isLong = lines.length > 8;
  const displayText = expanded ? job.coverLetter : lines.slice(0, 6).join("\n");

  return (
    <div className={cn("space-y-1", className)}>
      <div className="rounded-lg border border-violet-500/20 bg-violet-500/5 px-3 py-2.5">
        <div className="flex items-center justify-between mb-1.5">
          <div className="text-[11px] font-medium uppercase tracking-wide text-violet-600/80 dark:text-violet-400/80 flex items-center gap-1.5">
            <FileText className="h-3 w-3" />
            Cover Letter
          </div>
          <button
            type="button"
            onClick={handleCopy}
            className="text-[10px] text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors"
          >
            {copied ? (
              <>
                <Check className="h-3 w-3" /> Copied
              </>
            ) : (
              <>
                <Copy className="h-3 w-3" /> Copy
              </>
            )}
          </button>
        </div>
        <p className="text-xs text-foreground/85 leading-relaxed whitespace-pre-wrap">
          {displayText}
          {isLong && !expanded && "..."}
        </p>
        {isLong && (
          <button
            type="button"
            onClick={() => setExpanded(!expanded)}
            className="mt-1.5 text-[10px] text-violet-600/70 dark:text-violet-400/70 hover:text-violet-600 dark:hover:text-violet-400 transition-colors"
          >
            {expanded ? "Show less" : "Show full letter"}
          </button>
        )}
      </div>
    </div>
  );
};
