/**
 * Calendar Connection Banner Component
 * Shows calendar sync status and allows connect/disconnect of Google Calendar or Outlook
 * Supports bilingual (Arabic/English) with RTL layout
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Calendar,
  RefreshCw,
  Link2Off,
  CheckCircle2,
  AlertTriangle,
  Link2,
  ExternalLink,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/pages/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/pages/dashboard.ar";
import { fetchWithCSRF } from "@/lib/csrf-client";

interface CalendarStatus {
  connected: boolean;
  provider: "google_calendar" | "outlook_calendar" | null;
  lastSyncAt: string | null;
  needsReconnect: boolean;
}

interface CalendarConnectionBannerProps {
  lang: Lang;
  initialStatus?: CalendarStatus;
  showWhenDisconnected?: boolean; // When true, show connect options even when not connected
}

export default function CalendarConnectionBanner({
  lang,
  initialStatus,
  showWhenDisconnected = false,
}: CalendarConnectionBannerProps) {
  const isAr = lang === "ar";
  const t = isAr ? dashboardAr : dashboardEn;

  const [status, setStatus] = useState<CalendarStatus | undefined>(
    initialStatus,
  );
  const [isSyncing, setIsSyncing] = useState(false);
  const [syncError, setSyncError] = useState<string | null>(null);
  const [showDisconnectConfirm, setShowDisconnectConfirm] = useState(false);
  const [isDisconnecting, setIsDisconnecting] = useState(false);
  const [isConnecting, setIsConnecting] = useState(false);
  const [showConnectOptions, setShowConnectOptions] = useState(false);

  // Fetch calendar status on mount
  useEffect(() => {
    // Fetch calendar status if not provided
    if (!initialStatus) {
      fetch("/api/user/calendar-status")
        .then((res) => res.json())
        .then((data) => {
          if (data.success && data.calendarStatus) {
            setStatus(data.calendarStatus);
          }
        })
        .catch((error) => {
          console.error("Failed to fetch calendar status:", error);
        });
    }
  }, [initialStatus]);

  // Handle manual sync
  const handleSync = useCallback(async () => {
    setIsSyncing(true);
    setSyncError(null);

    try {
      const syncRes = await fetchWithCSRF("/api/integrations/sync", {
        method: "POST",
      });
      const syncData = await syncRes.json();

      if (!syncRes.ok || !syncData.success) {
        throw new Error(syncData.error || t.calendarSyncError);
      }

      // Refresh status after sync
      const statusRes = await fetch("/api/user/calendar-status");
      const statusData = await statusRes.json();

      if (statusData.success && statusData.calendarStatus) {
        setStatus(statusData.calendarStatus);
      }
    } catch (error) {
      console.error("Sync failed:", error);
      setSyncError(t.calendarSyncError);
    } finally {
      setIsSyncing(false);
    }
  }, [t.calendarSyncError]);

  // Handle disconnect
  const handleDisconnect = useCallback(async () => {
    if (!status?.provider) return;

    setIsDisconnecting(true);

    try {
      const res = await fetchWithCSRF("/api/integrations/disconnect", {
        method: "POST",
        body: JSON.stringify({ type: status.provider }),
      });
      const data = await res.json();

      if (res.ok && data.success) {
        setStatus({
          connected: false,
          provider: null,
          lastSyncAt: null,
          needsReconnect: false,
        });
      }
    } catch (error) {
      console.error("Disconnect failed:", error);
    } finally {
      setIsDisconnecting(false);
      setShowDisconnectConfirm(false);
    }
  }, [status?.provider]);

  // Handle connect - initiates OAuth flow
  const handleConnect = useCallback(
    async (provider: "google_calendar" | "outlook_calendar") => {
      setIsConnecting(true);
      setShowConnectOptions(false);

      try {
        const res = await fetchWithCSRF("/api/integrations/connect", {
          method: "POST",
          body: JSON.stringify({ type: provider }),
        });
        const data = await res.json();

        if (res.ok && data.success) {
          if (data.authUrl) {
            // Redirect to OAuth provider
            window.location.href = data.authUrl;
          } else if (data.status === "pending_setup") {
            // OAuth not configured yet
            alert(
              data.message || (isAr ? "التكوين قيد الإعداد" : "Setup pending"),
            );
          }
        } else {
          console.error("Connect failed:", data.error);
          alert(data.error || (isAr ? "فشل الاتصال" : "Connection failed"));
        }
      } catch (error) {
        console.error("Connect failed:", error);
        alert(isAr ? "فشل الاتصال" : "Connection failed");
      } finally {
        setIsConnecting(false);
      }
    },
    [isAr],
  );

  // Provider label
  const providerLabel = status?.provider
    ? status.provider === "google_calendar"
      ? t.calendarConnectedGoogle
      : t.calendarConnectedOutlook
    : "";

  // Format last sync time
  const lastSyncFormatted = status?.lastSyncAt
    ? new Date(status.lastSyncAt).toLocaleString(isAr ? "ar-SA" : "en-US", {
        dateStyle: "short",
        timeStyle: "short",
      })
    : null;

  // Show "Connect your calendar" banner when not connected
  if (!status?.connected) {
    if (!showWhenDisconnected) {
      return null;
    }

    return (
      <div
        className={`rounded-xl bg-gradient-to-r from-slate-50 to-blue-50 border border-slate-200 p-4 mb-6 ${
          isAr ? "text-right" : ""
        }`}
        dir={isAr ? "rtl" : "ltr"}
      >
        <div className="flex items-center justify-between flex-wrap gap-4">
          {/* Left side: Calendar info */}
          <div
            className={`flex items-center gap-3 ${isAr ? "flex-row-reverse" : ""}`}
          >
            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-slate-100 flex-shrink-0">
              <Calendar className="h-5 w-5 text-slate-600" />
            </div>
            <div>
              <span className="font-semibold text-slate-800">
                {t.calendarNotConnected}
              </span>
              <p className="text-sm text-slate-600">
                {t.calendarConnectPrompt}
              </p>
            </div>
          </div>

          {/* Right side: Connect buttons */}
          <div
            className={`flex items-center gap-2 ${isAr ? "flex-row-reverse" : ""}`}
          >
            {!showConnectOptions ? (
              <button
                onClick={() => setShowConnectOptions(true)}
                disabled={isConnecting}
                className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-green rounded-lg hover:bg-brand-greenHover disabled:opacity-50 transition-colors"
              >
                <Link2 className="h-4 w-4" />
                <span>{t.connectNow}</span>
              </button>
            ) : (
              <div
                className={`flex items-center gap-2 ${isAr ? "flex-row-reverse" : ""}`}
              >
                <button
                  onClick={() => handleConnect("google_calendar")}
                  disabled={isConnecting}
                  className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
                >
                  {isConnecting ? (
                    <RefreshCw className="h-4 w-4 animate-spin" />
                  ) : (
                    <ExternalLink className="h-4 w-4" />
                  )}
                  <span>Google</span>
                </button>
                <button
                  onClick={() => handleConnect("outlook_calendar")}
                  disabled={isConnecting}
                  className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-white bg-[#0078d4] rounded-lg hover:bg-[#106ebe] disabled:opacity-50 transition-colors"
                >
                  {isConnecting ? (
                    <RefreshCw className="h-4 w-4 animate-spin" />
                  ) : (
                    <ExternalLink className="h-4 w-4" />
                  )}
                  <span>Outlook</span>
                </button>
                <button
                  onClick={() => setShowConnectOptions(false)}
                  className="px-3 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors"
                >
                  {isAr ? "إلغاء" : "Cancel"}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  // Connected state - show status and controls
  return (
    <div
      className={`rounded-xl bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200 p-4 mb-6 ${
        isAr ? "text-right" : ""
      }`}
      dir={isAr ? "rtl" : "ltr"}
    >
      <div className="flex items-center justify-between flex-wrap gap-4">
        {/* Left side: Calendar info */}
        <div
          className={`flex items-center gap-3 ${isAr ? "flex-row-reverse" : ""}`}
        >
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-emerald-100 flex-shrink-0">
            <Calendar className="h-5 w-5 text-emerald-600" />
          </div>
          <div>
            <div
              className={`flex items-center gap-2 ${isAr ? "flex-row-reverse" : ""}`}
            >
              <CheckCircle2 className="h-4 w-4 text-emerald-500 flex-shrink-0" />
              <span className="font-semibold text-emerald-800">
                {providerLabel}
              </span>
            </div>
            <p className="text-sm text-emerald-700">{t.calendarSyncEnabled}</p>
            {lastSyncFormatted && (
              <p className="text-xs text-emerald-600 mt-1">
                {t.calendarLastSynced}: {lastSyncFormatted}
              </p>
            )}
          </div>
        </div>

        {/* Right side: Actions */}
        <div
          className={`flex items-center gap-2 ${isAr ? "flex-row-reverse" : ""}`}
        >
          {/* Sync Now button */}
          <button
            onClick={handleSync}
            disabled={isSyncing}
            className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-emerald-700 bg-white border border-emerald-300 rounded-lg hover:bg-emerald-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <RefreshCw
              className={`h-4 w-4 ${isSyncing ? "animate-spin" : ""}`}
            />
            <span>{isSyncing ? t.calendarSyncing : t.calendarSyncNow}</span>
          </button>

          {/* Disconnect button */}
          {!showDisconnectConfirm ? (
            <button
              onClick={() => setShowDisconnectConfirm(true)}
              className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors"
              title={t.calendarDisconnect}
            >
              <Link2Off className="h-4 w-4" />
              <span className="hidden sm:inline">{t.calendarDisconnect}</span>
            </button>
          ) : (
            <div
              className={`flex items-center gap-2 ${isAr ? "flex-row-reverse" : ""}`}
            >
              <button
                onClick={handleDisconnect}
                disabled={isDisconnecting}
                className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-white bg-red-500 rounded-lg hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isDisconnecting ? (
                  <RefreshCw className="h-4 w-4 animate-spin" />
                ) : (
                  <Link2Off className="h-4 w-4" />
                )}
                <span>{isAr ? "تأكيد" : "Confirm"}</span>
              </button>
              <button
                onClick={() => setShowDisconnectConfirm(false)}
                className="px-3 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors"
              >
                {isAr ? "إلغاء" : "Cancel"}
              </button>
            </div>
          )}

          {/* Needs reconnect warning */}
          {status.needsReconnect && (
            <div
              className={`flex items-center gap-1 text-amber-600 text-sm ${
                isAr ? "flex-row-reverse" : ""
              }`}
            >
              <AlertTriangle className="h-4 w-4 flex-shrink-0" />
              <span>{t.calendarNeedsReconnect}</span>
            </div>
          )}
        </div>
      </div>

      {/* Sync error message */}
      {syncError && (
        <div
          className={`mt-3 flex items-center gap-2 text-sm text-red-600 ${
            isAr ? "flex-row-reverse" : ""
          }`}
        >
          <AlertTriangle className="h-4 w-4 flex-shrink-0" />
          <span>{syncError}</span>
        </div>
      )}
    </div>
  );
}
