"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Palette,
  Type,
  Image,
  Code,
  Eye,
  Save,
  Loader2,
  Star,
  Copy,
  Check,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

interface ReviewQuestion {
  id: string;
  questionEn: string;
  questionAr: string;
  type: "rating" | "text" | "yesno";
  sortOrder: number;
}

const t = {
  en: {
    title: "Widget Settings",
    branding: "Branding",
    businessName: "Business Name",
    logoUrl: "Logo URL",
    primaryColor: "Primary Color",
    bgColor: "Background Color",
    thankYouMsg: "Thank You Message",
    thankYouPlaceholder: "Thank you for your feedback!",
    showPoweredBy: "Show 'Powered by Mawidi'",
    save: "Save Settings",
    saving: "Saving...",
    saved: "Settings saved!",
    error: "Failed to save settings",
    loadError: "Failed to load settings",
    preview: "Preview",
    embedCode: "Embed Code",
    copyCode: "Copy Code",
    copied: "Copied!",
    previewTitle: "How was your experience?",
    previewSubtitle: "Rate our service",
    submit: "Submit",
  },
  ar: {
    title: "إعدادات الأداة",
    branding: "العلامة التجارية",
    businessName: "اسم النشاط التجاري",
    logoUrl: "رابط الشعار",
    primaryColor: "اللون الرئيسي",
    bgColor: "لون الخلفية",
    thankYouMsg: "رسالة الشكر",
    thankYouPlaceholder: "شكراً لملاحظاتك!",
    showPoweredBy: "إظهار 'مدعوم من Mawidi'",
    save: "حفظ الإعدادات",
    saving: "جاري الحفظ...",
    saved: "تم حفظ الإعدادات!",
    error: "فشل في حفظ الإعدادات",
    loadError: "فشل في تحميل الإعدادات",
    preview: "معاينة",
    embedCode: "كود التضمين",
    copyCode: "نسخ الكود",
    copied: "تم النسخ!",
    previewTitle: "كيف كانت تجربتك؟",
    previewSubtitle: "قيّم خدمتنا",
    submit: "إرسال",
  },
};

interface WidgetSettings {
  businessName: string;
  logoUrl: string;
  primaryColor: string;
  backgroundColor: string;
  thankYouMessage: string;
  showPoweredBy: boolean;
}

interface TestimonialsSettingsProps {
  lang: string;
  userId?: string;
}

