"use client";

import { useState } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  Phone,
  Wifi,
  Server,
  CheckCircle2,
  XCircle,
  Loader2,
  RefreshCw,
  ChevronRight,
} from "lucide-react";

interface PhoneConfigData {
  connectionType: "twilio_native" | "custom_sip";
  phoneNumber: string;
  isActive: boolean;
  hasTwilio: boolean;
  hasSip: boolean;
}

interface PhoneConfigPanelProps {
  lang: Lang;
  phoneConfig: PhoneConfigData | null;
  onRefresh: () => void;
}

type ConfigMode = "select" | "twilio" | "sip";

export default function PhoneConfigPanel({
  lang,
  phoneConfig,
  onRefresh,
}: PhoneConfigPanelProps) {
  const isAr = lang === "ar";
  const [mode, setMode] = useState<ConfigMode>("select");
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [testResult, setTestResult] = useState<{
    success: boolean;
    message: string;
  } | null>(null);

  // Twilio form
  const [twilioSid, setTwilioSid] = useState("");
  const [twilioToken, setTwilioToken] = useState("");
  const [twilioPhone, setTwilioPhone] = useState("");

  // SIP form
  const [sipUri, setSipUri] = useState("");
  const [sipUsername, setSipUsername] = useState("");
  const [sipPassword, setSipPassword] = useState("");
  const [sipRegistrar, setSipRegistrar] = useState("");

  const handleSaveTwilio = async () => {
    if (!twilioSid || !twilioToken || !twilioPhone) {
      setError(isAr ? "جميع الحقول مطلوبة" : "All fields are required");
      return;
    }

    setSaving(true);
    setError(null);

    try {
      const res = await fetchWithCSRF("/api/voice-agent/phone", {
        method: "POST",
        body: JSON.stringify({
          connectionType: "twilio_native",
          twilio: {
            twilioAccountSid: twilioSid,
            twilioAuthToken: twilioToken,
            twilioPhoneNumber: twilioPhone,
          },
        }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.error || "Failed to save");
      }

      onRefresh();
      setMode("select");
    } catch (err: unknown) {
      setError(
        err instanceof Error
          ? err.message
          : isAr
            ? "حدث خطأ"
            : "An error occurred",
      );
    } finally {
      setSaving(false);
    }
  };

  const handleSaveSIP = async () => {
    if (!sipUri) {
      setError(isAr ? "عنوان SIP مطلوب" : "SIP URI is required");
      return;
    }

    setSaving(true);
    setError(null);

    try {
      const res = await fetchWithCSRF("/api/voice-agent/phone", {
        method: "POST",
        body: JSON.stringify({
          connectionType: "custom_sip",
          sip: {
            sipUri,
            sipUsername: sipUsername || undefined,
            sipPassword: sipPassword || undefined,
            sipRegistrar: sipRegistrar || undefined,
          },
        }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.error || "Failed to save");
      }

      onRefresh();
      setMode("select");
    } catch (err: unknown) {
      setError(
        err instanceof Error
          ? err.message
          : isAr
            ? "حدث خطأ"
            : "An error occurred",
      );
    } finally {
      setSaving(false);
    }
  };

  const handleTestConnection = async () => {
    setTesting(true);
    setTestResult(null);

    try {
      const res = await fetch("/api/voice-agent/phone?action=test");
      const data = await res.json();

      setTestResult({
        success: data.success,
        message: data.success
          ? isAr
            ? "الاتصال ناجح"
            : "Connection successful"
          : data.error || (isAr ? "فشل الاتصال" : "Connection failed"),
      });
    } catch {
      setTestResult({
        success: false,
        message: isAr ? "فشل اختبار الاتصال" : "Connection test failed",
      });
    } finally {
      setTesting(false);
    }
  };

  // Configured state - show status
  if (phoneConfig) {
    return (
      <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-10 h-10 rounded-xl bg-brand-green/10 flex items-center justify-center">
              <Phone className="w-5 h-5 text-brand-green" />
            </div>
            <div>
              <h3 className="font-semibold text-slate-900">
                {isAr ? "إعدادات الهاتف" : "Phone Configuration"}
              </h3>
              <p className="text-xs text-slate-400">
                {phoneConfig.connectionType === "twilio_native"
                  ? "Twilio"
                  : "Custom SIP"}
              </p>
            </div>
          </div>
          <button
            onClick={onRefresh}
            className="p-2 rounded-lg hover:bg-slate-100 transition-colors"
            title={isAr ? "تحديث" : "Refresh"}
          >
            <RefreshCw className="w-4 h-4 text-slate-400" />
          </button>
        </div>

        <div className="space-y-3">
          <div className="flex items-center justify-between p-3 rounded-xl bg-slate-50">
            <span className="text-sm text-slate-500">
              {isAr ? "رقم الهاتف" : "Phone Number"}
            </span>
            <span className="text-sm font-mono font-medium text-slate-800">
              {phoneConfig.phoneNumber}
            </span>
          </div>
          <div className="flex items-center justify-between p-3 rounded-xl bg-slate-50">
            <span className="text-sm text-slate-500">
              {isAr ? "الحالة" : "Status"}
            </span>
            <span
              className={`inline-flex items-center gap-1.5 text-sm font-medium ${
                phoneConfig.isActive ? "text-green-600" : "text-red-500"
              }`}
            >
              {phoneConfig.isActive ? (
                <CheckCircle2 className="w-4 h-4" />
              ) : (
                <XCircle className="w-4 h-4" />
              )}
              {phoneConfig.isActive
                ? isAr
                  ? "نشط"
                  : "Active"
                : isAr
                  ? "غير نشط"
                  : "Inactive"}
            </span>
          </div>
          <div className="flex items-center justify-between p-3 rounded-xl bg-slate-50">
            <span className="text-sm text-slate-500">
              {isAr ? "نوع الاتصال" : "Connection Type"}
            </span>
            <span className="text-sm font-medium text-slate-800">
              {phoneConfig.connectionType === "twilio_native"
                ? "Twilio"
                : "Custom SIP"}
            </span>
          </div>
        </div>

        {/* Test connection */}
        <div className="mt-4 flex items-center gap-3">
          <button
            onClick={handleTestConnection}
            disabled={testing}
            className="inline-flex items-center gap-2 px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-sm font-medium transition-colors disabled:opacity-50"
          >
            {testing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Wifi className="w-4 h-4" />
            )}
            {isAr ? "اختبار الاتصال" : "Test Connection"}
          </button>
          {testResult && (
            <span
              className={`text-sm ${testResult.success ? "text-green-600" : "text-red-500"}`}
            >
              {testResult.message}
            </span>
          )}
        </div>
      </div>
    );
  }

  // Unconfigured - show setup options
  return (
    <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
      <div className="flex items-center gap-3 mb-6">
        <div className="w-10 h-10 rounded-xl bg-slate-100 flex items-center justify-center">
          <Phone className="w-5 h-5 text-slate-500" />
        </div>
        <div>
          <h3 className="font-semibold text-slate-900">
            {isAr ? "ربط رقم الهاتف" : "Connect Phone Number"}
          </h3>
          <p className="text-xs text-slate-400">
            {isAr
              ? "اختر طريقة الاتصال لوكيلك الصوتي"
              : "Choose a connection method for your voice agent"}
          </p>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-3 rounded-xl bg-red-50 border border-red-200 text-red-600 text-sm">
          {error}
        </div>
      )}

      {mode === "select" && (
        <div className="grid gap-3">
          <button
            type="button"
            onClick={() => {
              setMode("twilio");
              setError(null);
            }}
            className="flex items-center justify-between p-4 rounded-xl border border-slate-200 hover:border-brand-green hover:bg-brand-green/5 transition-colors text-start"
          >
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-red-50 flex items-center justify-center">
                <Phone className="w-5 h-5 text-red-600" />
              </div>
              <div>
                <p className="text-sm font-medium text-slate-800">Twilio</p>
                <p className="text-xs text-slate-400">
                  {isAr
                    ? "ربط رقم هاتف Twilio الخاص بك"
                    : "Connect your Twilio phone number"}
                </p>
              </div>
            </div>
            <ChevronRight className="w-4 h-4 text-slate-400" />
          </button>

          <button
            type="button"
            onClick={() => {
              setMode("sip");
              setError(null);
            }}
            className="flex items-center justify-between p-4 rounded-xl border border-slate-200 hover:border-brand-green hover:bg-brand-green/5 transition-colors text-start"
          >
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-blue-50 flex items-center justify-center">
                <Server className="w-5 h-5 text-blue-600" />
              </div>
              <div>
                <p className="text-sm font-medium text-slate-800">Custom SIP</p>
                <p className="text-xs text-slate-400">
                  {isAr
                    ? "إعداد اتصال SIP مخصص"
                    : "Configure a custom SIP connection"}
                </p>
              </div>
            </div>
            <ChevronRight className="w-4 h-4 text-slate-400" />
          </button>
        </div>
      )}

      {/* Twilio Form */}
      {mode === "twilio" && (
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1.5">
              Account SID
            </label>
            <input
              type="text"
              value={twilioSid}
              onChange={(e) => setTwilioSid(e.target.value)}
              placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
              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 font-mono"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1.5">
              Auth Token
            </label>
            <input
              type="password"
              value={twilioToken}
              onChange={(e) => setTwilioToken(e.target.value)}
              placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
              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 font-mono"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1.5">
              {isAr ? "رقم الهاتف" : "Phone Number"}
            </label>
            <input
              type="tel"
              value={twilioPhone}
              onChange={(e) => setTwilioPhone(e.target.value)}
              placeholder="+1234567890"
              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 font-mono"
            />
          </div>

          <div className="flex items-center justify-between pt-2">
            <button
              type="button"
              onClick={() => {
                setMode("select");
                setError(null);
              }}
              className="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-sm font-medium transition-colors"
            >
              {isAr ? "رجوع" : "Back"}
            </button>
            <button
              type="button"
              onClick={handleSaveTwilio}
              disabled={saving}
              className="inline-flex items-center gap-2 px-6 py-2.5 bg-brand-green hover:bg-brand-greenHover text-white rounded-xl text-sm font-medium transition-colors disabled:opacity-50"
            >
              {saving ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Phone className="w-4 h-4" />
              )}
              {saving
                ? isAr
                  ? "جاري الحفظ..."
                  : "Saving..."
                : isAr
                  ? "ربط Twilio"
                  : "Connect Twilio"}
            </button>
          </div>
        </div>
      )}

      {/* SIP Form */}
      {mode === "sip" && (
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1.5">
              SIP URI <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              value={sipUri}
              onChange={(e) => setSipUri(e.target.value)}
              placeholder="sip:user@provider.com"
              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 font-mono"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">
                {isAr ? "اسم المستخدم" : "Username"}
              </label>
              <input
                type="text"
                value={sipUsername}
                onChange={(e) => setSipUsername(e.target.value)}
                placeholder={isAr ? "اختياري" : "Optional"}
                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>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">
                {isAr ? "كلمة المرور" : "Password"}
              </label>
              <input
                type="password"
                value={sipPassword}
                onChange={(e) => setSipPassword(e.target.value)}
                placeholder={isAr ? "اختياري" : "Optional"}
                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>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1.5">
              Registrar
            </label>
            <input
              type="text"
              value={sipRegistrar}
              onChange={(e) => setSipRegistrar(e.target.value)}
              placeholder="sip:registrar.provider.com"
              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 font-mono"
            />
          </div>

          <div className="flex items-center justify-between pt-2">
            <button
              type="button"
              onClick={() => {
                setMode("select");
                setError(null);
              }}
              className="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-sm font-medium transition-colors"
            >
              {isAr ? "رجوع" : "Back"}
            </button>
            <button
              type="button"
              onClick={handleSaveSIP}
              disabled={saving}
              className="inline-flex items-center gap-2 px-6 py-2.5 bg-brand-green hover:bg-brand-greenHover text-white rounded-xl text-sm font-medium transition-colors disabled:opacity-50"
            >
              {saving ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Server className="w-4 h-4" />
              )}
              {saving
                ? isAr
                  ? "جاري الحفظ..."
                  : "Saving..."
                : isAr
                  ? "ربط SIP"
                  : "Connect SIP"}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
