"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  Link2,
  Loader2,
  Lock,
  CreditCard,
  ChevronRight,
  CheckCircle,
  AlertCircle,
  Settings,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";

interface UserLink {
  id: string;
  linkType: string;
  title: string;
  url: string;
  description: string | null;
  icon: string | null;
  sortOrder: number;
}

const LINK_TYPE_ICONS: Record<string, string> = {
  KNOWLEDGE_BASE: "📚",
  AI_AGENT: "🤖",
  AI_VOICE_AGENT: "🎙️",
  WHATSAPP_INTEGRATION: "💬",
  APPOINTMENTS: "📅",
  CUSTOMERS: "👥",
  WAITLISTS: "⏳",
  CALENDAR: "🗓️",
  ANALYTICS: "📈",
  REPORTS: "📋",
  BILLING: "💳",
  DASHBOARD: "📊",
  DOCUMENTATION: "📄",
  SETTINGS: "⚙️",
  SUPPORT: "🆘",
  CUSTOM: "🔗",
};

const LINK_TYPE_COLORS: Record<string, string> = {
  KNOWLEDGE_BASE: "from-blue-500 to-indigo-600",
  AI_AGENT: "from-violet-500 to-purple-600",
  AI_VOICE_AGENT: "from-pink-500 to-rose-600",
  WHATSAPP_INTEGRATION: "from-green-500 to-emerald-600",
  APPOINTMENTS: "from-teal-500 to-cyan-600",
  CUSTOMERS: "from-indigo-500 to-blue-600",
  WAITLISTS: "from-amber-500 to-yellow-600",
  CALENDAR: "from-sky-500 to-blue-600",
  ANALYTICS: "from-emerald-500 to-green-600",
  REPORTS: "from-slate-500 to-zinc-600",
  BILLING: "from-purple-500 to-violet-600",
  DASHBOARD: "from-cyan-500 to-blue-600",
  DOCUMENTATION: "from-amber-500 to-orange-600",
  SETTINGS: "from-gray-500 to-slate-600",
  SUPPORT: "from-red-500 to-pink-600",
  CUSTOM: "from-slate-500 to-gray-600",
};

interface StripeStatus {
  hasKeys: boolean;
  canManageStripe: boolean;
  mode?: "test" | "live";
}

interface LinksPanelProps {
  lang: Lang;
}

