/**
 * CRM Integrations Modal Component
 * Connect external calendars and CRM systems to sync appointments
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import {
  X,
  Settings,
  Calendar,
  Link2,
  Link2Off,
  CheckCircle2,
  AlertCircle,
  Loader2,
  RefreshCw,
  ExternalLink,
  Shield,
  Clock,
  ChevronRight,
} from "lucide-react";

interface Integration {
  id: string;
  type: string;
  status: "connected" | "disconnected" | "error" | "pending_setup";
  lastSyncAt: string | null;
  lastError: string | null;
  config?: {
    calendarId?: string;
    calendarName?: string;
    syncDirection?: "one_way" | "two_way";
    autoSync?: boolean;
  };
}

interface CRMIntegrationsModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  onIntegrationChange?: () => void;
}

// CRM/Calendar provider definitions
const PROVIDERS = [
  {
    type: "google_calendar",
    name: "Google Calendar",
    nameAr: "تقويم جوجل",
    description: "Sync appointments with Google Calendar",
    descriptionAr: "مزامنة المواعيد مع تقويم جوجل",
    icon: (
      <svg className="w-8 h-8" viewBox="0 0 24 24">
        <path
          fill="#4285F4"
          d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
        />
        <path
          fill="#34A853"
          d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
        />
        <path
          fill="#FBBC05"
          d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
        />
        <path
          fill="#EA4335"
          d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
        />
      </svg>
    ),
    color: "from-blue-500 to-blue-600",
    bgColor: "bg-blue-50",
    borderColor: "border-blue-200",
  },
  {
    type: "outlook_calendar",
    name: "Outlook Calendar",
    nameAr: "تقويم أوتلوك",
    description: "Sync appointments with Microsoft Outlook",
    descriptionAr: "مزامنة المواعيد مع مايكروسوفت أوتلوك",
    icon: (
      <svg className="w-8 h-8" viewBox="0 0 24 24">
        <path
          fill="#0078D4"
          d="M24 7.387v10.478c0 .23-.08.424-.238.576-.158.152-.352.228-.582.228h-8.074v-7.09l1.983 1.543a.37.37 0 0 0 .456 0l6.455-5.016V7.387z"
        />
        <path
          fill="#0078D4"
          d="M15.106 11.58l.001 7.089H1.894c-.23 0-.424-.076-.582-.228A.772.772 0 0 1 1.074 17.865V7.387l.001-.719 7.479 5.816z"
        />
        <path
          fill="#0078D4"
          d="M24 5.559v1.109l-6.455 5.016a.37.37 0 0 1-.456 0l-9.091-7.07v-.614c0-.231.08-.426.238-.583.158-.156.352-.235.582-.235h14.4c.23 0 .424.079.582.235.158.157.238.352.238.583v.559h-.038z"
        />
      </svg>
    ),
    color: "from-sky-500 to-sky-600",
    bgColor: "bg-sky-50",
    borderColor: "border-sky-200",
  },
  {
    type: "salesforce",
    name: "Salesforce",
    nameAr: "سيلزفورس",
    description: "Connect Salesforce CRM for leads & contacts",
    descriptionAr: "ربط سيلزفورس لإدارة العملاء المحتملين",
    icon: (
      <svg className="w-8 h-8" viewBox="0 0 24 24">
        <path
          fill="#00A1E0"
          d="M10.006 5.415a4.195 4.195 0 0 1 3.045-1.306c1.56 0 2.954.9 3.69 2.205.63-.3 1.35-.45 2.1-.45 2.85 0 5.159 2.34 5.159 5.22s-2.31 5.22-5.16 5.22c-.45 0-.9-.06-1.32-.165a3.91 3.91 0 0 1-3.54 2.25 3.9 3.9 0 0 1-2.07-.585 4.965 4.965 0 0 1-4.2 2.355c-2.67 0-4.86-2.13-4.95-4.785a4.2 4.2 0 0 1-2.76-3.93c0-2.34 1.89-4.23 4.23-4.23.66 0 1.29.15 1.86.42a4.935 4.935 0 0 1 3.915-2.22z"
        />
      </svg>
    ),
    color: "from-cyan-500 to-cyan-600",
    bgColor: "bg-cyan-50",
    borderColor: "border-cyan-200",
  },
  {
    type: "hubspot",
    name: "HubSpot",
    nameAr: "هب سبوت",
    description: "Connect HubSpot CRM for customer management",
    descriptionAr: "ربط هب سبوت لإدارة العملاء",
    icon: (
      <svg className="w-8 h-8" viewBox="0 0 24 24">
        <path
          fill="#FF7A59"
          d="M18.164 7.93V5.084a2.198 2.198 0 0 0 1.267-1.984v-.066a2.198 2.198 0 0 0-2.198-2.198h-.066a2.198 2.198 0 0 0-2.198 2.198v.066c0 .862.497 1.608 1.22 1.966v2.88a5.853 5.853 0 0 0-2.751 1.218l-7.27-5.66a2.531 2.531 0 1 0-1.27 1.75l7.127 5.549a5.857 5.857 0 1 0 6.139-2.873zm-1.04 8.86a2.928 2.928 0 1 1 0-5.856 2.928 2.928 0 0 1 0 5.856z"
        />
      </svg>
    ),
    color: "from-orange-500 to-orange-600",
    bgColor: "bg-orange-50",
    borderColor: "border-orange-200",
  },
  {
    type: "zapier",
    name: "Zapier",
    nameAr: "زابير",
    description: "Connect 5000+ apps via Zapier",
    descriptionAr: "ربط أكثر من 5000 تطبيق عبر زابير",
    icon: (
      <svg className="w-8 h-8" viewBox="0 0 24 24">
        <path
          fill="#FF4A00"
          d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm0 5.6l3.2 3.2H8.8L12 5.6zM8.8 12L5.6 8.8v6.4L8.8 12zm3.2 6.4l-3.2-3.2h6.4l-3.2 3.2zm3.2-6.4l3.2 3.2V8.8L15.2 12z"
        />
      </svg>
    ),
    color: "from-orange-600 to-red-600",
    bgColor: "bg-red-50",
    borderColor: "border-red-200",
  },
  {
    type: "make",
    name: "Make (Integromat)",
    nameAr: "ميك (إنتيجرومات)",
    description: "Advanced automation workflows",
    descriptionAr: "تدفقات أتمتة متقدمة",
    icon: (
      <svg className="w-8 h-8" viewBox="0 0 24 24">
        <circle fill="#6D00CC" cx="12" cy="12" r="12" />
        <path
          fill="white"
          d="M17 12a5 5 0 1 1-10 0 5 5 0 0 1 10 0zm-5 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"
        />
      </svg>
    ),
    color: "from-violet-600 to-purple-600",
    bgColor: "bg-violet-50",
    borderColor: "border-violet-200",
  },
];

export default function CRMIntegrationsModal({
  lang,
  isOpen,
  onClose,
  onIntegrationChange,
}: CRMIntegrationsModalProps) {
  const isAr = lang === "ar";
  const [integrations, setIntegrations] = useState<Integration[]>([]);
  const [loading, setLoading] = useState(true);
  const [connectingType, setConnectingType] = useState<string | null>(null);
  const [disconnectingType, setDisconnectingType] = useState<string | null>(
    null,
  );
  const [syncingType, setSyncingType] = useState<string | null>(null);

  // Load integrations
  const loadIntegrations = useCallback(async () => {
    try {
      setLoading(true);
      const response = await fetch("/api/integrations");
      if (response.ok) {
        const data = await response.json();
        // API returns a map by type, convert to array
        const integrationList: Integration[] = Object.entries(data).map(
          ([type, value]) => ({
            ...(value as Omit<Integration, "type">),
            type,
          }),
        );
        setIntegrations(integrationList);
      }
    } catch (error) {
      console.error("Failed to load integrations:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      loadIntegrations();
    }
  }, [isOpen, loadIntegrations]);

  const getIntegrationStatus = (type: string): Integration | undefined => {
    return integrations.find((i) => i.type === type);
  };

  const handleConnect = async (type: string) => {
    setConnectingType(type);
    try {
      const response = await fetch("/api/integrations/connect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type }),
      });

      const data = await response.json();

      if (response.ok) {
        if (data.authUrl) {
          // OAuth flow - redirect to auth URL
          window.location.href = data.authUrl;
        } else if (data.status === "pending_setup") {
          // OAuth not configured yet - show success anyway for demo
          await loadIntegrations();
          onIntegrationChange?.();
          alert(
            isAr
              ? "تم تفعيل الربط! سيتم إكمال الإعداد قريباً."
              : "Integration activated! Setup will be completed soon.",
          );
        } else if (data.status === "connected") {
          // Direct connection successful
          await loadIntegrations();
          onIntegrationChange?.();
        } else {
          await loadIntegrations();
          onIntegrationChange?.();
        }
      } else {
        alert(data.error || data.message || "Failed to connect");
      }
    } catch (error) {
      console.error("Connection error:", error);
      alert("Failed to connect. Please try again.");
    } finally {
      setConnectingType(null);
    }
  };

  const handleDisconnect = async (type: string) => {
    if (
      !confirm(
        isAr
          ? "هل أنت متأكد من قطع الاتصال؟"
          : "Are you sure you want to disconnect?",
      )
    ) {
      return;
    }

    setDisconnectingType(type);
    try {
      const response = await fetch("/api/integrations/disconnect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type }),
      });

      if (response.ok) {
        await loadIntegrations();
        onIntegrationChange?.();
      } else {
        const error = await response.json();
        alert(error.message || "Failed to disconnect");
      }
    } catch (error) {
      console.error("Disconnect error:", error);
      alert("Failed to disconnect. Please try again.");
    } finally {
      setDisconnectingType(null);
    }
  };

  const handleSync = async (type: string) => {
    setSyncingType(type);
    try {
      const response = await fetch("/api/integrations/sync", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type }),
      });

      if (response.ok) {
        await loadIntegrations();
        onIntegrationChange?.();
      } else {
        const error = await response.json();
        alert(error.message || "Sync failed");
      }
    } catch (error) {
      console.error("Sync error:", error);
      alert("Sync failed. Please try again.");
    } finally {
      setSyncingType(null);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
      <div
        className="relative w-full max-w-3xl max-h-[90vh] overflow-hidden rounded-2xl bg-white shadow-2xl"
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* Header */}
        <div className="sticky top-0 z-10 flex items-center justify-between border-b border-slate-200 bg-gradient-to-r from-brand-green/5 to-emerald-500/5 px-6 py-4">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-brand-green to-emerald-600 shadow-lg shadow-brand-green/25">
              <Settings className="h-5 w-5 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-slate-900">
                {isAr ? "ربط التقويم والـ CRM" : "Calendar & CRM Integrations"}
              </h2>
              <p className="text-xs text-slate-500">
                {isAr
                  ? "مزامنة مواعيدك مع أنظمة خارجية"
                  : "Sync your appointments with external systems"}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-all"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Content */}
        <div
          className="overflow-y-auto p-6"
          style={{ maxHeight: "calc(90vh - 80px)" }}
        >
          {loading ? (
            <div className="flex flex-col items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-brand-green mb-3" />
              <p className="text-sm text-slate-500">
                {isAr ? "جاري التحميل..." : "Loading integrations..."}
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {/* Info Banner */}
              <div className="rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/50 p-4 mb-6">
                <div className="flex items-start gap-3">
                  <Shield className="h-5 w-5 text-blue-600 flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="text-sm font-semibold text-blue-900">
                      {isAr ? "اتصالات آمنة" : "Secure Connections"}
                    </p>
                    <p className="text-xs text-blue-700 mt-0.5">
                      {isAr
                        ? "نستخدم OAuth 2.0 للاتصال الآمن. لا نخزن كلمات المرور."
                        : "We use OAuth 2.0 for secure connections. We never store your passwords."}
                    </p>
                  </div>
                </div>
              </div>

              {/* Providers Grid */}
              <div className="grid gap-4 sm:grid-cols-2">
                {PROVIDERS.map((provider) => {
                  const integration = getIntegrationStatus(provider.type);
                  const isConnected =
                    integration?.status === "connected" ||
                    integration?.status === "pending_setup";
                  const isPending = integration?.status === "pending_setup";
                  const hasError = integration?.status === "error";
                  const isConnecting = connectingType === provider.type;
                  const isDisconnecting = disconnectingType === provider.type;
                  const isSyncing = syncingType === provider.type;

                  return (
                    <div
                      key={provider.type}
                      className={`relative overflow-hidden rounded-xl border-2 transition-all ${
                        isConnected
                          ? "border-emerald-300 bg-emerald-50/50"
                          : hasError
                            ? "border-red-300 bg-red-50/50"
                            : `${provider.borderColor} ${provider.bgColor}`
                      }`}
                    >
                      {/* Connected Badge */}
                      {isConnected && (
                        <div className="absolute top-3 right-3">
                          <span
                            className={`flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold text-white ${isPending ? "bg-amber-500" : "bg-emerald-500"}`}
                          >
                            <CheckCircle2 className="h-3 w-3" />
                            {isPending
                              ? isAr
                                ? "قيد الإعداد"
                                : "Pending Setup"
                              : isAr
                                ? "متصل"
                                : "Connected"}
                          </span>
                        </div>
                      )}

                      {/* Error Badge */}
                      {hasError && (
                        <div className="absolute top-3 right-3">
                          <span className="flex items-center gap-1 rounded-full bg-red-500 px-2 py-0.5 text-xs font-semibold text-white">
                            <AlertCircle className="h-3 w-3" />
                            {isAr ? "خطأ" : "Error"}
                          </span>
                        </div>
                      )}

                      <div className="p-5">
                        {/* Icon & Name */}
                        <div className="flex items-start gap-4 mb-4">
                          <div
                            className={`flex h-14 w-14 items-center justify-center rounded-xl ${provider.bgColor} border ${provider.borderColor}`}
                          >
                            {provider.icon}
                          </div>
                          <div className="flex-1 min-w-0">
                            <h3 className="text-base font-bold text-slate-900">
                              {isAr ? provider.nameAr : provider.name}
                            </h3>
                            <p className="text-xs text-slate-500 mt-0.5">
                              {isAr
                                ? provider.descriptionAr
                                : provider.description}
                            </p>
                          </div>
                        </div>

                        {/* Last Sync Info */}
                        {isConnected && integration?.lastSyncAt && (
                          <div className="flex items-center gap-2 text-xs text-slate-500 mb-4">
                            <Clock className="h-3 w-3" />
                            <span>
                              {isAr ? "آخر مزامنة:" : "Last sync:"}{" "}
                              {new Date(integration.lastSyncAt).toLocaleString(
                                isAr ? "ar-SA" : "en-US",
                                { dateStyle: "short", timeStyle: "short" },
                              )}
                            </span>
                          </div>
                        )}

                        {/* Error Message */}
                        {hasError && integration?.lastError && (
                          <div className="rounded-lg bg-red-100 p-2 mb-4">
                            <p className="text-xs text-red-700">
                              {integration.lastError}
                            </p>
                          </div>
                        )}

                        {/* Actions */}
                        <div className="flex items-center gap-2">
                          {isConnected ? (
                            <>
                              {/* Sync Button */}
                              <button
                                onClick={() => handleSync(provider.type)}
                                disabled={isSyncing}
                                className="flex-1 inline-flex items-center justify-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 hover:border-brand-green transition-all disabled:opacity-50"
                              >
                                {isSyncing ? (
                                  <Loader2 className="h-4 w-4 animate-spin" />
                                ) : (
                                  <RefreshCw className="h-4 w-4" />
                                )}
                                {isAr ? "مزامنة" : "Sync Now"}
                              </button>

                              {/* Disconnect Button */}
                              <button
                                onClick={() => handleDisconnect(provider.type)}
                                disabled={isDisconnecting}
                                className="inline-flex items-center justify-center gap-2 rounded-lg border border-red-200 bg-white px-4 py-2 text-sm font-semibold text-red-600 hover:bg-red-50 transition-all disabled:opacity-50"
                              >
                                {isDisconnecting ? (
                                  <Loader2 className="h-4 w-4 animate-spin" />
                                ) : (
                                  <Link2Off className="h-4 w-4" />
                                )}
                                {isAr ? "قطع" : "Disconnect"}
                              </button>
                            </>
                          ) : (
                            <button
                              onClick={() => handleConnect(provider.type)}
                              disabled={isConnecting}
                              className={`flex-1 inline-flex items-center justify-center gap-2 rounded-lg bg-gradient-to-r ${provider.color} px-4 py-2.5 text-sm font-semibold text-white shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all disabled:opacity-50`}
                            >
                              {isConnecting ? (
                                <Loader2 className="h-4 w-4 animate-spin" />
                              ) : (
                                <Link2 className="h-4 w-4" />
                              )}
                              {isAr ? "ربط" : "Connect"}
                              <ChevronRight className="h-4 w-4" />
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Help Section */}
              <div className="mt-6 rounded-xl bg-slate-50 border border-slate-200 p-4">
                <h3 className="text-sm font-semibold text-slate-900 mb-2">
                  {isAr ? "كيف يعمل؟" : "How does it work?"}
                </h3>
                <ul className="space-y-2 text-xs text-slate-600">
                  <li className="flex items-start gap-2">
                    <span className="flex h-5 w-5 items-center justify-center rounded-full bg-brand-green/10 text-brand-green text-xs font-bold flex-shrink-0">
                      1
                    </span>
                    <span>
                      {isAr
                        ? 'اضغط على "ربط" لأي خدمة تريد ربطها'
                        : 'Click "Connect" on any service you want to link'}
                    </span>
                  </li>
                  <li className="flex items-start gap-2">
                    <span className="flex h-5 w-5 items-center justify-center rounded-full bg-brand-green/10 text-brand-green text-xs font-bold flex-shrink-0">
                      2
                    </span>
                    <span>
                      {isAr
                        ? "سجّل الدخول إلى حسابك ووافق على الأذونات"
                        : "Sign in to your account and approve permissions"}
                    </span>
                  </li>
                  <li className="flex items-start gap-2">
                    <span className="flex h-5 w-5 items-center justify-center rounded-full bg-brand-green/10 text-brand-green text-xs font-bold flex-shrink-0">
                      3
                    </span>
                    <span>
                      {isAr
                        ? "ستتم مزامنة المواعيد تلقائياً في كلا الاتجاهين"
                        : "Appointments will sync automatically in both directions"}
                    </span>
                  </li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
