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

interface CoverLetterDisplayProps {
  job: Job;
  className?: string;
  /** When set, shows Generate (no letter) or Regenerate (has letter) instead of hiding entirely. */
  onRequestGenerate?: () => void | Promise<void>;
  generateInFlight?: boolean;
}

export const CoverLetterDisplay: React.FC<CoverLetterDisplayProps> = ({
  job,
  className,
  onRequestGenerate,
  generateInFlight = false,
}) => {
  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]);

  const canRunGenerate =
    Boolean(onRequestGenerate) && job.status !== "processing";
  const showEmptyState = !job.coverLetter && onRequestGenerate;

  if (!job.coverLetter && !onRequestGenerate) {
    return null;
  }

  if (showEmptyState) {
    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="text-[11px] font-medium uppercase tracking-wide text-violet-600/80 dark:text-violet-400/80 flex items-center gap-1.5 mb-1.5">
            <FileText className="h-3 w-3" />
            Cover letter
          </div>
          <p className="text-xs text-muted-foreground leading-relaxed mb-2">
            Saved on this job after you generate it (Overview here, or Ready
            tab). Use Copy to paste into the employer&apos;s application form.
          </p>
          <Button
            type="button"
            size="sm"
            variant="secondary"
            className="h-8 text-xs"
            disabled={!canRunGenerate || generateInFlight}
            onClick={() => void onRequestGenerate?.()}
          >
            {generateInFlight ? (
              <>
                <Loader2 className="h-3.5 w-3.5 animate-spin mr-1.5" />
                Generating…
              </>
            ) : (
              <>
                <FileText className="h-3.5 w-3.5 mr-1.5" />
                Generate cover letter
              </>
            )}
          </Button>
        </div>
      </div>
    );
  }

  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 gap-2 flex-wrap">
          <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>
          <div className="flex items-center gap-2">
            {onRequestGenerate && (
              <button
                type="button"
                onClick={() => void onRequestGenerate()}
                disabled={!canRunGenerate || generateInFlight}
                className="text-[10px] text-muted-foreground hover:text-foreground flex items-center gap-1 transition-colors disabled:opacity-50"
              >
                {generateInFlight ? (
                  <Loader2 className="h-3 w-3 animate-spin" />
                ) : (
                  <RefreshCw className="h-3 w-3" />
                )}
                Regenerate
              </button>
            )}
            <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>
        </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>
  );
};