export default function LinksPanel({ lang }: LinksPanelProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;
  const router = useRouter();
  const searchParams = useSearchParams();

  const [links, setLinks] = useState<UserLink[]>([]);
  const [loading, setLoading] = useState(true);
  const [stripeStatus, setStripeStatus] = useState<StripeStatus | null>(null);

  const fetchLinks = useCallback(async () => {
    try {
      setLoading(true);
      const response = await fetch("/api/user/links");
      if (response.ok) {
        const data = await response.json();
        setLinks(data.links || []);
      }
    } catch (error) {
      console.error("Failed to fetch links:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchStripeStatus = useCallback(async () => {
    try {
      const response = await fetch("/api/settings/stripe-keys");
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          setStripeStatus({
            hasKeys: data.hasKeys,
            canManageStripe: data.canManageStripe,
            mode: data.mode,
          });
        }
      }
    } catch (error) {
      console.error("Failed to fetch Stripe status:", error);
    }
  }, []);

  useEffect(() => {
    fetchLinks();
    fetchStripeStatus();
  }, [fetchLinks, fetchStripeStatus]);

  const handleGoToSettings = () => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("tab", "settings");
    router.push(`?${params.toString()}`);
  };

  const getIcon = (link: UserLink) => {
    if (link.icon) return link.icon;
    return LINK_TYPE_ICONS[link.linkType] || "🔗";
  };

  const getColor = (linkType: string) => {
    return LINK_TYPE_COLORS[linkType] || LINK_TYPE_COLORS.CUSTOM;
  };

  const getLinkTypeLabel = (linkType: string) => {
    const labels: Record<string, { en: string; ar: string }> = {
      KNOWLEDGE_BASE: { en: "Knowledge Base", ar: "قاعدة المعرفة" },
      AI_AGENT: { en: "AI Agent", ar: "وكيل ذكاء اصطناعي" },
      AI_VOICE_AGENT: { en: "Voice Agent", ar: "وكيل صوتي" },
      WHATSAPP_INTEGRATION: { en: "WhatsApp", ar: "واتساب" },
      APPOINTMENTS: { en: "Appointments", ar: "المواعيد" },
      CUSTOMERS: { en: "Customers", ar: "العملاء" },
      WAITLISTS: { en: "Waitlists", ar: "قوائم الانتظار" },
      CALENDAR: { en: "Calendar", ar: "التقويم" },
      ANALYTICS: { en: "Analytics", ar: "التحليلات" },
      REPORTS: { en: "Reports", ar: "التقارير" },
      BILLING: { en: "Billing", ar: "الفوترة" },
      DASHBOARD: { en: "Dashboard", ar: "لوحة التحكم" },
      DOCUMENTATION: { en: "Documentation", ar: "التوثيق" },
      SETTINGS: { en: "Settings", ar: "الإعدادات" },
      SUPPORT: { en: "Support", ar: "الدعم" },
      CUSTOM: { en: "Custom", ar: "مخصص" },
    };
    return labels[linkType]?.[isAr ? "ar" : "en"] || linkType;
  };

  if (loading) {
    return (
      <div className="space-y-6 animate-fadeIn">
        <div className="flex flex-col gap-2">
          <h2 className="text-2xl font-bold text-slate-900">{dt.linksTitle}</h2>
          <p className="text-slate-600">{dt.linksSubtitle}</p>
        </div>
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-8 h-8 text-brand-green animate-spin" />
        </div>
      </div>
    );
  }

  if (links.length === 0) {
    return (
      <div className="space-y-6 animate-fadeIn">
        <div className="flex flex-col gap-2">
          <h2 className="text-2xl font-bold text-slate-900">{dt.linksTitle}</h2>
          <p className="text-slate-600">{dt.linksSubtitle}</p>
        </div>
        <div className="flex flex-col items-center justify-center rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100 border border-slate-200 py-16 px-8 text-center">
          <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-slate-200 to-slate-300 flex items-center justify-center mb-4">
            <Link2 className="w-8 h-8 text-slate-500" />
          </div>
          <h3 className="text-lg font-semibold text-slate-800 mb-2">
            {dt.noLinks}
          </h3>
          <p className="text-sm text-slate-500 max-w-md">{dt.noLinksDesc}</p>
        </div>
      </div>
    );
  }

  // Translations for Stripe settings card
  const stripeT = {
    quickActions: isAr ? "إجراءات سريعة" : "Quick Actions",
    stripeSettings: isAr ? "إعدادات Stripe" : "Stripe Settings",
    stripeDesc: isAr
      ? "قم بتكوين مفاتيح Stripe لقبول المدفوعات"
      : "Configure your Stripe keys to accept payments",
    configured: isAr ? "تم التكوين" : "Configured",
    notConfigured: isAr ? "غير مكوّن" : "Not Configured",
    testMode: isAr ? "وضع الاختبار" : "Test Mode",
    liveMode: isAr ? "الوضع الحقيقي" : "Live Mode",
    configure: isAr ? "تكوين" : "Configure",
    manage: isAr ? "إدارة" : "Manage",
    managedLinks: isAr ? "الروابط المُدارة" : "Managed Links",
  };

  return (
    <div className="space-y-6 animate-fadeIn">
      <div className="flex flex-col gap-2">
        <h2 className="text-2xl font-bold text-slate-900">{dt.linksTitle}</h2>
        <p className="text-slate-600">{dt.linksSubtitle}</p>
      </div>

      {/* Quick Actions - Stripe Settings Card */}
      {stripeStatus?.canManageStripe && (
        <div className="space-y-4">
          <h3 className="text-lg font-semibold text-slate-800">
            {stripeT.quickActions}
          </h3>
          <button
            onClick={handleGoToSettings}
            className="group w-full sm:w-auto flex items-center gap-4 p-4 rounded-2xl bg-white border border-slate-200 shadow-sm hover:shadow-md hover:border-brand-green transition-all"
          >
            <div className="flex-shrink-0 w-14 h-14 rounded-xl bg-gradient-to-br from-violet-500 to-purple-600 shadow-lg flex items-center justify-center">
              <CreditCard className="w-7 h-7 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-brand-green transition-colors">
                  {stripeT.stripeSettings}
                </h4>
                {stripeStatus.hasKeys ? (
                  <span
                    className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${
                      stripeStatus.mode === "live"
                        ? "bg-amber-100 text-amber-800"
                        : "bg-blue-100 text-blue-800"
                    }`}
                  >
                    <CheckCircle className="w-3 h-3" />
                    {stripeStatus.mode === "live"
                      ? stripeT.liveMode
                      : stripeT.testMode}
                  </span>
                ) : (
                  <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-600">
                    <AlertCircle className="w-3 h-3" />
                    {stripeT.notConfigured}
                  </span>
                )}
              </div>
              <p className="text-sm text-slate-500 mt-0.5">
                {stripeT.stripeDesc}
              </p>
            </div>
            <ChevronRight
              className={`w-5 h-5 text-slate-400 group-hover:text-brand-green transition-colors ${isAr ? "rotate-180" : ""}`}
            />
          </button>
        </div>
      )}

      {/* Managed Links Section */}
      {links.length > 0 && (
        <h3 className="text-lg font-semibold text-slate-800">
          {stripeT.managedLinks}
        </h3>
      )}

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {links.map((link) => (
          <div
            key={link.id}
            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 ${getColor(link.linkType)}`}
            />

            <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 ${getColor(link.linkType)} shadow-lg flex items-center justify-center text-2xl`}
                >
                  {getIcon(link)}
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="font-semibold text-slate-900 truncate">
                    {link.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">
                    {getLinkTypeLabel(link.linkType)}
                  </span>
                </div>
              </div>

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

              {/* Read-only indicator */}
              <div className="flex items-center gap-2 text-xs text-slate-400 bg-slate-50 rounded-lg px-3 py-2">
                <Lock className="w-3 h-3" />
                <span>
                  {isAr ? "مُدار بواسطة المسؤول" : "Managed by administrator"}
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
