"use client";

/**
 * Phone Numbers Management Panel
 *
 * Dashboard component for managing Twilio phone numbers
 * connected to ElevenLabs voice agents
 */

import React, { useState, useEffect, useCallback } from "react";
import {
  Phone,
  Plus,
  Trash2,
  RefreshCw,
  Check,
  AlertCircle,
  Loader2,
} from "lucide-react";

interface PhoneNumber {
  id: string;
  phoneNumber: string;
  friendlyName: string | null;
  status: "active" | "inactive" | "pending" | "error";
  elevenLabsAgentId: string | null;
  inboundEnabled: boolean;
  outboundEnabled: boolean;
  createdAt: string;
}

interface PhoneNumbersPanelProps {
  userId: string;
  lang?: "en" | "ar";
}

const translations = {
  en: {
    title: "Phone Numbers",
    subtitle: "Manage your voice agent phone numbers",
    addNumber: "Add Phone Number",
    noNumbers: "No phone numbers configured",
    noNumbersDesc:
      "Add a Twilio phone number to enable voice calls with your AI agent.",
    status: "Status",
    inbound: "Inbound",
    outbound: "Outbound",
    actions: "Actions",
    delete: "Delete",
    sync: "Sync",
    loading: "Loading...",
    error: "Error loading phone numbers",
    retry: "Retry",
    active: "Active",
    inactive: "Inactive",
    pending: "Pending",
    enabled: "Enabled",
    disabled: "Disabled",
    confirmDelete: "Are you sure you want to delete this phone number?",
    deleteSuccess: "Phone number deleted successfully",
    deleteError: "Failed to delete phone number",
    syncSuccess: "Phone numbers synced successfully",
    syncError: "Failed to sync phone numbers",
  },
  ar: {
    title: "أرقام الهاتف",
    subtitle: "إدارة أرقام هاتف الوكيل الصوتي",
    addNumber: "إضافة رقم هاتف",
    noNumbers: "لا توجد أرقام هاتف مُكوّنة",
    noNumbersDesc:
      "أضف رقم هاتف Twilio لتمكين المكالمات الصوتية مع وكيلك الذكي.",
    status: "الحالة",
    inbound: "وارد",
    outbound: "صادر",
    actions: "الإجراءات",
    delete: "حذف",
    sync: "مزامنة",
    loading: "جاري التحميل...",
    error: "خطأ في تحميل أرقام الهاتف",
    retry: "إعادة المحاولة",
    active: "نشط",
    inactive: "غير نشط",
    pending: "قيد الانتظار",
    enabled: "مُفعّل",
    disabled: "مُعطّل",
    confirmDelete: "هل أنت متأكد من رغبتك في حذف هذا الرقم؟",
    deleteSuccess: "تم حذف رقم الهاتف بنجاح",
    deleteError: "فشل في حذف رقم الهاتف",
    syncSuccess: "تم مزامنة أرقام الهاتف بنجاح",
    syncError: "فشل في مزامنة أرقام الهاتف",
  },
};

