"use client";

import { useState } from "react";
import type { Lang } from "@/lib/config";
import type { VoiceAgentConfig } from "@/lib/types/voice-agent.types";
import {
  Save,
  Loader2,
  Globe,
  Volume2,
  MessageSquare,
  Brain,
  AlertTriangle,
  X,
  Wrench,
  Code,
} from "lucide-react";

interface VoiceAgentConfigFormProps {
  lang: Lang;
  config: VoiceAgentConfig;
  onSave: (config: VoiceAgentConfig) => Promise<void>;
  saving?: boolean;
}

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

const VOICE_TONE_OPTIONS = [
  { value: "professional", en: "Professional", ar: "احترافي" },
  { value: "friendly", en: "Friendly", ar: "ودود" },
  { value: "custom", en: "Casual", ar: "عفوي" },
];

export default function VoiceAgentConfigForm({
  lang,
  config,
  onSave,
  saving = false,
}: VoiceAgentConfigFormProps) {
  const isAr = lang === "ar";

  const [language, setLanguage] = useState(config.language);
  const [voiceTone, setVoiceTone] = useState(config.voiceTone);
  const [greetingEn, setGreetingEn] = useState(
    config.greetingMessage?.en ?? "",
  );
  const [greetingAr, setGreetingAr] = useState(
    config.greetingMessage?.ar ?? "",
  );
  const [useKnowledgeBase, setUseKnowledgeBase] = useState(
    config.useKnowledgeBase,
  );
  const [escalationKeywords, setEscalationKeywords] = useState(
    config.escalationKeywords?.join(", ") ?? "",
  );
  const [customPrompt, setCustomPrompt] = useState(config.customPrompt ?? "");
  const [customVariables, setCustomVariables] = useState(
    config.customVariables ?? [],
  );
  const [enabledTools, setEnabledTools] = useState(
    config.enabledTools ?? {
      checkAvailability: true,
      createBooking: true,
      cancelBooking: true,
      rescheduleBooking: true,
    },
  );

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const updatedConfig: VoiceAgentConfig = {
      language: language as VoiceAgentConfig["language"],
      voiceTone: voiceTone as VoiceAgentConfig["voiceTone"],
      greetingMessage: {
        en: greetingEn || undefined,
        ar: greetingAr || undefined,
      },
      useKnowledgeBase,
      escalationKeywords: escalationKeywords
        ? escalationKeywords
            .split(",")
            .map((k) => k.trim())
            .filter(Boolean)
        : undefined,
      customPrompt: customPrompt || undefined,
      customVariables:
        customVariables.filter((v) => v.key && v.value).length > 0
          ? customVariables.filter((v) => v.key && v.value)
          : undefined,
      enabledTools,
    };

    await onSave(updatedConfig);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Language */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center">
            <Globe className="w-4 h-4 text-blue-600" />
          </div>
          <h3 className="font-semibold text-slate-900">
            {isAr ? "اللغة" : "Language"}
          </h3>
        </div>
        <select
          value={language}
          onChange={(e) =>
            setLanguage(e.target.value as VoiceAgentConfig["language"])
          }
          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"
        >
          {LANGUAGE_OPTIONS.map((l) => (
            <option key={l.value} value={l.value}>
              {isAr ? l.ar : l.en}
            </option>
          ))}
        </select>
      </div>

      {/* Voice Tone */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-purple-50 flex items-center justify-center">
            <Volume2 className="w-4 h-4 text-purple-600" />
          </div>
          <h3 className="font-semibold text-slate-900">
            {isAr ? "نبرة الصوت" : "Voice Tone"}
          </h3>
        </div>
        <div className="grid grid-cols-3 gap-3">
          {VOICE_TONE_OPTIONS.map((t) => (
            <button
              key={t.value}
              type="button"
              onClick={() =>
                setVoiceTone(t.value as VoiceAgentConfig["voiceTone"])
              }
              className={`p-3 rounded-xl border text-sm font-medium transition-colors ${
                voiceTone === t.value
                  ? "border-brand-green bg-brand-green/5 text-brand-green ring-1 ring-brand-green"
                  : "border-slate-200 text-slate-600 hover:border-slate-300"
              }`}
            >
              {isAr ? t.ar : t.en}
            </button>
          ))}
        </div>
      </div>

      {/* Greeting Message */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-green-50 flex items-center justify-center">
            <MessageSquare className="w-4 h-4 text-green-600" />
          </div>
          <h3 className="font-semibold text-slate-900">
            {isAr ? "رسالة الترحيب" : "Greeting Message"}
          </h3>
        </div>
        <div className="space-y-3">
          <div>
            <label className="block text-xs font-medium text-slate-500 mb-1">
              English
            </label>
            <textarea
              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"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-slate-500 mb-1">
              {isAr ? "العربية" : "Arabic"}
            </label>
            <textarea
              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>
      </div>

      {/* Knowledge Base Toggle */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-amber-50 flex items-center justify-center">
              <Brain className="w-4 h-4 text-amber-600" />
            </div>
            <div>
              <h3 className="font-semibold text-slate-900">
                {isAr ? "قاعدة المعرفة" : "Knowledge Base"}
              </h3>
              <p className="text-xs text-slate-400 mt-0.5">
                {isAr
                  ? "يستخدم الوكيل مستندات عملك للإجابة بدقة"
                  : "Agent uses your business docs for accurate answers"}
              </p>
            </div>
          </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>

      {/* Escalation Keywords */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-red-50 flex items-center justify-center">
            <AlertTriangle className="w-4 h-4 text-red-600" />
          </div>
          <div>
            <h3 className="font-semibold text-slate-900">
              {isAr ? "كلمات التصعيد" : "Escalation Keywords"}
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">
              {isAr
                ? "عندما يذكر العميل هذه الكلمات، يتم تحويله لموظف بشري"
                : "When a customer mentions these words, transfer to a human agent"}
            </p>
          </div>
        </div>
        <input
          type="text"
          value={escalationKeywords}
          onChange={(e) => setEscalationKeywords(e.target.value)}
          placeholder={
            isAr
              ? "مدير، شكوى، إلغاء (مفصولة بفواصل)"
              : "manager, complaint, cancel (comma-separated)"
          }
          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>

      {/* System Prompt */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-indigo-50 flex items-center justify-center">
            <Code className="w-4 h-4 text-indigo-600" />
          </div>
          <div>
            <h3 className="font-semibold text-slate-900">
              {isAr ? "التعليمات المخصصة" : "System Prompt"}
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">
              {isAr
                ? "أضف تعليمات مخصصة لتوجيه سلوك الوكيل"
                : "Add custom instructions to guide agent behavior"}
            </p>
          </div>
        </div>
        <textarea
          value={customPrompt}
          onChange={(e) => setCustomPrompt(e.target.value)}
          placeholder={
            isAr
              ? "مثال: أنت مساعد ودود لعيادة طبية..."
              : "Example: You are a friendly assistant for a dental clinic..."
          }
          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 className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-cyan-50 flex items-center justify-center">
              <Code className="w-4 h-4 text-cyan-600" />
            </div>
            <div>
              <h3 className="font-semibold text-slate-900">
                {isAr ? "المتغيرات المخصصة" : "Custom Variables"}
              </h3>
              <p className="text-xs text-slate-400 mt-0.5">
                {isAr
                  ? "استخدم {{اسم_المتغير}} في التعليمات"
                  : "Use {{variable_name}} in your prompt"}
              </p>
            </div>
          </div>
          {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>
        {customVariables.length === 0 ? (
          <p className="text-sm text-slate-400 text-center py-3">
            {isAr ? "لا توجد متغيرات بعد" : "No variables added yet"}
          </p>
        ) : (
          <div className="space-y-2">
            {customVariables.map((v, idx) => (
              <div key={idx} className="flex items-center gap-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>

      {/* Booking Tools */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
        <div className="flex items-center gap-3 mb-4">
          <div className="w-8 h-8 rounded-lg bg-emerald-50 flex items-center justify-center">
            <Wrench className="w-4 h-4 text-emerald-600" />
          </div>
          <div>
            <h3 className="font-semibold text-slate-900">
              {isAr ? "أدوات الحجز" : "Booking Tools"}
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">
              {isAr
                ? "اختر الأدوات التي يمكن لوكيلك استخدامها"
                : "Choose which tools your agent can use"}
            </p>
          </div>
        </div>
        <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: "إعادة جدولة لموعد جديد",
              },
            ] as const
          ).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>

      {/* Save Button */}
      <div className="flex justify-end">
        <button
          type="submit"
          disabled={saving}
          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 disabled:opacity-50"
        >
          {saving ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" />
              {isAr ? "جاري الحفظ..." : "Saving..."}
            </>
          ) : (
            <>
              <Save className="w-4 h-4" />
              {isAr ? "حفظ التغييرات" : "Save Changes"}
            </>
          )}
        </button>
      </div>
    </form>
  );
}
