"use client";

import { useState, useCallback } from "react";
import { Sparkles, Copy, Check, Loader2, RefreshCw } from "lucide-react";
import type {
  SocialPlatform,
  AIGenerateOutput,
} from "@/lib/types/social-media.types";
import { PlatformBadge } from "./PlatformIcon";

interface AIAssistantViewProps {
  isAr: boolean;
}

type GenerateType = "caption" | "hashtags" | "reply" | "rephrase";
type Tone = "professional" | "casual" | "friendly" | "witty";

export default function AIAssistantView({ isAr }: AIAssistantViewProps) {
  const [type, setType] = useState<GenerateType>("caption");
  const [platform, setPlatform] = useState<SocialPlatform>("INSTAGRAM");
  const [topic, setTopic] = useState("");
  const [tone, setTone] = useState<Tone>("professional");
  const [language, setLanguage] = useState<"ar" | "en">(isAr ? "ar" : "en");
  const [originalContent, setOriginalContent] = useState("");
  const [result, setResult] = useState<AIGenerateOutput | null>(null);
  const [loading, setLoading] = useState(false);
  const [copied, setCopied] = useState(false);

  const handleGenerate = useCallback(async () => {
    setLoading(true);
    setResult(null);
    try {
      const res = await fetch("/api/social/ai/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          type,
          platform,
          topic: topic || undefined,
          tone,
          language,
          originalContent: originalContent || undefined,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setResult(json.data);
      }
    } catch {
      // silent
    } finally {
      setLoading(false);
    }
  }, [type, platform, topic, tone, language, originalContent]);

  const handleCopy = useCallback((text: string) => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }, []);

  const typeOptions: {
    value: GenerateType;
    labelEn: string;
    labelAr: string;
  }[] = [
    { value: "caption", labelEn: "Caption", labelAr: "تسمية توضيحية" },
    { value: "hashtags", labelEn: "Hashtags", labelAr: "هاشتاجات" },
    { value: "rephrase", labelEn: "Rephrase", labelAr: "إعادة صياغة" },
    { value: "reply", labelEn: "Reply Draft", labelAr: "مسودة رد" },
  ];

  const toneOptions: { value: Tone; labelEn: string; labelAr: string }[] = [
    { value: "professional", labelEn: "Professional", labelAr: "مهني" },
    { value: "casual", labelEn: "Casual", labelAr: "عادي" },
    { value: "friendly", labelEn: "Friendly", labelAr: "ودي" },
    { value: "witty", labelEn: "Witty", labelAr: "ذكي" },
  ];

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* Input Form */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6">
        <div className="flex items-center gap-2 mb-5">
          <div className="p-2 rounded-xl bg-gradient-to-br from-violet-500 to-purple-600">
            <Sparkles className="h-5 w-5 text-white" />
          </div>
          <h3 className="text-lg font-bold text-slate-900">
            {isAr ? "مساعد الذكاء الاصطناعي" : "AI Assistant"}
          </h3>
        </div>

        <div className="space-y-4">
          {/* Type selector */}
          <div>
            <label className="text-sm font-medium text-slate-700 mb-1.5 block">
              {isAr ? "نوع المحتوى" : "Content Type"}
            </label>
            <div className="flex flex-wrap gap-2">
              {typeOptions.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => setType(opt.value)}
                  className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                    type === opt.value
                      ? "bg-violet-100 text-violet-700 ring-1 ring-violet-300"
                      : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                  }`}
                >
                  {isAr ? opt.labelAr : opt.labelEn}
                </button>
              ))}
            </div>
          </div>

          {/* Platform selector */}
          <div>
            <label className="text-sm font-medium text-slate-700 mb-1.5 block">
              {isAr ? "المنصة" : "Platform"}
            </label>
            <div className="flex gap-2">
              {(["FACEBOOK", "INSTAGRAM"] as SocialPlatform[]).map((p) => (
                <button
                  key={p}
                  onClick={() => setPlatform(p)}
                  className={`transition-all ${platform === p ? "ring-2 ring-violet-400 rounded-lg" : "opacity-60"}`}
                >
                  <PlatformBadge platform={p} />
                </button>
              ))}
            </div>
          </div>

          {/* Topic / Original content */}
          {type === "rephrase" || type === "reply" ? (
            <div>
              <label className="text-sm font-medium text-slate-700 mb-1.5 block">
                {type === "rephrase"
                  ? isAr
                    ? "المحتوى الأصلي"
                    : "Original Content"
                  : isAr
                    ? "سياق المحادثة"
                    : "Conversation Context"}
              </label>
              <textarea
                value={originalContent}
                onChange={(e) => setOriginalContent(e.target.value)}
                rows={4}
                className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-violet-200 resize-none"
                dir={isAr ? "rtl" : "ltr"}
                placeholder={
                  type === "rephrase"
                    ? isAr
                      ? "الصق المحتوى هنا..."
                      : "Paste content here..."
                    : isAr
                      ? "الصق المحادثة هنا..."
                      : "Paste conversation here..."
                }
              />
            </div>
          ) : (
            <div>
              <label className="text-sm font-medium text-slate-700 mb-1.5 block">
                {isAr ? "الموضوع" : "Topic"}
              </label>
              <input
                value={topic}
                onChange={(e) => setTopic(e.target.value)}
                className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-violet-200"
                dir={isAr ? "rtl" : "ltr"}
                placeholder={isAr ? "مثال: عروض رمضان" : "e.g., Ramadan offers"}
              />
            </div>
          )}

          {/* Tone & Language */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-sm font-medium text-slate-700 mb-1.5 block">
                {isAr ? "النبرة" : "Tone"}
              </label>
              <select
                value={tone}
                onChange={(e) => setTone(e.target.value as Tone)}
                className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-violet-200"
              >
                {toneOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {isAr ? opt.labelAr : opt.labelEn}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="text-sm font-medium text-slate-700 mb-1.5 block">
                {isAr ? "اللغة" : "Language"}
              </label>
              <select
                value={language}
                onChange={(e) => setLanguage(e.target.value as "ar" | "en")}
                className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-violet-200"
              >
                <option value="en">English</option>
                <option value="ar">العربية</option>
              </select>
            </div>
          </div>

          {/* Generate button */}
          <button
            onClick={handleGenerate}
            disabled={loading}
            className="w-full py-3 bg-gradient-to-r from-violet-600 to-purple-600 text-white rounded-xl text-sm font-semibold hover:from-violet-700 hover:to-purple-700 disabled:opacity-50 transition-all flex items-center justify-center gap-2"
          >
            {loading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Sparkles className="h-4 w-4" />
            )}
            {isAr ? "إنشاء" : "Generate"}
          </button>
        </div>
      </div>

      {/* Result panel */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6">
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-lg font-bold text-slate-900">
            {isAr ? "النتيجة" : "Result"}
          </h3>
          {result && (
            <button
              onClick={handleGenerate}
              className="p-2 rounded-lg hover:bg-slate-100 transition-colors"
              title={isAr ? "إعادة إنشاء" : "Regenerate"}
            >
              <RefreshCw className="h-4 w-4 text-slate-500" />
            </button>
          )}
        </div>

        {!result && !loading ? (
          <div className="flex flex-col items-center justify-center h-64 text-slate-400">
            <Sparkles className="h-12 w-12 mb-3" />
            <p className="text-sm">
              {isAr
                ? "اضغط على إنشاء لتوليد المحتوى"
                : "Click Generate to create content"}
            </p>
          </div>
        ) : loading ? (
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <Loader2 className="h-8 w-8 animate-spin text-violet-500 mx-auto mb-3" />
              <p className="text-sm text-slate-500">
                {isAr ? "جارٍ الإنشاء..." : "Generating..."}
              </p>
            </div>
          </div>
        ) : result ? (
          <div className="space-y-4">
            {/* Main content */}
            <div className="relative group">
              <div
                className="p-4 bg-slate-50 rounded-xl text-sm text-slate-800 whitespace-pre-wrap"
                dir={language === "ar" ? "rtl" : "ltr"}
              >
                {result.content}
              </div>
              <button
                onClick={() => handleCopy(result.content)}
                className="absolute top-2 right-2 p-1.5 bg-white rounded-lg shadow-sm border border-slate-200 opacity-0 group-hover:opacity-100 transition-opacity"
              >
                {copied ? (
                  <Check className="h-3.5 w-3.5 text-green-500" />
                ) : (
                  <Copy className="h-3.5 w-3.5 text-slate-500" />
                )}
              </button>
            </div>

            {/* Hashtags */}
            {result.hashtags && result.hashtags.length > 0 && (
              <div>
                <p className="text-xs font-medium text-slate-500 mb-2">
                  {isAr ? "هاشتاجات" : "Hashtags"}
                </p>
                <div className="flex flex-wrap gap-1.5">
                  {result.hashtags.map((tag, i) => (
                    <span
                      key={i}
                      className="px-2 py-0.5 bg-violet-50 text-violet-700 text-xs rounded-full cursor-pointer hover:bg-violet-100"
                      onClick={() => handleCopy(tag)}
                    >
                      {tag.startsWith("#") ? tag : `#${tag}`}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {/* Alternatives */}
            {result.alternatives && result.alternatives.length > 0 && (
              <div>
                <p className="text-xs font-medium text-slate-500 mb-2">
                  {isAr ? "بدائل" : "Alternatives"}
                </p>
                <div className="space-y-2">
                  {result.alternatives.map((alt, i) => (
                    <div
                      key={i}
                      className="p-3 bg-slate-50 rounded-lg text-xs text-slate-700 cursor-pointer hover:bg-slate-100 transition-colors"
                      onClick={() => handleCopy(alt)}
                    >
                      {alt}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        ) : null}
      </div>
    </div>
  );
}
