/**
 * Voice Agent Setup Step - Configure AI voice receptionist
 */

"use client";

import { useState } from "react";
import { Phone, Volume2, CheckCircle2 } from "lucide-react";
import type { Lang } from "@/lib/config";
import type { VoiceAgentConfig } from "@/lib/types/onboarding.types";

interface VoiceAgentSetupStepProps {
  lang: Lang;
  onContinue: (config: VoiceAgentConfig) => void;
}

export default function VoiceAgentSetupStep({
  lang,
  onContinue,
}: VoiceAgentSetupStepProps) {
  const isAr = lang === "ar";
  const [config, setConfig] = useState<VoiceAgentConfig>({
    languages: ["ar"],
    tone: "professional",
    customGreeting: "",
  });
  const [saving, setSaving] = useState(false);

  const t = {
    title: isAr ? "إعداد الوكيل الصوتي" : "Voice Agent Setup",
    subtitle: isAr
      ? "قم بتخصيص مساعدك الصوتي الذكي"
      : "Customize your AI voice assistant",
    languageLabel: isAr ? "اللغات المدعومة" : "Supported Languages",
    arabic: isAr ? "العربية" : "Arabic",
    english: isAr ? "الإنجليزية" : "English",
    both: isAr ? "كلاهما" : "Both",
    toneLabel: isAr ? "نبرة الصوت" : "Voice Tone",
    professional: isAr ? "احترافي" : "Professional",
    friendly: isAr ? "ودود" : "Friendly",
    casual: isAr ? "غير رسمي" : "Casual",
    greetingLabel: isAr
      ? "رسالة الترحيب المخصصة (اختياري)"
      : "Custom Greeting (Optional)",
    greetingPlaceholder: isAr
      ? "مرحباً! كيف يمكنني مساعدتك اليوم؟"
      : "Hello! How can I help you today?",
    previewBtn: isAr ? "معاينة الصوت" : "Preview Voice",
    saveBtn: isAr ? "حفظ والمتابعة" : "Save & Continue",
    saving: isAr ? "جارٍ الحفظ..." : "Saving...",
  };

  const handleLanguageToggle = (selectedLang: "ar" | "en" | "both") => {
    setConfig((prev) => ({ ...prev, languages: [selectedLang] }));
  };

  const handleToneChange = (tone: "professional" | "friendly" | "casual") => {
    setConfig((prev) => ({ ...prev, tone }));
  };

  const handleGreetingChange = (greeting: string) => {
    setConfig((prev) => ({ ...prev, customGreeting: greeting }));
  };

  const handlePreview = () => {
    // TODO: Implement preview functionality
    console.log("Preview voice with config:", config);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const response = await fetch("/api/voice-agent/configure", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(config),
      });

      if (response.ok) {
        onContinue(config);
      }
    } catch (error) {
      console.error("Error saving voice agent config:", error);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-8 animate-fadeIn">
      {/* Header */}
      <div className="text-center">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg shadow-blue-500/25 mb-6">
          <Phone className="w-8 h-8 text-white" />
        </div>
        <h2 className="text-3xl font-bold text-slate-900 mb-3">{t.title}</h2>
        <p className="text-lg text-slate-600">{t.subtitle}</p>
      </div>

      {/* Configuration Form */}
      <div className="space-y-6">
        {/* Language Selection */}
        <div className="p-6 rounded-2xl bg-white border border-slate-200">
          <label className="block text-sm font-semibold text-slate-700 mb-4">
            {t.languageLabel}
          </label>
          <div className="grid grid-cols-3 gap-3">
            {[
              { value: "ar" as const, label: t.arabic },
              { value: "en" as const, label: t.english },
              { value: "both" as const, label: t.both },
            ].map((option) => (
              <button
                key={option.value}
                onClick={() => handleLanguageToggle(option.value)}
                className={`p-4 rounded-xl border-2 font-semibold text-sm transition-all ${
                  config.languages.includes(option.value)
                    ? "border-brand-green bg-brand-green/10 text-brand-green"
                    : "border-slate-200 text-slate-600 hover:border-slate-300"
                }`}
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>

        {/* Tone Selection */}
        <div className="p-6 rounded-2xl bg-white border border-slate-200">
          <label className="block text-sm font-semibold text-slate-700 mb-4">
            {t.toneLabel}
          </label>
          <div className="grid grid-cols-3 gap-3">
            {[
              { value: "professional" as const, label: t.professional },
              { value: "friendly" as const, label: t.friendly },
              { value: "casual" as const, label: t.casual },
            ].map((option) => (
              <button
                key={option.value}
                onClick={() => handleToneChange(option.value)}
                className={`p-4 rounded-xl border-2 font-semibold text-sm transition-all ${
                  config.tone === option.value
                    ? "border-brand-green bg-brand-green/10 text-brand-green"
                    : "border-slate-200 text-slate-600 hover:border-slate-300"
                }`}
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>

        {/* Custom Greeting */}
        <div className="p-6 rounded-2xl bg-white border border-slate-200">
          <label className="block text-sm font-semibold text-slate-700 mb-4">
            {t.greetingLabel}
          </label>
          <textarea
            value={config.customGreeting}
            onChange={(e) => handleGreetingChange(e.target.value)}
            placeholder={t.greetingPlaceholder}
            rows={4}
            maxLength={500}
            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"
          />
          <div className="mt-2 text-xs text-slate-500 text-right">
            {config.customGreeting.length}/500
          </div>
        </div>

        {/* Preview Button */}
        <div className="flex justify-center">
          <button
            onClick={handlePreview}
            className="inline-flex items-center gap-2 px-6 py-3 rounded-xl border-2 border-brand-green text-brand-green font-semibold hover:bg-brand-green/5 transition-all"
          >
            <Volume2 className="w-4 h-4" />
            {t.previewBtn}
          </button>
        </div>
      </div>

      {/* Save & Continue */}
      <div className="flex justify-center pt-4">
        <button
          onClick={handleSave}
          disabled={saving}
          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"
        >
          {saving ? (
            <>
              <CheckCircle2 className="w-5 h-5 animate-pulse" />
              {t.saving}
            </>
          ) : (
            <>
              {t.saveBtn}
              <span className="text-xl">{isAr ? "←" : "→"}</span>
            </>
          )}
        </button>
      </div>

      <style jsx>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        .animate-fadeIn {
          animation: fadeIn 0.4s ease-out forwards;
        }
      `}</style>
    </div>
  );
}
