"use client";

import { useState } from "react";

export default function AiBioGenerator() {
  const [loading, setLoading] = useState(false);
  const [generatedBio, setGeneratedBio] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  async function handleGenerate() {
    setLoading(true);
    setError(null);
    setGeneratedBio(null);

    try {
      const charRes = await fetch("/api/profile/characteristics");
      const charData = await charRes.json();

      const res = await fetch("/api/ai/generate-description", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ characteristics: charData.characteristic }),
      });

      if (!res.ok) throw new Error("Failed to generate bio");

      const data = await res.json();
      setGeneratedBio(data.description || data.text || data.bio || "");
    } catch {
      setError("Failed to generate bio. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  async function handleCopy() {
    if (!generatedBio) return;
    try {
      await navigator.clipboard.writeText(generatedBio);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // Fallback
      const textarea = document.createElement("textarea");
      textarea.value = generatedBio;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  }

  return (
    <div className="space-y-3">
      <button
        type="button"
        onClick={handleGenerate}
        disabled={loading}
        className="inline-flex items-center gap-2 bg-gold/20 hover:bg-gold/30 text-gold border border-gold/30 font-semibold px-4 py-2 rounded-lg transition-all duration-200 text-sm disabled:opacity-50"
      >
        {loading ? (
          <>
            <svg
              className="w-4 h-4 animate-spin"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              />
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
              />
            </svg>
            Generating...
          </>
        ) : (
          <>
            <svg
              className="w-4 h-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"
              />
            </svg>
            Generate Bio with AI
          </>
        )}
      </button>

      {error && (
        <div className="bg-red-900/30 text-red-400 text-sm rounded-lg p-3">
          {error}
        </div>
      )}

      {generatedBio && (
        <div className="bg-background border border-gold/20 rounded-lg p-4 space-y-3">
          <p className="text-xs text-gold font-medium uppercase tracking-wide">
            AI Generated Bio
          </p>
          <p className="text-text text-sm leading-relaxed whitespace-pre-wrap">
            {generatedBio}
          </p>
          <button
            type="button"
            onClick={handleCopy}
            className="inline-flex items-center gap-2 bg-gold hover:bg-gold-light text-black font-semibold px-4 py-2 rounded-lg transition-all duration-200 text-sm"
          >
            {copied ? (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                Copied!
              </>
            ) : (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                </svg>
                Use This
              </>
            )}
          </button>
        </div>
      )}
    </div>
  );
}
