"use client";

import { useState } from "react";
import {
  Lock,
  ArrowRight,
  CheckCircle,
  Inbox,
  Sparkles,
  TrendingUp,
  Calendar,
  Loader2,
  Link2,
  XCircle,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import type { SocialAccountOutput } from "@/lib/types/social-media.types";
import { fetchWithCSRF } from "@/lib/csrf-client";
import { useSocialData } from "./useSocialData";
import InboxView from "./InboxView";
import AIAssistantView from "./AIAssistantView";
import TrendsView from "./TrendsView";
import CalendarView from "./CalendarView";

type SubTab = "inbox" | "ai-assistant" | "trends" | "calendar";

interface SubTabConfig {
  id: SubTab;
  labelEn: string;
  labelAr: string;
  icon: React.ReactNode;
}

const SUB_TABS: SubTabConfig[] = [
  {
    id: "inbox",
    labelEn: "Inbox",
    labelAr: "البريد الوارد",
    icon: <Inbox className="h-4 w-4" />,
  },
  {
    id: "ai-assistant",
    labelEn: "AI Assistant",
    labelAr: "مساعد الذكاء الاصطناعي",
    icon: <Sparkles className="h-4 w-4" />,
  },
  {
    id: "trends",
    labelEn: "Trends",
    labelAr: "الاتجاهات",
    icon: <TrendingUp className="h-4 w-4" />,
  },
  {
    id: "calendar",
    labelEn: "Calendar",
    labelAr: "التقويم",
    icon: <Calendar className="h-4 w-4" />,
  },
];

interface SocialMediaPanelProps {
  lang: Lang;
  hasAccess?: boolean;
}

const isDev = process.env.NODE_ENV === "development";

export default function SocialMediaPanel({
  lang,
  hasAccess,
}: SocialMediaPanelProps) {
  const isAr = lang === "ar";
  const [activeSubTab, setActiveSubTab] = useState<SubTab>("inbox");

  // Bypass tier gate in development mode
  if (hasAccess === false && !isDev) {
    return <UpgradePrompt isAr={isAr} />;
  }

  return (
    <SocialMediaDashboard
      isAr={isAr}
      activeSubTab={activeSubTab}
      setActiveSubTab={setActiveSubTab}
    />
  );
}

function SocialMediaDashboard({
  isAr,
  activeSubTab,
  setActiveSubTab,
}: {
  isAr: boolean;
  activeSubTab: SubTab;
  setActiveSubTab: (tab: SubTab) => void;
}) {
  const {
    accounts,
    accountsLoading,
    conversations,
    unreadCounts,
    inboxLoading,
    trends,
    postIdeas,
    bestTimes,
    trendsLoading,
    calendarEvents,
    calendarLoading,
    refreshInbox,
    refreshTrends,
    refreshCalendar,
    disconnectAccount,
    errors,
  } = useSocialData();

  const hasConnectedAccounts = accounts.length > 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-slate-900">
          {isAr ? "إدارة التواصل الاجتماعي" : "Social Media Management"}
        </h2>
        <p className="text-slate-500 mt-1">
          {isAr
            ? "أدر جميع حساباتك الاجتماعية من مكان واحد"
            : "Manage all your social accounts from one place"}
        </p>
      </div>

      {/* Show connect prompt if no accounts are connected */}
      {!accountsLoading && !hasConnectedAccounts && (
        <ConnectAccountsPrompt isAr={isAr} />
      )}

      {/* Show loading state while checking accounts */}
      {accountsLoading && (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-6 w-6 animate-spin text-slate-400" />
        </div>
      )}

      {/* Show dashboard when accounts are connected */}
      {!accountsLoading && hasConnectedAccounts && (
        <>
          {/* Connected accounts with disconnect */}
          <ConnectedAccountsHeader
            accounts={accounts}
            isAr={isAr}
            onDisconnect={disconnectAccount}
          />

          {/* Sub-tab navigation */}
          <div className="flex gap-1 p-1 bg-slate-100 rounded-xl w-fit">
            {SUB_TABS.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveSubTab(tab.id)}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                  activeSubTab === tab.id
                    ? "bg-white text-slate-900 shadow-sm"
                    : "text-slate-500 hover:text-slate-700"
                }`}
              >
                {tab.icon}
                {isAr ? tab.labelAr : tab.labelEn}
                {tab.id === "inbox" &&
                  unreadCounts &&
                  unreadCounts.total > 0 && (
                    <span className="ml-1 px-1.5 py-0.5 bg-red-500 text-white text-[10px] font-bold rounded-full min-w-[18px] text-center">
                      {unreadCounts.total}
                    </span>
                  )}
              </button>
            ))}
          </div>

          {/* Tab content */}
          {activeSubTab === "inbox" && (
            <>
              {errors.inbox && (
                <ErrorBanner message={errors.inbox} onRetry={refreshInbox} />
              )}
              <InboxView
                isAr={isAr}
                conversations={conversations}
                loading={inboxLoading}
                onRefresh={refreshInbox}
              />
            </>
          )}
          {activeSubTab === "ai-assistant" && <AIAssistantView isAr={isAr} />}
          {activeSubTab === "trends" && (
            <>
              {errors.trends && (
                <ErrorBanner message={errors.trends} onRetry={refreshTrends} />
              )}
              <TrendsView
                isAr={isAr}
                trends={trends}
                postIdeas={postIdeas}
                bestTimes={bestTimes}
                loading={trendsLoading}
                onRefresh={refreshTrends}
              />
            </>
          )}
          {activeSubTab === "calendar" && (
            <>
              {errors.calendar && (
                <ErrorBanner
                  message={errors.calendar}
                  onRetry={refreshCalendar}
                />
              )}
              <CalendarView
                isAr={isAr}
                events={calendarEvents}
                loading={calendarLoading}
                onRefresh={refreshCalendar}
              />
            </>
          )}
        </>
      )}
    </div>
  );
}

function ConnectedAccountsHeader({
  accounts,
  isAr,
  onDisconnect,
}: {
  accounts: SocialAccountOutput[];
  isAr: boolean;
  onDisconnect: (id: string) => Promise<void>;
}) {
  const [disconnectingId, setDisconnectingId] = useState<string | null>(null);

  async function handleDisconnect(id: string) {
    setDisconnectingId(id);
    try {
      await onDisconnect(id);
    } finally {
      setDisconnectingId(null);
    }
  }

  return (
    <div className="flex flex-wrap items-center gap-3">
      {accounts.map((account) => (
        <div
          key={account.id}
          className="flex items-center gap-2 px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-sm"
        >
          <span className="w-2 h-2 rounded-full bg-emerald-500" />
          <span className="font-medium text-slate-700">
            {account.accountName}
          </span>
          <span className="text-slate-400 capitalize">{account.platform}</span>
          <button
            onClick={() => handleDisconnect(account.id)}
            disabled={disconnectingId === account.id}
            className="ml-1 text-slate-400 hover:text-red-500 transition-colors disabled:opacity-50"
            title={isAr ? "فصل الحساب" : "Disconnect account"}
          >
            {disconnectingId === account.id ? (
              <Loader2 className="h-3.5 w-3.5 animate-spin" />
            ) : (
              <XCircle className="h-3.5 w-3.5" />
            )}
          </button>
        </div>
      ))}
    </div>
  );
}

function ConnectAccountsPrompt({ isAr }: { isAr: boolean }) {
  const [connecting, setConnecting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleConnect() {
    setConnecting(true);
    setError(null);
    try {
      const res = await fetchWithCSRF("/api/social/auth/facebook/authorize", {
        method: "POST",
      });
      if (res.status === 401) {
        setError("Session expired. Please refresh the page and try again.");
        setConnecting(false);
        return;
      }
      if (res.status === 503) {
        setError(
          "Facebook integration is temporarily unavailable. Please try again later.",
        );
        setConnecting(false);
        return;
      }
      const json = await res.json();
      if (json.success && json.data?.url) {
        window.location.href = json.data.url;
      } else {
        setError(json.error || "Failed to start connection");
        setConnecting(false);
      }
    } catch {
      setError("Network error. Please try again.");
      setConnecting(false);
    }
  }

  return (
    <div className="bg-white rounded-2xl border border-slate-200 p-10 text-center shadow-sm">
      <div className="mx-auto w-16 h-16 rounded-2xl bg-gradient-to-br from-blue-50 to-blue-100 flex items-center justify-center mb-5">
        <Link2 className="h-8 w-8 text-blue-500" />
      </div>
      <h3 className="text-xl font-bold text-slate-900 mb-2">
        {isAr ? "اربط حساباتك الاجتماعية" : "Connect Your Social Accounts"}
      </h3>
      <p className="text-slate-500 max-w-md mx-auto mb-6">
        {isAr
          ? "اربط صفحتك على فيسبوك وحساب إنستغرام لإدارة الرسائل والمحتوى من مكان واحد"
          : "Connect your Facebook Page and Instagram account to manage messages and content from one place"}
      </p>
      {error && <p className="text-red-600 text-sm mb-4">{error}</p>}
      <button
        onClick={handleConnect}
        disabled={connecting}
        className="px-6 py-3 bg-[#1877F2] text-white rounded-xl text-sm font-semibold hover:bg-[#166FE5] transition-colors inline-flex items-center gap-2 disabled:opacity-60 disabled:cursor-not-allowed"
      >
        {connecting ? (
          <Loader2 className="h-4 w-4 animate-spin" />
        ) : (
          <svg className="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
            <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
          </svg>
        )}
        {isAr
          ? connecting
            ? "جاري الاتصال..."
            : "ربط فيسبوك"
          : connecting
            ? "Connecting..."
            : "Connect Facebook"}
      </button>
    </div>
  );
}

function ErrorBanner({
  message,
  onRetry,
}: {
  message: string;
  onRetry: () => void;
}) {
  return (
    <div className="flex items-center justify-between bg-red-50 border border-red-200 text-red-700 text-sm p-2 rounded-lg">
      <span>{message}</span>
      <button
        onClick={onRetry}
        className="ml-3 text-xs font-medium underline hover:text-red-900"
      >
        Retry
      </button>
    </div>
  );
}

function UpgradePrompt({ isAr }: { isAr: boolean }) {
  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">
            {isAr ? "إدارة التواصل الاجتماعي" : "Social Media Management"}
          </h2>
          <p className="text-slate-500 mt-1">
            {isAr
              ? "أدر جميع حساباتك الاجتماعية بالذكاء الاصطناعي"
              : "AI-powered social media management"}
          </p>
        </div>
      </div>

      <div className="bg-white rounded-2xl border border-slate-200 p-10 text-center shadow-sm">
        <div className="mx-auto w-16 h-16 rounded-2xl bg-gradient-to-br from-slate-100 to-slate-200 flex items-center justify-center mb-5">
          <Lock className="h-8 w-8 text-slate-400" />
        </div>
        <h3 className="text-xl font-bold text-slate-900 mb-2">
          {isAr
            ? "إدارة التواصل الاجتماعي متاحة في خطة المؤسسات"
            : "Social Media Available on Enterprise Plan"}
        </h3>
        <p className="text-slate-500 max-w-md mx-auto mb-6">
          {isAr
            ? "قم بالترقية إلى خطة المؤسسات للحصول على إدارة متكاملة لحساباتك الاجتماعية مع مساعد ذكاء اصطناعي وتحليلات متقدمة"
            : "Upgrade to the Enterprise plan to get unified social inbox, AI content assistant, trend analysis, and content scheduling"}
        </p>
        <div className="flex flex-wrap justify-center gap-3 mb-8">
          {[
            { en: "Unified social inbox", ar: "بريد وارد موحد" },
            { en: "AI content assistant", ar: "مساعد محتوى ذكي" },
            { en: "Trend analysis", ar: "تحليل الاتجاهات" },
            { en: "Content calendar", ar: "تقويم المحتوى" },
          ].map((feature) => (
            <span
              key={feature.en}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-emerald-50 text-emerald-700 text-sm font-medium"
            >
              <CheckCircle className="h-3.5 w-3.5" />
              {isAr ? feature.ar : feature.en}
            </span>
          ))}
        </div>
        <button className="px-6 py-3 bg-brand-green text-white rounded-xl text-sm font-semibold hover:bg-brand-green/90 transition-colors inline-flex items-center gap-2">
          {isAr ? "ترقية الآن" : "Upgrade Now"}
          <ArrowRight className={`h-4 w-4 ${isAr ? "rotate-180" : ""}`} />
        </button>
      </div>
    </div>
  );
}