export default function TestimonialsSettings({
  lang,
  userId,
}: TestimonialsSettingsProps) {
  const isAr = lang === "ar";
  const labels = t[isAr ? "ar" : "en"];

  const [settings, setSettings] = useState<WidgetSettings>({
    businessName: "",
    logoUrl: "",
    primaryColor: "#10b981",
    backgroundColor: "#ffffff",
    thankYouMessage: "",
    showPoweredBy: true,
  });
  const [defaultBusinessName, setDefaultBusinessName] = useState("");
  const [questions, setQuestions] = useState<ReviewQuestion[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [copied, setCopied] = useState(false);

  const fetchSettings = useCallback(async () => {
    try {
      const [settingsRes, questionsRes] = await Promise.all([
        fetchWithCSRF("/api/dashboard/reviews/widget-settings"),
        fetchWithCSRF("/api/dashboard/reviews/questions"),
      ]);
      if (settingsRes.ok) {
        const data = await settingsRes.json();
        if (data.settings) {
          setSettings(data.settings);
        }
        // Always use the company name from Convex
        if (data.defaultBusinessName) {
          setDefaultBusinessName(data.defaultBusinessName);
          setSettings((prev) => ({ ...prev, businessName: data.defaultBusinessName }));
        }
      }
      if (questionsRes.ok) {
        const data = await questionsRes.json();
        if (data.questions) {
          setQuestions(data.questions);
        }
      }
    } catch {
      setError(labels.loadError);
    } finally {
      setLoading(false);
    }
  }, [labels.loadError]);

  useEffect(() => {
    fetchSettings();
  }, [fetchSettings]);

  const handleSave = async () => {
    setSaving(true);
    setError("");
    setSuccess(false);
    try {
      const res = await fetchWithCSRF(
        "/api/dashboard/reviews/widget-settings",
        {
          method: "PUT",
          body: JSON.stringify(settings),
        },
      );
      if (!res.ok) throw new Error("Failed");
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch {
      setError(labels.error);
    } finally {
      setSaving(false);
    }
  };

  const embedCode = userId
    ? `<iframe src="${typeof window !== "undefined" ? window.location.origin : ""}/${lang}/embed/testimonials/${userId}" width="100%" height="600" frameborder="0" style="border:none;"></iframe>`
    : "";

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

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-6 h-6 animate-spin text-brand-green" />
      </div>
    );
  }

  return (
    <div dir={isAr ? "rtl" : "ltr"} className="space-y-6">
      <h3 className="text-lg font-semibold text-slate-900">{labels.title}</h3>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Settings Form */}
        <div className="space-y-4">
          <div className="flex items-center gap-2 text-sm text-slate-500 mb-2">
            <Palette className="w-4 h-4" />
            {labels.branding}
          </div>

          <div>
            <label className="block text-sm text-slate-500 mb-1">
              <Type className="w-3.5 h-3.5 inline me-1" />
              {labels.businessName}
            </label>
            <input
              value={settings.businessName}
              placeholder={defaultBusinessName}
              onChange={(e) =>
                setSettings({ ...settings, businessName: e.target.value })
              }
              className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm text-slate-500 mb-1">
              <Image className="w-3.5 h-3.5 inline me-1" />
              {labels.logoUrl}
            </label>
            <input
              value={settings.logoUrl}
              onChange={(e) =>
                setSettings({ ...settings, logoUrl: e.target.value })
              }
              placeholder="https://..."
              className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm text-slate-500 mb-1">
                {labels.primaryColor}
              </label>
              <div className="flex items-center gap-2">
                <input
                  type="color"
                  value={settings.primaryColor}
                  onChange={(e) =>
                    setSettings({ ...settings, primaryColor: e.target.value })
                  }
                  className="w-8 h-8 rounded border border-slate-300 cursor-pointer bg-transparent"
                />
                <input
                  value={settings.primaryColor}
                  onChange={(e) =>
                    setSettings({ ...settings, primaryColor: e.target.value })
                  }
                  className="flex-1 border border-slate-300 rounded-lg px-3 py-1.5 text-slate-900 text-sm"
                />
              </div>
            </div>
            <div>
              <label className="block text-sm text-slate-500 mb-1">
                {labels.bgColor}
              </label>
              <div className="flex items-center gap-2">
                <input
                  type="color"
                  value={settings.backgroundColor}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      backgroundColor: e.target.value,
                    })
                  }
                  className="w-8 h-8 rounded border border-slate-300 cursor-pointer bg-transparent"
                />
                <input
                  value={settings.backgroundColor}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      backgroundColor: e.target.value,
                    })
                  }
                  className="flex-1 border border-slate-300 rounded-lg px-3 py-1.5 text-slate-900 text-sm"
                />
              </div>
            </div>
          </div>

          <div>
            <label className="block text-sm text-slate-500 mb-1">
              {labels.thankYouMsg}
            </label>
            <textarea
              value={settings.thankYouMessage}
              onChange={(e) =>
                setSettings({ ...settings, thankYouMessage: e.target.value })
              }
              placeholder={labels.thankYouPlaceholder}
              rows={3}
              className="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-900 text-sm resize-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={settings.showPoweredBy}
              onChange={(e) =>
                setSettings({ ...settings, showPoweredBy: e.target.checked })
              }
              className="rounded border-slate-300 text-brand-green focus:ring-blue-500"
            />
            <span className="text-sm text-slate-600">
              {labels.showPoweredBy}
            </span>
          </label>

          {error && (
            <p className="text-sm text-red-600 bg-red-50 px-3 py-2 rounded-lg">
              {error}
            </p>
          )}
          {success && (
            <p className="text-sm text-green-600 bg-green-50 px-3 py-2 rounded-lg">
              {labels.saved}
            </p>
          )}

          <button
            onClick={handleSave}
            disabled={saving}
            className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-green/90 disabled:opacity-50 text-sm"
          >
            {saving ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Save className="w-4 h-4" />
            )}
            {saving ? labels.saving : labels.save}
          </button>
        </div>

        {/* Live Preview */}
        <div className="space-y-4">
          <div className="flex items-center gap-2 text-sm text-slate-500 mb-2">
            <Eye className="w-4 h-4" />
            {labels.preview}
          </div>

          <div
            className="rounded-xl border border-slate-200 overflow-hidden"
            style={{ backgroundColor: settings.backgroundColor }}
          >
            <div className="p-6 text-center">
              {settings.logoUrl && (
                <img
                  src={settings.logoUrl}
                  alt={settings.businessName}
                  className="h-10 mx-auto mb-4 object-contain"
                />
              )}
              <h4
                className="text-lg font-semibold mb-1"
                style={{ color: settings.primaryColor }}
              >
                {settings.businessName || defaultBusinessName || labels.previewTitle}
              </h4>
              <p className="text-sm text-gray-500 mb-4">
                {labels.previewSubtitle}
              </p>
              <div className="flex justify-center gap-1 mb-4">
                {[1, 2, 3, 4, 5].map((s) => (
                  <Star
                    key={s}
                    className="w-8 h-8"
                    style={{
                      color: s <= 4 ? settings.primaryColor : "#d1d5db",
                      fill: s <= 4 ? settings.primaryColor : "none",
                    }}
                  />
                ))}
              </div>
              {questions.length > 0 ? (
                <div className="space-y-3 mb-4 text-left">
                  {questions.map((q) => (
                    <div
                      key={q.id}
                      className="border border-slate-200 rounded-lg p-3 bg-white"
                    >
                      <p className="text-xs font-medium text-slate-700 mb-2">
                        {isAr
                          ? q.questionAr || q.questionEn
                          : q.questionEn || q.questionAr}
                      </p>
                      {q.type === "rating" && (
                        <div className="flex gap-1">
                          {[1, 2, 3, 4, 5].map((s) => (
                            <Star
                              key={s}
                              className="w-5 h-5"
                              style={{
                                color:
                                  s <= 3 ? settings.primaryColor : "#d1d5db",
                                fill: s <= 3 ? settings.primaryColor : "none",
                              }}
                            />
                          ))}
                        </div>
                      )}
                      {q.type === "yesno" && (
                        <div className="flex gap-2">
                          <span
                            className="px-3 py-1 rounded-full text-xs text-white"
                            style={{ backgroundColor: settings.primaryColor }}
                          >
                            {isAr ? "نعم" : "Yes"}
                          </span>
                          <span className="px-3 py-1 rounded-full text-xs border border-slate-300 text-slate-500">
                            {isAr ? "لا" : "No"}
                          </span>
                        </div>
                      )}
                      {q.type === "text" && (
                        <div className="h-8 bg-slate-100 rounded border border-slate-200" />
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="h-20 bg-gray-100 rounded-lg mb-4" />
              )}
              <div
                className="inline-block px-6 py-2 rounded-lg text-white text-sm font-medium"
                style={{ backgroundColor: settings.primaryColor }}
              >
                {labels.submit}
              </div>
              {settings.showPoweredBy && (
                <p className="text-xs text-slate-400 mt-4">Powered by Mawidi</p>
              )}
            </div>
          </div>

          {/* Embed Code */}
          {userId && (
            <div>
              <div className="flex items-center gap-2 text-sm text-slate-500 mb-2">
                <Code className="w-4 h-4" />
                {labels.embedCode}
              </div>
              <div className="relative">
                <pre className="bg-slate-50 border border-slate-200 rounded-lg p-3 text-xs text-slate-600 overflow-x-auto">
                  {embedCode}
                </pre>
                <button
                  onClick={handleCopy}
                  className="absolute top-2 end-2 flex items-center gap-1 px-2 py-1 bg-slate-200 text-slate-600 rounded text-xs hover:bg-slate-300"
                >
                  {copied ? (
                    <>
                      <Check className="w-3 h-3" />
                      {labels.copied}
                    </>
                  ) : (
                    <>
                      <Copy className="w-3 h-3" />
                      {labels.copyCode}
                    </>
                  )}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
