"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import {
  Phone,
  Settings,
  Pause,
  Loader2,
  CheckCircle2,
  AlertCircle,
  Volume2,
  Globe,
  Clock,
  Mic,
  Trash2,
  RefreshCw,
  Sparkles,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import type { VoiceAgentConfig } from "@/lib/types/voice-agent.types";
import { getCSRFToken } from "@/lib/csrf-client";

interface VoiceAgentPanelProps {
  lang: Lang;
}

interface VoiceAgentData {
  agentId: string | null;
  config: VoiceAgentConfig | null;
}

export default function VoiceAgentPanel({ lang }: VoiceAgentPanelProps) {
  const isAr = lang === "ar";
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [provisioning, setProvisioning] = useState(false);
  const [agentData, setAgentData] = useState<VoiceAgentData | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // Preview state
  const [isPreviewPlaying, setIsPreviewPlaying] = useState(false);
  const [isPreviewLoading, setIsPreviewLoading] = useState(false);
  const [previewError, setPreviewError] = useState<string | null>(null);
  const audioRef = useRef<HTMLAudioElement | null>(null);

  // Edit form state
  const [editMode, setEditMode] = useState(false);
  const [formConfig, setFormConfig] = useState<VoiceAgentConfig>({
    language: "ar",
    voiceTone: "professional",
    useKnowledgeBase: true,
    greetingMessage: {
      ar: "",
      en: "",
    },
    escalationKeywords: [],
  });

  const t = {
    title: isAr ? "الوكيل الصوتي بالذكاء الاصطناعي" : "AI Voice Agent",
    subtitle: isAr
      ? "أتمتة المكالمات الهاتفية باستخدام موظف استقبال صوتي ذكي"
      : "Automate phone calls with an intelligent voice receptionist",
    noAgent: isAr ? "لم يتم إعداد وكيل صوتي بعد" : "No voice agent set up yet",
    noAgentDesc: isAr
      ? "قم بإنشاء وكيل صوتي بالذكاء الاصطناعي للرد على المكالمات وحجز المواعيد تلقائياً"
      : "Create an AI voice agent to answer calls and book appointments automatically",
    provisionBtn: isAr ? "إنشاء وكيل صوتي" : "Create Voice Agent",
    provisioning: isAr ? "جارٍ الإنشاء..." : "Creating...",
    status: isAr ? "الحالة" : "Status",
    active: isAr ? "نشط" : "Active",
    inactive: isAr ? "غير نشط" : "Inactive",
    language: isAr ? "اللغة" : "Language",
    arabic: isAr ? "العربية" : "Arabic",
    english: isAr ? "الإنجليزية" : "English",
    both: isAr ? "كلاهما" : "Both",
    voiceTone: isAr ? "نبرة الصوت" : "Voice Tone",
    professional: isAr ? "احترافي" : "Professional",
    friendly: isAr ? "ودود" : "Friendly",
    custom: isAr ? "مخصص" : "Custom",
    greeting: isAr ? "رسالة الترحيب" : "Greeting Message",
    greetingAr: isAr ? "الترحيب بالعربية" : "Arabic Greeting",
    greetingEn: isAr ? "الترحيب بالإنجليزية" : "English Greeting",
    greetingPlaceholder: isAr
      ? "مرحباً! كيف يمكنني مساعدتك اليوم؟"
      : "Hello! How can I help you today?",
    knowledgeBase: isAr ? "استخدام قاعدة المعرفة" : "Use Knowledge Base",
    knowledgeBaseDesc: isAr
      ? "يستخدم الوكيل قاعدة المعرفة للإجابة على الأسئلة"
      : "Agent uses your knowledge base to answer questions",
    escalationKeywords: isAr ? "كلمات التصعيد" : "Escalation Keywords",
    escalationDesc: isAr
      ? "كلمات تؤدي إلى تحويل المكالمة لموظف بشري"
      : "Words that trigger transfer to a human agent",
    previewVoice: isAr ? "معاينة الصوت" : "Preview Voice",
    stopPreview: isAr ? "إيقاف" : "Stop",
    edit: isAr ? "تعديل" : "Edit",
    cancel: isAr ? "إلغاء" : "Cancel",
    save: isAr ? "حفظ" : "Save",
    saving: isAr ? "جارٍ الحفظ..." : "Saving...",
    delete: isAr ? "حذف الوكيل" : "Delete Agent",
    deleteConfirm: isAr
      ? "هل أنت متأكد من حذف الوكيل الصوتي؟ لا يمكن التراجع عن هذا الإجراء."
      : "Are you sure you want to delete the voice agent? This cannot be undone.",
    refresh: isAr ? "تحديث" : "Refresh",
    poweredBy: isAr ? "مدعوم من ElevenLabs" : "Powered by ElevenLabs",
    featureHighlight: isAr ? "ميزة مميزة" : "Premium Feature",
    featureDesc: isAr
      ? "متاحة في باقة الأعمال والأعلى"
      : "Available on Business plan and above",
  };

  // Fetch voice agent config
  const fetchAgentConfig = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const csrfToken = await getCSRFToken();
      const response = await fetch("/api/voice-agent/config", {
        method: "GET",
        headers: {
          ...(csrfToken ? { "x-csrf-token": csrfToken } : {}),
        },
      });

      if (response.status === 404) {
        // No agent configured yet
        setAgentData({ agentId: null, config: null });
        return;
      }

      if (!response.ok) {
        throw new Error("Failed to fetch voice agent config");
      }

      const data = await response.json();
      setAgentData({
        agentId: data.agentId,
        config: data.config as VoiceAgentConfig,
      });

      // Set form state from fetched config
      if (data.config) {
        setFormConfig(data.config);
      }
    } catch (err) {
      console.error("Error fetching voice agent config:", err);
      setError(
        isAr ? "فشل في تحميل بيانات الوكيل" : "Failed to load agent data",
      );
    } finally {
      setLoading(false);
    }
  }, [isAr]);

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

  // Provision new agent
  const handleProvision = async () => {
    try {
      setProvisioning(true);
      setError(null);

      const csrfToken = await getCSRFToken();
      const response = await fetch("/api/voice-agent/provision", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...(csrfToken ? { "x-csrf-token": csrfToken } : {}),
        },
        body: JSON.stringify({
          language: formConfig.language,
          voiceTone: formConfig.voiceTone,
          useKnowledgeBase: formConfig.useKnowledgeBase,
          greetingMessage: formConfig.greetingMessage,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || "Failed to provision voice agent");
      }

      const data = await response.json();
      // Provision endpoint returns nested data structure
      setAgentData({
        agentId: data.data.agentId,
        config: data.data.config as VoiceAgentConfig,
      });
      setSuccessMessage(
        isAr
          ? "تم إنشاء الوكيل الصوتي بنجاح!"
          : "Voice agent created successfully!",
      );
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err) {
      console.error("Error provisioning voice agent:", err);
      setError(
        err instanceof Error ? err.message : "Failed to create voice agent",
      );
    } finally {
      setProvisioning(false);
    }
  };

  // Update config
  const handleSaveConfig = async () => {
    try {
      setSaving(true);
      setError(null);

      const csrfToken = await getCSRFToken();
      const response = await fetch("/api/voice-agent/config", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          ...(csrfToken ? { "x-csrf-token": csrfToken } : {}),
        },
        body: JSON.stringify(formConfig),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || "Failed to update configuration");
      }

      const data = await response.json();
      setAgentData({
        agentId: data.data.agentId,
        config: data.data.config as VoiceAgentConfig,
      });
      setEditMode(false);
      setSuccessMessage(
        isAr ? "تم حفظ الإعدادات بنجاح!" : "Settings saved successfully!",
      );
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err) {
      console.error("Error updating voice agent config:", err);
      setError(
        err instanceof Error ? err.message : "Failed to update configuration",
      );
    } finally {
      setSaving(false);
    }
  };

  // Delete agent
  const handleDelete = async () => {
    if (!confirm(t.deleteConfirm)) return;

    try {
      setLoading(true);
      setError(null);

      const csrfToken = await getCSRFToken();
      const response = await fetch("/api/voice-agent/config", {
        method: "DELETE",
        headers: {
          ...(csrfToken ? { "x-csrf-token": csrfToken } : {}),
        },
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || "Failed to delete voice agent");
      }

      setAgentData({ agentId: null, config: null });
      setSuccessMessage(
        isAr ? "تم حذف الوكيل بنجاح" : "Agent deleted successfully",
      );
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err) {
      console.error("Error deleting voice agent:", err);
      setError(err instanceof Error ? err.message : "Failed to delete agent");
    } finally {
      setLoading(false);
    }
  };

  // Preview voice
  const handlePreview = async () => {
    if (isPreviewPlaying && audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
      setIsPreviewPlaying(false);
      return;
    }

    setIsPreviewLoading(true);
    setPreviewError(null);

    try {
      const previewLang = formConfig.language === "en" ? "en" : "ar";
      const previewText =
        (previewLang === "ar"
          ? formConfig.greetingMessage?.ar
          : formConfig.greetingMessage?.en) ||
        (previewLang === "ar"
          ? "مرحباً! هذا مركز مويدي الطبي. كيف يمكنني مساعدتك اليوم؟"
          : "Hello! This is Mawidi Medical Center. How can I help you today?");

      const csrfToken = await getCSRFToken();
      const response = await fetch("/api/voice-agent/preview", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...(csrfToken ? { "x-csrf-token": csrfToken } : {}),
        },
        body: JSON.stringify({
          text: previewText,
          language: previewLang,
          voiceTone: formConfig.voiceTone,
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to generate voice preview");
      }

      const audioBlob = await response.blob();
      const audioUrl = URL.createObjectURL(audioBlob);

      if (audioRef.current) {
        audioRef.current.pause();
        URL.revokeObjectURL(audioRef.current.src);
      }

      const audio = new Audio(audioUrl);
      audioRef.current = audio;

      audio.onended = () => {
        setIsPreviewPlaying(false);
        URL.revokeObjectURL(audioUrl);
      };

      audio.onerror = () => {
        setIsPreviewPlaying(false);
        setPreviewError(isAr ? "فشل تشغيل الصوت" : "Failed to play audio");
        URL.revokeObjectURL(audioUrl);
      };

      await audio.play();
      setIsPreviewPlaying(true);
    } catch (err) {
      console.error("Voice preview error:", err);
      setPreviewError(
        isAr ? "فشل في إنشاء معاينة الصوت" : "Failed to generate voice preview",
      );
    } finally {
      setIsPreviewLoading(false);
    }
  };

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

  // No agent provisioned yet
  if (!agentData?.agentId) {
    return (
      <div className="space-y-8">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
            <p className="text-slate-500 mt-1">{t.subtitle}</p>
          </div>
          <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 text-blue-700 text-sm font-medium">
            <Sparkles className="w-4 h-4" />
            {t.featureHighlight}
          </span>
        </div>

        {/* Empty State */}
        <div className="bg-white rounded-2xl border border-slate-200 p-12 text-center">
          <div className="inline-flex items-center justify-center w-20 h-20 rounded-2xl bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg shadow-blue-500/25 mb-6">
            <Phone className="w-10 h-10 text-white" />
          </div>
          <h3 className="text-xl font-semibold text-slate-900 mb-2">
            {t.noAgent}
          </h3>
          <p className="text-slate-500 mb-8 max-w-md mx-auto">
            {t.noAgentDesc}
          </p>

          {error && (
            <div className="mb-6 p-4 rounded-xl bg-red-50 border border-red-200 text-red-700 flex items-center gap-3 max-w-md mx-auto">
              <AlertCircle className="w-5 h-5 flex-shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {/* Quick Setup Form */}
          <div className="max-w-md mx-auto space-y-4 mb-8">
            {/* Language Selection */}
            <div className="text-left">
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {t.language}
              </label>
              <div className="grid grid-cols-3 gap-2">
                {(["ar", "en", "both"] as const).map((value) => (
                  <button
                    key={value}
                    onClick={() =>
                      setFormConfig((prev) => ({ ...prev, language: value }))
                    }
                    className={`p-3 rounded-xl border-2 text-sm font-medium transition-all ${
                      formConfig.language === value
                        ? "border-brand-green bg-brand-green/10 text-brand-green"
                        : "border-slate-200 text-slate-600 hover:border-slate-300"
                    }`}
                  >
                    {value === "ar"
                      ? t.arabic
                      : value === "en"
                        ? t.english
                        : t.both}
                  </button>
                ))}
              </div>
            </div>

            {/* Voice Tone */}
            <div className="text-left">
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {t.voiceTone}
              </label>
              <div className="grid grid-cols-3 gap-2">
                {(["professional", "friendly", "custom"] as const).map(
                  (value) => (
                    <button
                      key={value}
                      onClick={() =>
                        setFormConfig((prev) => ({ ...prev, voiceTone: value }))
                      }
                      className={`p-3 rounded-xl border-2 text-sm font-medium transition-all ${
                        formConfig.voiceTone === value
                          ? "border-brand-green bg-brand-green/10 text-brand-green"
                          : "border-slate-200 text-slate-600 hover:border-slate-300"
                      }`}
                    >
                      {value === "professional"
                        ? t.professional
                        : value === "friendly"
                          ? t.friendly
                          : t.custom}
                    </button>
                  ),
                )}
              </div>
            </div>
          </div>

          <button
            onClick={handleProvision}
            disabled={provisioning}
            className="inline-flex items-center gap-2 px-8 py-4 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-white font-semibold shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 hover:-translate-y-0.5 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {provisioning ? (
              <>
                <Loader2 className="w-5 h-5 animate-spin" />
                {t.provisioning}
              </>
            ) : (
              <>
                <Phone className="w-5 h-5" />
                {t.provisionBtn}
              </>
            )}
          </button>

          <p className="mt-6 text-xs text-slate-400">{t.poweredBy}</p>
        </div>
      </div>
    );
  }

  // Agent configured - show management UI
  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
          <p className="text-slate-500 mt-1">{t.subtitle}</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={fetchAgentConfig}
            className="p-2 rounded-lg text-slate-500 hover:text-slate-700 hover:bg-slate-100 transition-colors"
            title={t.refresh}
          >
            <RefreshCw className="w-5 h-5" />
          </button>
          {!editMode && (
            <button
              onClick={() => setEditMode(true)}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-100 text-slate-700 font-medium hover:bg-slate-200 transition-colors"
            >
              <Settings className="w-4 h-4" />
              {t.edit}
            </button>
          )}
        </div>
      </div>

      {/* Status Messages */}
      {successMessage && (
        <div className="p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-700 flex items-center gap-3">
          <CheckCircle2 className="w-5 h-5 flex-shrink-0" />
          <span>{successMessage}</span>
        </div>
      )}

      {error && (
        <div className="p-4 rounded-xl bg-red-50 border border-red-200 text-red-700 flex items-center gap-3">
          <AlertCircle className="w-5 h-5 flex-shrink-0" />
          <span>{error}</span>
        </div>
      )}

      {/* Status Card */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-emerald-500 to-green-600 flex items-center justify-center shadow-lg shadow-emerald-500/25">
              <Phone className="w-6 h-6 text-white" />
            </div>
            <div>
              <h3 className="font-semibold text-slate-900">{t.status}</h3>
              <div className="flex items-center gap-2 mt-0.5">
                <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                <span className="text-sm text-emerald-600 font-medium">
                  {t.active}
                </span>
              </div>
            </div>
          </div>
          <span className="text-xs text-slate-400">{t.poweredBy}</span>
        </div>

        {/* Quick Stats */}
        <div className="grid grid-cols-3 gap-4">
          <div className="p-4 rounded-xl bg-slate-50">
            <div className="flex items-center gap-2 text-slate-500 mb-1">
              <Globe className="w-4 h-4" />
              <span className="text-xs font-medium">{t.language}</span>
            </div>
            <p className="font-semibold text-slate-900">
              {agentData.config?.language === "ar"
                ? t.arabic
                : agentData.config?.language === "en"
                  ? t.english
                  : t.both}
            </p>
          </div>
          <div className="p-4 rounded-xl bg-slate-50">
            <div className="flex items-center gap-2 text-slate-500 mb-1">
              <Mic className="w-4 h-4" />
              <span className="text-xs font-medium">{t.voiceTone}</span>
            </div>
            <p className="font-semibold text-slate-900">
              {agentData.config?.voiceTone === "professional"
                ? t.professional
                : agentData.config?.voiceTone === "friendly"
                  ? t.friendly
                  : t.custom}
            </p>
          </div>
          <div className="p-4 rounded-xl bg-slate-50">
            <div className="flex items-center gap-2 text-slate-500 mb-1">
              <Clock className="w-4 h-4" />
              <span className="text-xs font-medium">{t.knowledgeBase}</span>
            </div>
            <p className="font-semibold text-slate-900">
              {agentData.config?.useKnowledgeBase
                ? isAr
                  ? "مفعّل"
                  : "Enabled"
                : isAr
                  ? "معطّل"
                  : "Disabled"}
            </p>
          </div>
        </div>
      </div>

      {/* Configuration / Edit Form */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6">
        <h3 className="text-lg font-semibold text-slate-900 mb-6">
          {editMode
            ? isAr
              ? "تعديل الإعدادات"
              : "Edit Settings"
            : isAr
              ? "الإعدادات الحالية"
              : "Current Settings"}
        </h3>

        <div className="space-y-6">
          {/* Language */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-3">
              {t.language}
            </label>
            <div className="grid grid-cols-3 gap-3">
              {(["ar", "en", "both"] as const).map((value) => (
                <button
                  key={value}
                  onClick={() =>
                    editMode &&
                    setFormConfig((prev) => ({ ...prev, language: value }))
                  }
                  disabled={!editMode}
                  className={`p-4 rounded-xl border-2 text-sm font-semibold transition-all ${
                    (editMode
                      ? formConfig.language
                      : agentData.config?.language) === value
                      ? "border-brand-green bg-brand-green/10 text-brand-green"
                      : "border-slate-200 text-slate-600"
                  } ${editMode ? "hover:border-slate-300 cursor-pointer" : "cursor-default"}`}
                >
                  {value === "ar"
                    ? t.arabic
                    : value === "en"
                      ? t.english
                      : t.both}
                </button>
              ))}
            </div>
          </div>

          {/* Voice Tone */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-3">
              {t.voiceTone}
            </label>
            <div className="grid grid-cols-3 gap-3">
              {(["professional", "friendly", "custom"] as const).map(
                (value) => (
                  <button
                    key={value}
                    onClick={() =>
                      editMode &&
                      setFormConfig((prev) => ({ ...prev, voiceTone: value }))
                    }
                    disabled={!editMode}
                    className={`p-4 rounded-xl border-2 text-sm font-semibold transition-all ${
                      (editMode
                        ? formConfig.voiceTone
                        : agentData.config?.voiceTone) === value
                        ? "border-brand-green bg-brand-green/10 text-brand-green"
                        : "border-slate-200 text-slate-600"
                    } ${editMode ? "hover:border-slate-300 cursor-pointer" : "cursor-default"}`}
                  >
                    {value === "professional"
                      ? t.professional
                      : value === "friendly"
                        ? t.friendly
                        : t.custom}
                  </button>
                ),
              )}
            </div>
          </div>

          {/* Greeting Messages */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-3">
              {t.greeting}
            </label>
            <div className="space-y-3">
              <div>
                <label className="block text-xs text-slate-500 mb-1">
                  {t.greetingAr}
                </label>
                <textarea
                  value={
                    editMode
                      ? formConfig.greetingMessage?.ar || ""
                      : agentData.config?.greetingMessage?.ar || ""
                  }
                  onChange={(e) =>
                    setFormConfig((prev) => ({
                      ...prev,
                      greetingMessage: {
                        ...prev.greetingMessage,
                        ar: e.target.value,
                      },
                    }))
                  }
                  disabled={!editMode}
                  placeholder={t.greetingPlaceholder}
                  rows={2}
                  className="w-full px-4 py-3 rounded-xl border border-slate-200 text-slate-900 placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none transition-all resize-none disabled:bg-slate-50 disabled:text-slate-600"
                  dir="rtl"
                />
              </div>
              <div>
                <label className="block text-xs text-slate-500 mb-1">
                  {t.greetingEn}
                </label>
                <textarea
                  value={
                    editMode
                      ? formConfig.greetingMessage?.en || ""
                      : agentData.config?.greetingMessage?.en || ""
                  }
                  onChange={(e) =>
                    setFormConfig((prev) => ({
                      ...prev,
                      greetingMessage: {
                        ...prev.greetingMessage,
                        en: e.target.value,
                      },
                    }))
                  }
                  disabled={!editMode}
                  placeholder="Hello! How can I help you today?"
                  rows={2}
                  className="w-full px-4 py-3 rounded-xl border border-slate-200 text-slate-900 placeholder-slate-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 focus:outline-none transition-all resize-none disabled:bg-slate-50 disabled:text-slate-600"
                />
              </div>
            </div>
          </div>

          {/* Knowledge Base Toggle */}
          <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
            <div>
              <p className="font-medium text-slate-900">{t.knowledgeBase}</p>
              <p className="text-sm text-slate-500">{t.knowledgeBaseDesc}</p>
            </div>
            <button
              onClick={() =>
                editMode &&
                setFormConfig((prev) => ({
                  ...prev,
                  useKnowledgeBase: !prev.useKnowledgeBase,
                }))
              }
              disabled={!editMode}
              className={`relative w-12 h-7 rounded-full transition-colors ${
                (
                  editMode
                    ? formConfig.useKnowledgeBase
                    : agentData.config?.useKnowledgeBase
                )
                  ? "bg-brand-green"
                  : "bg-slate-300"
              } ${editMode ? "cursor-pointer" : "cursor-default"}`}
            >
              <span
                className={`absolute top-1 w-5 h-5 rounded-full bg-white shadow-sm transition-transform ${
                  (
                    editMode
                      ? formConfig.useKnowledgeBase
                      : agentData.config?.useKnowledgeBase
                  )
                    ? isAr
                      ? "right-1"
                      : "left-6"
                    : isAr
                      ? "right-6"
                      : "left-1"
                }`}
              />
            </button>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex items-center justify-between mt-8 pt-6 border-t border-slate-100">
          <div className="flex items-center gap-3">
            {/* Preview Voice Button */}
            <button
              onClick={handlePreview}
              disabled={isPreviewLoading}
              className={`inline-flex items-center gap-2 px-4 py-2.5 rounded-lg border-2 font-medium transition-all ${
                isPreviewPlaying
                  ? "border-red-500 text-red-500 hover:bg-red-50"
                  : "border-blue-500 text-blue-500 hover:bg-blue-50"
              } disabled:opacity-50 disabled:cursor-not-allowed`}
            >
              {isPreviewLoading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : isPreviewPlaying ? (
                <Pause className="w-4 h-4" />
              ) : (
                <Volume2 className="w-4 h-4" />
              )}
              {isPreviewPlaying ? t.stopPreview : t.previewVoice}
            </button>
            {previewError && (
              <span className="text-sm text-red-500">{previewError}</span>
            )}
          </div>

          <div className="flex items-center gap-3">
            {editMode ? (
              <>
                <button
                  onClick={() => {
                    setEditMode(false);
                    setFormConfig(agentData.config || formConfig);
                  }}
                  className="px-4 py-2.5 rounded-lg text-slate-600 font-medium hover:bg-slate-100 transition-colors"
                >
                  {t.cancel}
                </button>
                <button
                  onClick={handleSaveConfig}
                  disabled={saving}
                  className="inline-flex items-center gap-2 px-6 py-2.5 rounded-lg bg-brand-green text-white font-medium hover:bg-emerald-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {saving ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      {t.saving}
                    </>
                  ) : (
                    <>
                      <CheckCircle2 className="w-4 h-4" />
                      {t.save}
                    </>
                  )}
                </button>
              </>
            ) : (
              <button
                onClick={handleDelete}
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg text-red-600 font-medium hover:bg-red-50 transition-colors"
              >
                <Trash2 className="w-4 h-4" />
                {t.delete}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
