"use client";

import { useState } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  Check,
  ChevronRight,
  ChevronLeft,
  Loader2,
  Mic,
  MessageSquare,
  Calendar,
  Brain,
  Sparkles,
  Phone,
  X,
} from "lucide-react";

interface VoiceAgentSetupWizardProps {
  lang: Lang;
  onComplete: () => void;
}

type WizardStep = 1 | 2 | 3 | 4 | 5;

const FEATURES = [
  {
    icon: Mic,
    en: "Natural voice conversations in Arabic & English",
    ar: "محادثات صوتية طبيعية بالعربية والإنجليزية",
  },
  {
    icon: Calendar,
    en: "Automatic appointment booking & management",
    ar: "حجز وإدارة المواعيد تلقائياً",
  },
  {
    icon: MessageSquare,
    en: "24/7 customer support with instant responses",
    ar: "دعم العملاء على مدار الساعة مع ردود فورية",
  },
  {
    icon: Brain,
    en: "AI-powered knowledge base for accurate answers",
    ar: "قاعدة معرفة ذكية لإجابات دقيقة",
  },
];

const VOICE_TONES = [
  {
    value: "professional",
    en: "Professional",
    ar: "احترافي",
    desc_en: "Formal and business-appropriate",
    desc_ar: "رسمي ومناسب للأعمال",
  },
  {
    value: "friendly",
    en: "Friendly",
    ar: "ودود",
    desc_en: "Warm and approachable",
    desc_ar: "دافئ وقريب",
  },
  {
    value: "custom",
    en: "Casual",
    ar: "عفوي",
    desc_en: "Relaxed and conversational",
    desc_ar: "مريح وحواري",
  },
];

const LANGUAGES = [
  { value: "en", en: "English", ar: "الإنجليزية" },
  { value: "ar", en: "Arabic", ar: "العربية" },
  {
    value: "both",
    en: "Both (Arabic & English)",
    ar: "كلاهما (عربي وإنجليزي)",
  },
];

