"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Phone, ChevronRight } from "lucide-react";
import type { Lang } from "@/lib/config";

interface VoiceAgentQuickLinkProps {
  lang: Lang;
}

interface VoiceAgentStatus {
  configured: boolean;
  id: string | null;
}

export default function VoiceAgentQuickLink({
  lang,
}: VoiceAgentQuickLinkProps) {
  const isAr = lang === "ar";
  const router = useRouter();
  const searchParams = useSearchParams();
  const [status, setStatus] = useState<VoiceAgentStatus | null>(null);
  const [loading, setLoading] = useState(true);

  const t = {
    title: isAr ? "الوكيل الصوتي بالذكاء الاصطناعي" : "AI Voice Agent",
    description: isAr
      ? "إدارة إعدادات الوكيل الصوتي الخاص بك"
      : "Manage your AI voice agent settings",
    active: isAr ? "نشط" : "Active",
    manage: isAr ? "إدارة" : "Manage",
  };

  const fetchVoiceAgentStatus = useCallback(async () => {
    try {
      setLoading(true);
      const response = await fetch("/api/dashboard/voice-agents");
      if (response.ok) {
        const data = await response.json();
        if (data.success && data.voiceAgent?.agent) {
          setStatus({
            configured: data.voiceAgent.agent.configured,
            id: data.voiceAgent.agent.id,
          });
        }
      }
    } catch (error) {
      console.error("Failed to fetch voice agent status:", error);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleClick = () => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("tab", "voice-agent");
    router.push(`?${params.toString()}`);
  };

  // Don't render if loading or voice agent is not configured
  if (loading || !status?.configured) {
    return null;
  }

  return (
    <button
      onClick={handleClick}
      className="group flex items-center gap-4 rounded-xl bg-gradient-to-r from-pink-500/10 to-rose-500/10 border border-pink-200/50 px-5 py-4 text-left hover:border-pink-300 hover:shadow-lg hover:shadow-pink-500/10 transition-all duration-300"
    >
      <div className="flex-shrink-0 w-12 h-12 rounded-xl bg-gradient-to-br from-pink-500 to-rose-600 shadow-lg shadow-pink-500/25 flex items-center justify-center">
        <Phone className="w-6 h-6 text-white" />
      </div>
      <div className={`flex-1 ${isAr ? "text-right" : "text-left"}`}>
        <div className="flex items-center gap-2">
          <h4 className="font-semibold text-slate-900 group-hover:text-pink-600 transition-colors">
            {t.title}
          </h4>
          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800">
            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
            {t.active}
          </span>
        </div>
        <p className="text-sm text-slate-500 mt-0.5">{t.description}</p>
      </div>
      <ChevronRight
        className={`w-5 h-5 text-slate-400 group-hover:text-pink-500 transition-colors ${isAr ? "rotate-180" : ""}`}
      />
    </button>
  );
}

// Named export for use in LinksPanel with loading state
export function VoiceAgentLinkCard({
  lang,
  onNavigate,
}: {
  lang: Lang;
  onNavigate: () => void;
}) {
  const isAr = lang === "ar";

  const t = {
    title: isAr ? "الوكيل الصوتي" : "Voice Agent",
    type: isAr ? "وكيل صوتي" : "Voice Agent",
    description: isAr
      ? "وكيلك الصوتي بالذكاء الاصطناعي نشط ويستقبل المكالمات"
      : "Your AI voice agent is active and receiving calls",
  };

  return (
    <div className="group relative overflow-hidden rounded-2xl bg-white border border-slate-200 shadow-sm transition-all duration-300">
      {/* Gradient accent bar */}
      <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-pink-500 to-rose-600" />

      <div className="p-5">
        {/* Header with icon and title */}
        <div className="flex items-start gap-4 mb-3">
          <div className="flex-shrink-0 w-12 h-12 rounded-xl bg-gradient-to-br from-pink-500 to-rose-600 shadow-lg flex items-center justify-center text-2xl">
            🎙️
          </div>
          <div className="flex-1 min-w-0">
            <h3 className="font-semibold text-slate-900 truncate">{t.title}</h3>
            <span className="inline-flex items-center px-2 py-0.5 mt-1 text-xs font-medium bg-slate-100 text-slate-600 rounded-full">
              {t.type}
            </span>
          </div>
        </div>

        {/* Description */}
        <p className="text-sm text-slate-500 mb-3 line-clamp-2">
          {t.description}
        </p>

        {/* Active indicator and manage button */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 text-xs text-emerald-600 bg-emerald-50 rounded-lg px-3 py-2">
            <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
            <span className="font-medium">{isAr ? "نشط" : "Active"}</span>
          </div>
          <button
            onClick={onNavigate}
            className="text-sm font-medium text-pink-600 hover:text-pink-700 transition-colors"
          >
            {isAr ? "إدارة" : "Manage"} →
          </button>
        </div>
      </div>
    </div>
  );
}
