"use client";

/**
 * Blog AI Generator Component
 * Allows staff to generate blog posts using AI
 */

import { useState } from "react";
import type {
  BlogGenerationInput,
  BlogGenerationOutput,
} from "@/lib/types/social-media.types";

type Tone = "professional" | "casual" | "informative";
type Language = "ar" | "en";

interface BlogAIGeneratorProps {
  onGenerated?: (output: BlogGenerationOutput) => void;
  onSave?: (output: BlogGenerationOutput) => void;
}

export function BlogAIGenerator({ onGenerated, onSave }: BlogAIGeneratorProps) {
  const [topic, setTopic] = useState("");
  const [keywords, setKeywords] = useState("");
  const [tone, setTone] = useState<Tone>("professional");
  const [language, setLanguage] = useState<Language>("en");
  const [wordCount, setWordCount] = useState(1000);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedContent, setGeneratedContent] =
    useState<BlogGenerationOutput | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleGenerate = async () => {
    if (!topic.trim()) {
      setError("Please enter a topic");
      return;
    }

    setIsGenerating(true);
    setError(null);

    try {
      const input: BlogGenerationInput = {
        topic: topic.trim(),
        keywords: keywords
          .split(",")
          .map((k) => k.trim())
          .filter(Boolean),
        tone,
        language,
        wordCount,
      };

      const response = await fetch(
        "/api/staff/dashboard/social/ai/blog/generate",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(input),
        },
      );

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to generate blog post");
      }

      setGeneratedContent(data.data);
      onGenerated?.(data.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setIsGenerating(false);
    }
  };

  const handleRegenerate = () => {
    handleGenerate();
  };

  const handleSave = () => {
    if (generatedContent) {
      onSave?.(generatedContent);
    }
  };

  const handleCopyToClipboard = async () => {
    if (!generatedContent) return;
    try {
      await navigator.clipboard.writeText(generatedContent.content);
      // Could add toast notification here
    } catch {
      setError("Failed to copy to clipboard");
    }
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
          AI Blog Generator
        </h2>
        <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
          Generate SEO-optimized blog posts using AI
        </p>
      </div>

      {/* Form */}
      <div className="p-6 space-y-4">
        {/* Topic */}
        <div>
          <label
            htmlFor="topic"
            className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
          >
            Topic *
          </label>
          <input
            id="topic"
            type="text"
            value={topic}
            onChange={(e) => setTopic(e.target.value)}
            placeholder="e.g., How AI is transforming appointment scheduling"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
          />
        </div>

        {/* Keywords */}
        <div>
          <label
            htmlFor="keywords"
            className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
          >
            Keywords (comma-separated)
          </label>
          <input
            id="keywords"
            type="text"
            value={keywords}
            onChange={(e) => setKeywords(e.target.value)}
            placeholder="e.g., AI scheduling, automation, GCC business"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
          />
        </div>

        {/* Tone and Language */}
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label
              htmlFor="tone"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
            >
              Tone
            </label>
            <select
              id="tone"
              value={tone}
              onChange={(e) => setTone(e.target.value as Tone)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
            >
              <option value="professional">Professional</option>
              <option value="casual">Casual</option>
              <option value="informative">Informative</option>
            </select>
          </div>

          <div>
            <label
              htmlFor="language"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
            >
              Language
            </label>
            <select
              id="language"
              value={language}
              onChange={(e) => setLanguage(e.target.value as Language)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
            >
              <option value="en">English</option>
              <option value="ar">Arabic</option>
            </select>
          </div>
        </div>

        {/* Word Count Slider */}
        <div>
          <label
            htmlFor="wordCount"
            className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
          >
            Target Word Count: {wordCount}
          </label>
          <input
            id="wordCount"
            type="range"
            min={300}
            max={2000}
            step={100}
            value={wordCount}
            onChange={(e) => setWordCount(parseInt(e.target.value))}
            className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700"
          />
          <div className="flex justify-between text-xs text-gray-500 mt-1">
            <span>300</span>
            <span>2000</span>
          </div>
        </div>

        {/* Error Message */}
        {error && (
          <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
            <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
          </div>
        )}

        {/* Generate Button */}
        <button
          onClick={handleGenerate}
          disabled={isGenerating || !topic.trim()}
          className="w-full py-2 px-4 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-300 text-white font-medium rounded-md transition-colors"
        >
          {isGenerating ? (
            <span className="flex items-center justify-center gap-2">
              <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                  fill="none"
                />
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                />
              </svg>
              Generating...
            </span>
          ) : (
            "Generate Blog Post"
          )}
        </button>
      </div>

      {/* Preview Section */}
      {generatedContent && (
        <div className="border-t border-gray-200 dark:border-gray-700">
          <div className="px-6 py-4 bg-gray-50 dark:bg-gray-750 flex items-center justify-between">
            <h3 className="font-medium text-gray-900 dark:text-white">
              Generated Content
            </h3>
            <div className="flex gap-2">
              <button
                onClick={handleRegenerate}
                disabled={isGenerating}
                className="px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                Regenerate
              </button>
              <button
                onClick={handleCopyToClipboard}
                className="px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                Copy
              </button>
              <button
                onClick={handleSave}
                className="px-3 py-1.5 text-sm bg-green-600 text-white rounded-md hover:bg-green-700"
              >
                Save Draft
              </button>
            </div>
          </div>

          <div className="p-6 space-y-4">
            {/* Title */}
            <div>
              <h4 className="text-sm font-medium text-gray-500 dark:text-gray-400 mb-1">
                Title
              </h4>
              <p className="text-lg font-semibold text-gray-900 dark:text-white">
                {generatedContent.title}
              </p>
            </div>

            {/* Excerpt */}
            <div>
              <h4 className="text-sm font-medium text-gray-500 dark:text-gray-400 mb-1">
                Excerpt
              </h4>
              <p className="text-gray-700 dark:text-gray-300">
                {generatedContent.excerpt}
              </p>
            </div>

            {/* SEO Preview */}
            <div className="p-4 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-md">
              <h4 className="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">
                SEO Preview
              </h4>
              <div className="text-blue-600 dark:text-blue-400 text-lg font-medium">
                {generatedContent.seo.metaTitle}
              </div>
              <div className="text-green-600 dark:text-green-400 text-sm">
                mawidi.com/blog/{generatedContent.slug}
              </div>
              <div className="text-gray-600 dark:text-gray-400 text-sm mt-1">
                {generatedContent.seo.metaDescription}
              </div>
            </div>

            {/* Tags */}
            <div>
              <h4 className="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">
                Tags
              </h4>
              <div className="flex flex-wrap gap-2">
                {generatedContent.tags.map((tag, index) => (
                  <span
                    key={index}
                    className="px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-sm rounded-md"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            </div>

            {/* Content Preview */}
            <div>
              <h4 className="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">
                Content
              </h4>
              <div className="prose dark:prose-invert max-w-none p-4 bg-gray-50 dark:bg-gray-900 rounded-md max-h-96 overflow-y-auto">
                <pre className="whitespace-pre-wrap text-sm font-sans">
                  {generatedContent.content}
                </pre>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default BlogAIGenerator;
