"use client";

/**
 * Outbound Call Button
 *
 * Component for initiating outbound voice calls
 * through the ElevenLabs voice agent
 */

import React, { useState } from "react";
import {
  Phone,
  PhoneOutgoing,
  X,
  Loader2,
  AlertCircle,
  CheckCircle,
} from "lucide-react";

interface OutboundCallButtonProps {
  lang?: "en" | "ar";
  disabled?: boolean;
  variant?: "button" | "icon";
  className?: string;
}

const translations = {
  en: {
    call: "Make Call",
    title: "Initiate Outbound Call",
    subtitle: "Call a customer using your AI voice agent",
    phoneNumber: "Phone Number",
    phoneNumberPlaceholder: "+1234567890",
    phoneNumberHelp: "Enter the phone number in E.164 format",
    selectFromNumber: "Call From",
    selectAgent: "Voice Agent",
    cancel: "Cancel",
    calling: "Initiating call...",
    success: "Call initiated successfully!",
    callId: "Call ID",
    error: "Failed to initiate call",
    noPhoneNumbers: "No phone numbers available",
    noAgents: "No voice agents configured",
    close: "Close",
    tryAgain: "Try Again",
  },
  ar: {
    call: "إجراء مكالمة",
    title: "بدء مكالمة صادرة",
    subtitle: "اتصل بعميل باستخدام وكيلك الصوتي الذكي",
    phoneNumber: "رقم الهاتف",
    phoneNumberPlaceholder: "+966501234567",
    phoneNumberHelp: "أدخل رقم الهاتف بتنسيق E.164",
    selectFromNumber: "الاتصال من",
    selectAgent: "الوكيل الصوتي",
    cancel: "إلغاء",
    calling: "جاري بدء المكالمة...",
    success: "تم بدء المكالمة بنجاح!",
    callId: "معرف المكالمة",
    error: "فشل في بدء المكالمة",
    noPhoneNumbers: "لا توجد أرقام هاتف متاحة",
    noAgents: "لا يوجد وكلاء صوتيون مُكوّنون",
    close: "إغلاق",
    tryAgain: "حاول مرة أخرى",
  },
};

export function OutboundCallButton({
  lang = "en",
  disabled = false,
  variant = "button",
  className = "",
}: OutboundCallButtonProps) {
  const t = translations[lang];
  const [showModal, setShowModal] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [status, setStatus] = useState<
    "idle" | "calling" | "success" | "error"
  >("idle");
  const [error, setError] = useState<string | null>(null);
  const [callId, setCallId] = useState<string | null>(null);

  // Form state
  const [toNumber, setToNumber] = useState("");
  const [fromNumberId, _setFromNumberId] = useState("");

  const handleOpen = () => {
    setShowModal(true);
    setStatus("idle");
    setError(null);
    setCallId(null);
    setToNumber("");
  };

  const handleClose = () => {
    setShowModal(false);
    setStatus("idle");
    setError(null);
  };

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

    if (!toNumber.trim()) {
      setError("Phone number is required");
      return;
    }

    setIsSubmitting(true);
    setStatus("calling");
    setError(null);

    try {
      const response = await fetch("/api/voice/twilio/outbound", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          toNumber: toNumber.trim(),
          fromNumberId: fromNumberId || undefined,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to initiate call");
      }

      setStatus("success");
      setCallId(data.callId);
    } catch (err) {
      setStatus("error");
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setIsSubmitting(false);
    }
  };

  const buttonContent =
    variant === "icon" ? (
      <PhoneOutgoing className="h-5 w-5" />
    ) : (
      <>
        <Phone className="h-4 w-4" />
        {t.call}
      </>
    );

  return (
    <>
      <button
        onClick={handleOpen}
        disabled={disabled}
        className={`${
          variant === "icon"
            ? "p-2 rounded-lg"
            : "flex items-center gap-2 px-4 py-2 rounded-lg"
        } bg-brand-500 text-white hover:bg-brand-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${className}`}
        title={t.call}
      >
        {buttonContent}
      </button>

      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
            {/* Header */}
            <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                  {t.title}
                </h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                  {t.subtitle}
                </p>
              </div>
              <button
                onClick={handleClose}
                className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* Content */}
            <div className="p-6">
              {status === "success" ? (
                <div className="text-center py-4">
                  <div className="mx-auto w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mb-4">
                    <CheckCircle className="h-6 w-6 text-green-600" />
                  </div>
                  <h4 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                    {t.success}
                  </h4>
                  {callId && (
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {t.callId}: {callId.slice(0, 8).toUpperCase()}
                    </p>
                  )}
                  <button
                    onClick={handleClose}
                    className="mt-6 px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors"
                  >
                    {t.close}
                  </button>
                </div>
              ) : status === "error" ? (
                <div className="text-center py-4">
                  <div className="mx-auto w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mb-4">
                    <AlertCircle className="h-6 w-6 text-red-600" />
                  </div>
                  <h4 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                    {t.error}
                  </h4>
                  <p className="text-sm text-red-600 dark:text-red-400 mb-4">
                    {error}
                  </p>
                  <button
                    onClick={() => setStatus("idle")}
                    className="px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors"
                  >
                    {t.tryAgain}
                  </button>
                </div>
              ) : status === "calling" ? (
                <div className="text-center py-8">
                  <Loader2 className="h-8 w-8 animate-spin text-brand-500 mx-auto mb-4" />
                  <p className="text-gray-600 dark:text-gray-400">
                    {t.calling}
                  </p>
                </div>
              ) : (
                <form onSubmit={handleSubmit} className="space-y-4">
                  {/* Phone Number Input */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      {t.phoneNumber} *
                    </label>
                    <input
                      type="tel"
                      value={toNumber}
                      onChange={(e) => setToNumber(e.target.value)}
                      placeholder={t.phoneNumberPlaceholder}
                      className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent dark:bg-gray-700 dark:text-white"
                      required
                    />
                    <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      {t.phoneNumberHelp}
                    </p>
                  </div>

                  {/* Error Display */}
                  {error && (
                    <div className="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg text-sm">
                      {error}
                    </div>
                  )}

                  {/* Actions */}
                  <div className="flex justify-end gap-3 pt-4">
                    <button
                      type="button"
                      onClick={handleClose}
                      className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                    >
                      {t.cancel}
                    </button>
                    <button
                      type="submit"
                      disabled={isSubmitting || !toNumber.trim()}
                      className="px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50 flex items-center gap-2"
                    >
                      <Phone className="h-4 w-4" />
                      {t.call}
                    </button>
                  </div>
                </form>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

export default OutboundCallButton;