export function PhoneNumbersPanel({
  userId: _userId,
  lang = "en",
}: PhoneNumbersPanelProps) {
  const t = translations[lang];
  const [phoneNumbers, setPhoneNumbers] = useState<PhoneNumber[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isSyncing, setIsSyncing] = useState(false);
  const [showAddModal, setShowAddModal] = useState(false);

  const fetchPhoneNumbers = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      const response = await fetch("/api/voice/twilio/numbers");
      if (!response.ok) {
        throw new Error("Failed to fetch phone numbers");
      }

      const data = await response.json();
      setPhoneNumbers(data.phoneNumbers || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchPhoneNumbers();
  }, [fetchPhoneNumbers]);

  const handleSync = async () => {
    try {
      setIsSyncing(true);
      const response = await fetch("/api/voice/twilio/numbers", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "sync" }),
      });

      if (!response.ok) {
        throw new Error("Failed to sync");
      }

      await fetchPhoneNumbers();
    } catch {
      setError(t.syncError);
    } finally {
      setIsSyncing(false);
    }
  };

  const handleDelete = async (phoneNumberId: string) => {
    if (!confirm(t.confirmDelete)) return;

    try {
      const response = await fetch(
        `/api/voice/twilio/numbers/${phoneNumberId}`,
        {
          method: "DELETE",
        },
      );

      if (!response.ok) {
        throw new Error("Failed to delete");
      }

      setPhoneNumbers((prev) => prev.filter((p) => p.id !== phoneNumberId));
    } catch {
      setError(t.deleteError);
    }
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      active: { color: "bg-green-100 text-green-800", label: t.active },
      inactive: { color: "bg-gray-100 text-gray-800", label: t.inactive },
      pending: { color: "bg-yellow-100 text-yellow-800", label: t.pending },
      error: { color: "bg-red-100 text-red-800", label: "Error" },
    };

    const config =
      statusConfig[status as keyof typeof statusConfig] ||
      statusConfig.inactive;

    return (
      <span
        className={`px-2 py-1 rounded-full text-xs font-medium ${config.color}`}
      >
        {config.label}
      </span>
    );
  };

  if (isLoading) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <div className="flex items-center justify-center py-8">
          <Loader2 className="h-6 w-6 animate-spin text-brand-500" />
          <span className="ml-2 text-gray-600 dark:text-gray-400">
            {t.loading}
          </span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <div className="flex flex-col items-center justify-center py-8">
          <AlertCircle className="h-8 w-8 text-red-500 mb-2" />
          <p className="text-red-600 dark:text-red-400 mb-4">{t.error}</p>
          <button
            onClick={fetchPhoneNumbers}
            className="px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors"
          >
            {t.retry}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <Phone className="h-5 w-5 text-brand-500" />
              {t.title}
            </h3>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              {t.subtitle}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={handleSync}
              disabled={isSyncing}
              className="p-2 text-gray-600 hover:text-brand-500 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
              title={t.sync}
            >
              <RefreshCw
                className={`h-5 w-5 ${isSyncing ? "animate-spin" : ""}`}
              />
            </button>
            <button
              onClick={() => setShowAddModal(true)}
              className="flex items-center gap-2 px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors"
            >
              <Plus className="h-4 w-4" />
              {t.addNumber}
            </button>
          </div>
        </div>
      </div>

      {/* Content */}
      {phoneNumbers.length === 0 ? (
        <div className="px-6 py-12 text-center">
          <Phone className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h4 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            {t.noNumbers}
          </h4>
          <p className="text-gray-600 dark:text-gray-400 mb-6 max-w-md mx-auto">
            {t.noNumbersDesc}
          </p>
          <button
            onClick={() => setShowAddModal(true)}
            className="inline-flex items-center gap-2 px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors"
          >
            <Plus className="h-4 w-4" />
            {t.addNumber}
          </button>
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 dark:bg-gray-700/50">
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Phone Number
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t.status}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t.inbound}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t.outbound}
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t.actions}
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
              {phoneNumbers.map((phone) => (
                <tr
                  key={phone.id}
                  className="hover:bg-gray-50 dark:hover:bg-gray-700/30"
                >
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div>
                      <div className="font-medium text-gray-900 dark:text-white">
                        {phone.phoneNumber}
                      </div>
                      {phone.friendlyName && (
                        <div className="text-sm text-gray-500 dark:text-gray-400">
                          {phone.friendlyName}
                        </div>
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {getStatusBadge(phone.status)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {phone.inboundEnabled ? (
                      <span className="flex items-center text-green-600">
                        <Check className="h-4 w-4 mr-1" />
                        {t.enabled}
                      </span>
                    ) : (
                      <span className="text-gray-500">{t.disabled}</span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {phone.outboundEnabled ? (
                      <span className="flex items-center text-green-600">
                        <Check className="h-4 w-4 mr-1" />
                        {t.enabled}
                      </span>
                    ) : (
                      <span className="text-gray-500">{t.disabled}</span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-right">
                    <button
                      onClick={() => handleDelete(phone.id)}
                      className="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                      title={t.delete}
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Add Phone Number Modal would go here */}
      {showAddModal && (
        <AddPhoneNumberModal
          onClose={() => setShowAddModal(false)}
          onSuccess={() => {
            setShowAddModal(false);
            fetchPhoneNumbers();
          }}
          lang={lang}
        />
      )}
    </div>
  );
}

interface AddPhoneNumberModalProps {
  onClose: () => void;
  onSuccess: () => void;
  lang: "en" | "ar";
}

function AddPhoneNumberModal({
  onClose,
  onSuccess,
  lang,
}: AddPhoneNumberModalProps) {
  const [phoneNumber, setPhoneNumber] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError(null);

    try {
      const response = await fetch("/api/voice/twilio/numbers", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "import",
          phoneNumber,
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to add phone number");
      }

      onSuccess();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md mx-4">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
            {lang === "ar" ? "إضافة رقم هاتف" : "Add Phone Number"}
          </h3>
        </div>

        <form onSubmit={handleSubmit} className="p-6">
          {error && (
            <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg text-sm">
              {error}
            </div>
          )}

          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              {lang === "ar" ? "رقم الهاتف (E.164)" : "Phone Number (E.164)"}
            </label>
            <input
              type="tel"
              value={phoneNumber}
              onChange={(e) => setPhoneNumber(e.target.value)}
              placeholder="+1234567890"
              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">
              {lang === "ar"
                ? "أدخل رقم الهاتف بتنسيق E.164 (مثال: +966501234567)"
                : "Enter the phone number in E.164 format (e.g., +966501234567)"}
            </p>
          </div>

          <div className="flex justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              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"
            >
              {lang === "ar" ? "إلغاء" : "Cancel"}
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              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"
            >
              {isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
              {lang === "ar" ? "إضافة" : "Add"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default PhoneNumbersPanel;
