/**
 * Testing Step - Test WhatsApp and voice agent
 */

"use client";

import { useState } from "react";
import {
  MessageSquare,
  Phone,
  Send,
  CheckCircle2,
  XCircle,
  Loader2,
} from "lucide-react";
import type { Lang } from "@/lib/config";

interface TestingStepProps {
  lang: Lang;
  onContinue: () => void;
}

export default function TestingStep({ lang, onContinue }: TestingStepProps) {
  const isAr = lang === "ar";
  const [testingWhatsApp, setTestingWhatsApp] = useState(false);
  const [testingVoice, setTestingVoice] = useState(false);
  const [whatsAppStatus, setWhatsAppStatus] = useState<
    "idle" | "success" | "error"
  >("idle");
  const [voiceStatus, setVoiceStatus] = useState<"idle" | "success" | "error">(
    "idle",
  );
  const [testPhone, setTestPhone] = useState("");

  const t = {
    title: isAr ? "اختبار والتحقق" : "Test & Verify",
    subtitle: isAr
      ? "تأكد من أن كل شيء يعمل بشكل صحيح"
      : "Make sure everything works correctly",
    whatsAppTitle: isAr ? "اختبار رسالة واتساب" : "Test WhatsApp Message",
    whatsAppDesc: isAr
      ? "أرسل رسالة اختبار إلى رقمك للتحقق من التكامل"
      : "Send a test message to your number to verify integration",
    voiceTitle: isAr ? "اختبار التحية الصوتية" : "Test Voice Greeting",
    voiceDesc: isAr
      ? "استمع إلى تحية الوكيل الصوتي"
      : "Listen to your voice agent greeting",
    phonePlaceholder: isAr
      ? "رقم هاتفك (+974...)"
      : "Your phone number (+974...)",
    sendTestBtn: isAr ? "إرسال رسالة تجريبية" : "Send Test Message",
    playGreetingBtn: isAr ? "تشغيل التحية" : "Play Greeting",
    testing: isAr ? "جارٍ الاختبار..." : "Testing...",
    success: isAr ? "نجح!" : "Success!",
    error: isAr ? "فشل" : "Failed",
    whatsAppSuccess: isAr
      ? "تم إرسال رسالة واتساب التجريبية!"
      : "Test WhatsApp message sent!",
    whatsAppError: isAr
      ? "فشل إرسال رسالة واتساب"
      : "Failed to send WhatsApp message",
    voiceSuccess: isAr
      ? "يعمل الوكيل الصوتي بشكل مثالي!"
      : "Voice agent working perfectly!",
    voiceError: isAr ? "فشل اختبار الوكيل الصوتي" : "Voice agent test failed",
    allGood: isAr ? "كل شيء يعمل بشكل رائع!" : "Everything is working great!",
    continueBtn: isAr ? "إكمال الإعداد" : "Complete Setup",
  };

  const handleTestWhatsApp = async () => {
    if (!testPhone) return;

    setTestingWhatsApp(true);
    setWhatsAppStatus("idle");

    try {
      const response = await fetch("/api/integrations/whatsapp/test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ phone: testPhone }),
      });

      if (response.ok) {
        setWhatsAppStatus("success");
      } else {
        setWhatsAppStatus("error");
      }
    } catch (error) {
      console.error("WhatsApp test error:", error);
      setWhatsAppStatus("error");
    } finally {
      setTestingWhatsApp(false);
    }
  };

  const handleTestVoice = async () => {
    setTestingVoice(true);
    setVoiceStatus("idle");

    try {
      const response = await fetch("/api/voice-agent/test", {
        method: "POST",
      });

      if (response.ok) {
        const data = await response.json();
        // Play audio if available
        if (data.audioUrl) {
          const audio = new Audio(data.audioUrl);
          audio.play();
        }
        setVoiceStatus("success");
      } else {
        setVoiceStatus("error");
      }
    } catch (error) {
      console.error("Voice test error:", error);
      setVoiceStatus("error");
    } finally {
      setTestingVoice(false);
    }
  };

  const allTestsPassed =
    whatsAppStatus === "success" && voiceStatus === "success";

  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-emerald-500 to-teal-600 shadow-lg shadow-emerald-500/25 mb-6">
          <CheckCircle2 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>

      {/* Test Cards */}
      <div className="space-y-4">
        {/* WhatsApp Test */}
        <div className="p-6 rounded-2xl bg-white border border-slate-200">
          <div className="flex items-start gap-4 mb-4">
            <div className="flex-shrink-0 w-12 h-12 rounded-xl bg-green-100 flex items-center justify-center">
              <MessageSquare className="w-6 h-6 text-green-600" />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-bold text-slate-900 mb-1">
                {t.whatsAppTitle}
              </h3>
              <p className="text-sm text-slate-600">{t.whatsAppDesc}</p>
            </div>
            {whatsAppStatus === "success" && (
              <CheckCircle2 className="w-6 h-6 text-green-500 flex-shrink-0" />
            )}
            {whatsAppStatus === "error" && (
              <XCircle className="w-6 h-6 text-red-500 flex-shrink-0" />
            )}
          </div>

          <div className="flex gap-3">
            <input
              type="tel"
              value={testPhone}
              onChange={(e) => setTestPhone(e.target.value)}
              placeholder={t.phonePlaceholder}
              className="flex-1 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"
            />
            <button
              onClick={handleTestWhatsApp}
              disabled={!testPhone || testingWhatsApp}
              className="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-white font-semibold shadow-md hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
            >
              {testingWhatsApp ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  {t.testing}
                </>
              ) : (
                <>
                  <Send className="w-4 h-4" />
                  {t.sendTestBtn}
                </>
              )}
            </button>
          </div>

          {whatsAppStatus === "success" && (
            <div className="mt-4 p-3 rounded-lg bg-green-50 border border-green-200 text-sm text-green-700">
              {t.whatsAppSuccess}
            </div>
          )}
          {whatsAppStatus === "error" && (
            <div className="mt-4 p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700">
              {t.whatsAppError}
            </div>
          )}
        </div>

        {/* Voice Test */}
        <div className="p-6 rounded-2xl bg-white border border-slate-200">
          <div className="flex items-start gap-4 mb-4">
            <div className="flex-shrink-0 w-12 h-12 rounded-xl bg-blue-100 flex items-center justify-center">
              <Phone className="w-6 h-6 text-blue-600" />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-bold text-slate-900 mb-1">
                {t.voiceTitle}
              </h3>
              <p className="text-sm text-slate-600">{t.voiceDesc}</p>
            </div>
            {voiceStatus === "success" && (
              <CheckCircle2 className="w-6 h-6 text-green-500 flex-shrink-0" />
            )}
            {voiceStatus === "error" && (
              <XCircle className="w-6 h-6 text-red-500 flex-shrink-0" />
            )}
          </div>

          <button
            onClick={handleTestVoice}
            disabled={testingVoice}
            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 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
          >
            {testingVoice ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                {t.testing}
              </>
            ) : (
              <>
                <Phone className="w-4 h-4" />
                {t.playGreetingBtn}
              </>
            )}
          </button>

          {voiceStatus === "success" && (
            <div className="mt-4 p-3 rounded-lg bg-green-50 border border-green-200 text-sm text-green-700">
              {t.voiceSuccess}
            </div>
          )}
          {voiceStatus === "error" && (
            <div className="mt-4 p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700">
              {t.voiceError}
            </div>
          )}
        </div>
      </div>

      {/* All Tests Passed */}
      {allTestsPassed && (
        <div className="p-6 rounded-2xl bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200 text-center">
          <CheckCircle2 className="w-12 h-12 text-emerald-600 mx-auto mb-3" />
          <p className="text-lg font-bold text-emerald-900">{t.allGood}</p>
        </div>
      )}

      {/* Complete Button */}
      <div className="flex justify-center pt-4">
        <button
          onClick={onContinue}
          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"
        >
          {t.continueBtn}
          <CheckCircle2 className="w-5 h-5" />
        </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>
  );
}