export default function VoiceAgentSetupWizard({
  lang,
  onComplete,
}: VoiceAgentSetupWizardProps) {
  const isAr = lang === "ar";
  const [step, setStep] = useState<WizardStep>(1);
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [errorType, setErrorType] = useState<string | null>(null);
  const [toolsWarning, setToolsWarning] = useState<string | null>(null);

  // Form state
  const [agentName, setAgentName] = useState("");
  const [language, setLanguage] = useState("both");
  const [voiceTone, setVoiceTone] = useState("professional");
  const [greetingEn, setGreetingEn] = useState("");
  const [greetingAr, setGreetingAr] = useState("");
  const [phoneConnectionType, setPhoneConnectionType] = useState<
    "none" | "twilio_native" | "custom_sip"
  >("none");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [sipUri, setSipUri] = useState("");
  const [businessHoursEnabled, setBusinessHoursEnabled] = useState(true);
  const [customPrompt, setCustomPrompt] = useState("");
  const [customVariables, setCustomVariables] = useState<
    Array<{ key: string; value: string }>
  >([]);
  const [enabledTools, setEnabledTools] = useState({
    checkAvailability: true,
    createBooking: true,
    cancelBooking: true,
    rescheduleBooking: true,
  });
  const [useKnowledgeBase, setUseKnowledgeBase] = useState(true);

  const handleCreate = async () => {
    setCreating(true);
    setError(null);
    setErrorType(null);

    try {
      const res = await fetchWithCSRF("/api/voice-agent/provision", {
        method: "POST",
        body: JSON.stringify({
          agentName: agentName.trim() || undefined,
          language,
          voiceTone,
          greetingMessage:
            greetingEn.trim() || greetingAr.trim()
              ? {
                  en: greetingEn.trim() || undefined,
                  ar: greetingAr.trim() || undefined,
                }
              : undefined,
          useKnowledgeBase,
          customPrompt: customPrompt || undefined,
          customVariables:
            customVariables.filter((v) => v.key && v.value).length > 0
              ? customVariables.filter((v) => v.key && v.value)
              : undefined,
          enabledTools,
          phoneConfig:
            phoneConnectionType !== "none"
              ? {
                  connectionType: phoneConnectionType,
                  phoneNumber: phoneNumber.trim() || undefined,
                  sipUri: sipUri.trim() || undefined,
                }
              : undefined,
        }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => null);
        if (data?.errorType) setErrorType(data.errorType);
        throw new Error(
          data?.message ||
            data?.error ||
            (isAr ? "فشل في إنشاء الوكيل" : "Failed to create agent"),
        );
      }

      const successData = await res.json().catch(() => null);
      if (successData?.data?.toolsWarning) {
        setToolsWarning(
          typeof successData.data.toolsWarning === "string"
            ? successData.data.toolsWarning
            : isAr
              ? "تم إنشاء الوكيل. أدوات الحجز تحتاج إعادة إعداد."
              : "Agent created. Booking tools need to be configured.",
        );
      }
      onComplete();
    } catch (err: unknown) {
      const message =
        err instanceof Error
          ? err.message
          : isAr
            ? "حدث خطأ غير متوقع"
            : "An unexpected error occurred";
      setError(message);
    } finally {
      setCreating(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto">
      {/* Progress indicator */}
      <div className="flex items-center justify-center gap-2 mb-8">
        {[1, 2, 3, 4, 5].map((s) => (
          <div key={s} className="flex items-center gap-2">
            <div
              className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors ${
                s < step
                  ? "bg-brand-green text-white"
                  : s === step
                    ? "bg-brand-green text-white"
                    : "bg-slate-100 text-slate-400"
              }`}
            >
              {s < step ? <Check className="w-4 h-4" /> : s}
            </div>
            {s < 5 && (
              <div
                className={`w-12 h-0.5 ${s < step ? "bg-brand-green" : "bg-slate-200"}`}
              />
            )}
          </div>
        ))}
      </div>
      <p className="text-center text-xs text-slate-400 mb-6">
        {isAr ? `الخطوة ${step} من 5` : `Step ${step} of 5`}
      </p>

      {/* Step 1: Welcome */}
      {step === 1 && (
        <div className="bg-white rounded-2xl border border-slate-200 p-8 shadow-sm text-center">
          <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-brand-green to-emerald-600 flex items-center justify-center mx-auto mb-6">
            <Sparkles className="w-8 h-8 text-white" />
          </div>
          <h2 className="text-2xl font-bold text-slate-900 mb-2">
            {isAr ? "أنشئ وكيلك الصوتي" : "Create Your Voice Agent"}
          </h2>
          <p className="text-slate-500 mb-8 max-w-md mx-auto">
            {isAr
              ? "وكيل ذكاء اصطناعي يتعامل مع مكالمات العملاء، يحجز المواعيد، ويجيب على الأسئلة - على مدار الساعة."
              : "An AI agent that handles customer calls, books appointments, and answers questions - 24/7."}
          </p>

          <div className="grid gap-4 text-start mb-8">
            {FEATURES.map((f, idx) => {
              const Icon = f.icon;
              return (
                <div
                  key={idx}
                  className="flex items-center gap-3 p-3 rounded-xl bg-slate-50"
                >
                  <div className="w-8 h-8 rounded-lg bg-brand-green/10 flex items-center justify-center flex-shrink-0">
                    <Icon className="w-4 h-4 text-brand-green" />
                  </div>
                  <span className="text-sm text-slate-700">
                    {isAr ? f.ar : f.en}
                  </span>
                  <Check className="w-4 h-4 text-brand-green ml-auto flex-shrink-0" />
                </div>
              );
            })}
          </div>

          <button
            onClick={() => setStep(2)}
            className="inline-flex items-center gap-2 px-6 py-3 bg-brand-green hover:bg-brand-greenHover text-white rounded-xl font-medium transition-colors"
          >
            {isAr ? "ابدأ الإعداد" : "Get Started"}
            <ChevronRight className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* Step 2: Configure */}
      {step === 2 && (
        <div className="bg-white rounded-2xl border border-slate-200 p-8 shadow-sm">
          <h2 className="text-xl font-bold text-slate-900 mb-1">
            {isAr ? "إعدادات الوكيل" : "Agent Configuration"}
          </h2>
          <p className="text-sm text-slate-500 mb-6">
            {isAr
              ? "خصّص وكيلك الصوتي حسب احتياجات عملك"
              : "Customize your voice agent to fit your business needs"}
          </p>

          <div className="space-y-5">
            {/* Agent Name */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {isAr ? "اسم الوكيل" : "Agent Name"}
              </label>
              <input
                type="text"
                value={agentName}
                onChange={(e) => setAgentName(e.target.value)}
                placeholder={
                  isAr
                    ? "مثال: مساعد عيادة النور"
                    : "e.g. Al Noor Clinic Assistant"
                }
                maxLength={100}
                className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none"
              />
              <p className="text-xs text-slate-400 mt-1">
                {isAr
                  ? "اختر اسماً مميزاً لوكيلك الصوتي"
                  : "Choose a distinctive name for your voice agent"}
              </p>
            </div>

            {/* Language */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {isAr ? "اللغة" : "Language"}
              </label>
              <select
                value={language}
                onChange={(e) => setLanguage(e.target.value)}
                className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none"
              >
                {LANGUAGES.map((l) => (
                  <option key={l.value} value={l.value}>
                    {isAr ? l.ar : l.en}
                  </option>
                ))}
              </select>
            </div>

            {/* Voice Tone */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {isAr ? "نبرة الصوت" : "Voice Tone"}
              </label>
              <div className="grid grid-cols-3 gap-3">
                {VOICE_TONES.map((t) => (
                  <button
                    key={t.value}
                    type="button"
                    onClick={() => setVoiceTone(t.value)}
                    className={`p-3 rounded-xl border text-center transition-colors ${
                      voiceTone === t.value
                        ? "border-brand-green bg-brand-green/5 ring-1 ring-brand-green"
                        : "border-slate-200 hover:border-slate-300"
                    }`}
                  >
                    <p className="text-sm font-medium text-slate-800">
                      {isAr ? t.ar : t.en}
                    </p>
                    <p className="text-[11px] text-slate-400 mt-0.5">
                      {isAr ? t.desc_ar : t.desc_en}
                    </p>
                  </button>
                ))}
              </div>
            </div>

            {/* Greeting Message */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {isAr
                  ? "رسالة الترحيب (اختياري)"
                  : "Greeting Message (Optional)"}
              </label>
              <div className="space-y-2">
                <textarea
                  aria-label={
                    isAr
                      ? "رسالة الترحيب بالإنجليزية"
                      : "English greeting message"
                  }
                  value={greetingEn}
                  onChange={(e) => setGreetingEn(e.target.value)}
                  placeholder="Hello! How can I help you today?"
                  rows={2}
                  className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none resize-none"
                />
                <textarea
                  aria-label={
                    isAr ? "رسالة الترحيب بالعربية" : "Arabic greeting message"
                  }
                  value={greetingAr}
                  onChange={(e) => setGreetingAr(e.target.value)}
                  placeholder="مرحباً! كيف يمكنني مساعدتك اليوم؟"
                  rows={2}
                  dir="rtl"
                  className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none resize-none"
                />
              </div>
            </div>

            {/* Business Hours Toggle */}
            <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
              <div>
                <p className="text-sm font-medium text-slate-700">
                  {isAr ? "ساعات العمل" : "Business Hours"}
                </p>
                <p className="text-xs text-slate-400 mt-0.5">
                  {isAr
                    ? "تقييد المكالمات بساعات العمل"
                    : "Restrict calls to business hours"}
                </p>
              </div>
              <button
                type="button"
                onClick={() => setBusinessHoursEnabled(!businessHoursEnabled)}
                className={`relative w-11 h-6 rounded-full transition-colors ${
                  businessHoursEnabled ? "bg-brand-green" : "bg-slate-300"
                }`}
                role="switch"
                aria-checked={businessHoursEnabled}
              >
                <span
                  className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${
                    businessHoursEnabled ? "translate-x-5" : "translate-x-0"
                  }`}
                />
              </button>
            </div>

            {/* Phone / SIP Configuration */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                <Phone className="w-4 h-4 inline-block mr-1 -mt-0.5" />
                {isAr
                  ? "رقم الهاتف / SIP (اختياري)"
                  : "Phone Number / SIP (Optional)"}
              </label>
              <p className="text-xs text-slate-400 mb-3">
                {isAr
                  ? "اربط رقم هاتف أو SIP trunk ليتمكن العملاء من الاتصال بالوكيل"
                  : "Connect a phone number or SIP trunk so customers can call your agent"}
              </p>
              <div className="grid grid-cols-3 gap-2 mb-3">
                {(
                  [
                    {
                      value: "none",
                      en: "Skip",
                      ar: "تخطي",
                    },
                    {
                      value: "twilio_native",
                      en: "Phone Number",
                      ar: "رقم هاتف",
                    },
                    {
                      value: "custom_sip",
                      en: "SIP URI",
                      ar: "SIP URI",
                    },
                  ] as const
                ).map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setPhoneConnectionType(opt.value)}
                    className={`p-2.5 rounded-xl border text-center text-sm font-medium transition-colors ${
                      phoneConnectionType === opt.value
                        ? "border-brand-green bg-brand-green/5 ring-1 ring-brand-green text-slate-800"
                        : "border-slate-200 hover:border-slate-300 text-slate-600"
                    }`}
                  >
                    {isAr ? opt.ar : opt.en}
                  </button>
                ))}
              </div>

              {phoneConnectionType === "twilio_native" && (
                <input
                  type="tel"
                  value={phoneNumber}
                  onChange={(e) => setPhoneNumber(e.target.value)}
                  placeholder={isAr ? "+974 1234 5678" : "+974 1234 5678"}
                  maxLength={30}
                  className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none"
                />
              )}

              {phoneConnectionType === "custom_sip" && (
                <div className="space-y-2">
                  <input
                    type="text"
                    value={sipUri}
                    onChange={(e) => setSipUri(e.target.value)}
                    placeholder="sip:trunk@provider.com"
                    maxLength={200}
                    className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm font-mono focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none"
                  />
                  <input
                    type="tel"
                    value={phoneNumber}
                    onChange={(e) => setPhoneNumber(e.target.value)}
                    placeholder={
                      isAr
                        ? "رقم الهاتف المرتبط (اختياري)"
                        : "Associated phone number (optional)"
                    }
                    maxLength={30}
                    className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none"
                  />
                </div>
              )}
            </div>
          </div>

          <div className="flex items-center justify-between mt-8">
            <button
              onClick={() => setStep(1)}
              className="inline-flex items-center gap-2 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-sm font-medium transition-colors"
            >
              <ChevronLeft className="w-4 h-4" />
              {isAr ? "السابق" : "Back"}
            </button>
            <button
              onClick={() => setStep(3)}
              className="inline-flex items-center gap-2 px-6 py-2.5 bg-brand-green hover:bg-brand-greenHover text-white rounded-xl text-sm font-medium transition-colors"
            >
              {isAr ? "التالي" : "Next"}
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Step 3: System Prompt & Variables */}
      {step === 3 && (
        <div className="bg-white rounded-2xl border border-slate-200 p-8 shadow-sm">
          <h2 className="text-xl font-bold text-slate-900 mb-1">
            {isAr ? "التعليمات المخصصة" : "Custom Instructions"}
          </h2>
          <p className="text-sm text-slate-500 mb-6">
            {isAr
              ? "أضف تعليمات مخصصة لوكيلك الصوتي"
              : "Add custom instructions for your voice agent"}
          </p>

          <div className="space-y-5">
            {/* System Prompt */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {isAr
                  ? "التعليمات المخصصة (اختياري)"
                  : "System Prompt (Optional)"}
              </label>
              <textarea
                value={customPrompt}
                onChange={(e) => setCustomPrompt(e.target.value)}
                placeholder={
                  isAr
                    ? "مثال: أنت مساعد ودود لعيادة طبية. اسأل دائماً عن رقم الهاتف قبل الحجز..."
                    : "Example: You are a friendly assistant for a dental clinic. Always ask for the phone number before booking..."
                }
                rows={5}
                maxLength={4000}
                className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm font-mono focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none resize-none"
              />
              <p className="text-xs text-slate-400 mt-1 text-end">
                {customPrompt.length}/4000
              </p>
            </div>

            {/* Custom Variables */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <label className="block text-sm font-medium text-slate-700">
                  {isAr
                    ? "المتغيرات المخصصة (اختياري)"
                    : "Custom Variables (Optional)"}
                </label>
                {customVariables.length < 20 && (
                  <button
                    type="button"
                    onClick={() =>
                      setCustomVariables([
                        ...customVariables,
                        { key: "", value: "" },
                      ])
                    }
                    className="text-xs text-brand-green hover:text-brand-greenHover font-medium"
                  >
                    {isAr ? "+ إضافة متغير" : "+ Add Variable"}
                  </button>
                )}
              </div>
              <p className="text-xs text-slate-400 mb-3">
                {isAr
                  ? "استخدم {{اسم_المتغير}} في التعليمات للإشارة إلى هذه القيم"
                  : "Use {{variable_name}} in your prompt to reference these values"}
              </p>
              {customVariables.map((v, idx) => (
                <div key={idx} className="flex items-center gap-2 mb-2">
                  <input
                    type="text"
                    value={v.key}
                    onChange={(e) => {
                      const updated = [...customVariables];
                      updated[idx] = { ...updated[idx], key: e.target.value };
                      setCustomVariables(updated);
                    }}
                    placeholder={isAr ? "المفتاح" : "Key"}
                    className="w-1/3 rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none"
                  />
                  <input
                    type="text"
                    value={v.value}
                    onChange={(e) => {
                      const updated = [...customVariables];
                      updated[idx] = { ...updated[idx], value: e.target.value };
                      setCustomVariables(updated);
                    }}
                    placeholder={isAr ? "القيمة" : "Value"}
                    className="flex-1 rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none"
                  />
                  <button
                    type="button"
                    onClick={() =>
                      setCustomVariables(
                        customVariables.filter((_, i) => i !== idx),
                      )
                    }
                    className="p-2 text-slate-400 hover:text-red-500 transition-colors"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          </div>

          <div className="flex items-center justify-between mt-8">
            <button
              onClick={() => setStep(2)}
              className="inline-flex items-center gap-2 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-sm font-medium transition-colors"
            >
              <ChevronLeft className="w-4 h-4" />
              {isAr ? "السابق" : "Back"}
            </button>
            <button
              onClick={() => setStep(4)}
              className="inline-flex items-center gap-2 px-6 py-2.5 bg-brand-green hover:bg-brand-greenHover text-white rounded-xl text-sm font-medium transition-colors"
            >
              {isAr ? "التالي" : "Next"}
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Step 4: Tools & Knowledge Base */}
      {step === 4 && (
        <div className="bg-white rounded-2xl border border-slate-200 p-8 shadow-sm">
          <h2 className="text-xl font-bold text-slate-900 mb-1">
            {isAr ? "الأدوات وقاعدة المعرفة" : "Tools & Knowledge Base"}
          </h2>
          <p className="text-sm text-slate-500 mb-6">
            {isAr
              ? "اختر الأدوات التي يمكن لوكيلك استخدامها"
              : "Choose which tools your agent can use"}
          </p>

          <div className="space-y-5">
            {/* Booking Tools */}
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-3">
                {isAr ? "أدوات الحجز" : "Booking Tools"}
              </label>
              <div className="space-y-2">
                {[
                  {
                    key: "checkAvailability" as const,
                    en: "Check Availability",
                    ar: "التحقق من التوفر",
                    descEn: "Query available time slots",
                    descAr: "الاستعلام عن المواعيد المتاحة",
                  },
                  {
                    key: "createBooking" as const,
                    en: "Create Booking",
                    ar: "إنشاء حجز",
                    descEn: "Book appointments for callers",
                    descAr: "حجز مواعيد للمتصلين",
                  },
                  {
                    key: "cancelBooking" as const,
                    en: "Cancel Booking",
                    ar: "إلغاء حجز",
                    descEn: "Cancel existing appointments",
                    descAr: "إلغاء المواعيد الحالية",
                  },
                  {
                    key: "rescheduleBooking" as const,
                    en: "Reschedule Booking",
                    ar: "إعادة جدولة",
                    descEn: "Reschedule to a new date/time",
                    descAr: "إعادة جدولة لموعد جديد",
                  },
                ].map((tool) => (
                  <label
                    key={tool.key}
                    className="flex items-center justify-between p-3 rounded-xl bg-slate-50 cursor-pointer hover:bg-slate-100 transition-colors"
                  >
                    <div>
                      <p className="text-sm font-medium text-slate-700">
                        {isAr ? tool.ar : tool.en}
                      </p>
                      <p className="text-xs text-slate-400">
                        {isAr ? tool.descAr : tool.descEn}
                      </p>
                    </div>
                    <input
                      type="checkbox"
                      checked={enabledTools[tool.key]}
                      onChange={(e) =>
                        setEnabledTools({
                          ...enabledTools,
                          [tool.key]: e.target.checked,
                        })
                      }
                      className="w-4 h-4 rounded border-slate-300 text-brand-green focus:ring-brand-green"
                    />
                  </label>
                ))}
              </div>
            </div>

            {/* Knowledge Base Toggle */}
            <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
              <div>
                <p className="text-sm font-medium text-slate-700">
                  {isAr ? "قاعدة المعرفة" : "Knowledge Base"}
                </p>
                <p className="text-xs text-slate-400 mt-0.5">
                  {isAr
                    ? "يستخدم الوكيل مستنداتك للإجابة على الأسئلة بدقة"
                    : "Agent uses your documents to answer questions accurately"}
                </p>
              </div>
              <button
                type="button"
                onClick={() => setUseKnowledgeBase(!useKnowledgeBase)}
                className={`relative w-11 h-6 rounded-full transition-colors ${useKnowledgeBase ? "bg-brand-green" : "bg-slate-300"}`}
                role="switch"
                aria-checked={useKnowledgeBase}
              >
                <span
                  className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${useKnowledgeBase ? "translate-x-5" : "translate-x-0"}`}
                />
              </button>
            </div>
          </div>

          <div className="flex items-center justify-between mt-8">
            <button
              onClick={() => setStep(3)}
              className="inline-flex items-center gap-2 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-sm font-medium transition-colors"
            >
              <ChevronLeft className="w-4 h-4" />
              {isAr ? "السابق" : "Back"}
            </button>
            <button
              onClick={() => setStep(5)}
              className="inline-flex items-center gap-2 px-6 py-2.5 bg-brand-green hover:bg-brand-greenHover text-white rounded-xl text-sm font-medium transition-colors"
            >
              {isAr ? "مراجعة" : "Review"}
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Step 5: Review & Create */}
      {step === 5 && (
        <div className="bg-white rounded-2xl border border-slate-200 p-8 shadow-sm">
          <h2 className="text-xl font-bold text-slate-900 mb-1">
            {isAr ? "مراجعة وإنشاء" : "Review & Create"}
          </h2>
          <p className="text-sm text-slate-500 mb-6">
            {isAr
              ? "تحقق من الإعدادات قبل إنشاء وكيلك الصوتي"
              : "Confirm your settings before creating your voice agent"}
          </p>

          <div className="space-y-4 mb-8">
            {agentName.trim() && (
              <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
                <span className="text-sm text-slate-500">
                  {isAr ? "اسم الوكيل" : "Agent Name"}
                </span>
                <span className="text-sm font-medium text-slate-800">
                  {agentName.trim()}
                </span>
              </div>
            )}
            <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
              <span className="text-sm text-slate-500">
                {isAr ? "اللغة" : "Language"}
              </span>
              <span className="text-sm font-medium text-slate-800">
                {
                  LANGUAGES.find((l) => l.value === language)?.[
                    isAr ? "ar" : "en"
                  ]
                }
              </span>
            </div>
            <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
              <span className="text-sm text-slate-500">
                {isAr ? "نبرة الصوت" : "Voice Tone"}
              </span>
              <span className="text-sm font-medium text-slate-800">
                {
                  VOICE_TONES.find((t) => t.value === voiceTone)?.[
                    isAr ? "ar" : "en"
                  ]
                }
              </span>
            </div>
            {(greetingEn.trim() || greetingAr.trim()) && (
              <div className="p-4 rounded-xl bg-slate-50">
                <span className="text-sm text-slate-500 block mb-1">
                  {isAr ? "رسالة الترحيب" : "Greeting"}
                </span>
                {greetingEn && (
                  <span className="text-sm text-slate-800 block">
                    EN: {greetingEn}
                  </span>
                )}
                {greetingAr && (
                  <span className="text-sm text-slate-800 block" dir="rtl">
                    AR: {greetingAr}
                  </span>
                )}
              </div>
            )}
            <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
              <span className="text-sm text-slate-500">
                {isAr ? "ساعات العمل" : "Business Hours"}
              </span>
              <span className="text-sm font-medium text-slate-800">
                {businessHoursEnabled
                  ? isAr
                    ? "مفعّل"
                    : "Enabled"
                  : isAr
                    ? "معطّل"
                    : "Disabled"}
              </span>
            </div>
            {customPrompt && (
              <div className="p-4 rounded-xl bg-slate-50">
                <span className="text-sm text-slate-500 block mb-1">
                  {isAr ? "التعليمات المخصصة" : "Custom Prompt"}
                </span>
                <span className="text-sm text-slate-800 font-mono line-clamp-3">
                  {customPrompt}
                </span>
              </div>
            )}
            {customVariables.filter((v) => v.key && v.value).length > 0 && (
              <div className="p-4 rounded-xl bg-slate-50">
                <span className="text-sm text-slate-500 block mb-1">
                  {isAr ? "المتغيرات المخصصة" : "Custom Variables"}
                </span>
                <div className="flex flex-wrap gap-2 mt-1">
                  {customVariables
                    .filter((v) => v.key && v.value)
                    .map((v, i) => (
                      <span
                        key={i}
                        className="text-xs bg-white border border-slate-200 rounded-lg px-2 py-1 text-slate-700"
                      >
                        {v.key}: {v.value}
                      </span>
                    ))}
                </div>
              </div>
            )}
            <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
              <span className="text-sm text-slate-500">
                {isAr ? "أدوات الحجز" : "Booking Tools"}
              </span>
              <span className="text-sm font-medium text-slate-800">
                {Object.values(enabledTools).filter(Boolean).length}/4{" "}
                {isAr ? "مفعّل" : "enabled"}
              </span>
            </div>
            <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50">
              <span className="text-sm text-slate-500">
                {isAr ? "قاعدة المعرفة" : "Knowledge Base"}
              </span>
              <span
                className={`text-sm font-medium ${useKnowledgeBase ? "text-brand-green" : "text-slate-500"}`}
              >
                {useKnowledgeBase
                  ? isAr
                    ? "مفعّل"
                    : "Enabled"
                  : isAr
                    ? "معطّل"
                    : "Disabled"}
              </span>
            </div>
            {phoneConnectionType !== "none" && (
              <div className="p-4 rounded-xl bg-slate-50">
                <span className="text-sm text-slate-500 block mb-1">
                  <Phone className="w-3.5 h-3.5 inline-block mr-1 -mt-0.5" />
                  {isAr ? "الهاتف / SIP" : "Phone / SIP"}
                </span>
                <span className="text-sm font-medium text-slate-800">
                  {phoneConnectionType === "twilio_native"
                    ? phoneNumber || (isAr ? "رقم هاتف" : "Phone Number")
                    : sipUri || (isAr ? "SIP URI" : "SIP URI")}
                </span>
              </div>
            )}
          </div>

          {toolsWarning && (
            <div className="mb-4 p-4 rounded-xl bg-amber-50 border border-amber-200">
              <p className="text-amber-700 text-sm font-medium">
                {toolsWarning}
              </p>
            </div>
          )}

          {error && (
            <div className="mb-4 p-4 rounded-xl bg-red-50 border border-red-200">
              <p className="text-red-600 text-sm font-medium">{error}</p>
              {(errorType === "permission_error" ||
                error.includes("permission") ||
                error.includes("convai_write") ||
                error.includes("unauthorized")) && (
                <p className="text-xs text-red-500 mt-2">
                  {isAr
                    ? "مفتاح API يحتاج صلاحية convai_write."
                    : "Your API key needs the convai_write permission."}{" "}
                  <a
                    href="https://elevenlabs.io/app/settings/api-keys"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="underline font-medium"
                  >
                    {isAr
                      ? "تحديث مفتاح API على ElevenLabs"
                      : "Update API key on ElevenLabs"}
                  </a>
                </p>
              )}
            </div>
          )}

          <div className="flex items-center justify-between">
            <button
              onClick={() => setStep(4)}
              disabled={creating}
              className="inline-flex items-center gap-2 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-sm font-medium transition-colors disabled:opacity-50"
            >
              <ChevronLeft className="w-4 h-4" />
              {isAr ? "السابق" : "Back"}
            </button>
            <button
              onClick={handleCreate}
              disabled={creating}
              className="inline-flex items-center gap-2 px-6 py-2.5 bg-brand-green hover:bg-brand-greenHover text-white rounded-xl text-sm font-medium transition-colors disabled:opacity-50"
            >
              {creating ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  {isAr ? "جاري الإنشاء..." : "Creating..."}
                </>
              ) : (
                <>
                  <Sparkles className="w-4 h-4" />
                  {isAr ? "إنشاء الوكيل" : "Create Agent"}
                </>
              )}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
