/**
 * Dashboard Client Component
 * Contains all interactive UI elements
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useClerk } from "@clerk/nextjs";
import Link from "next/link";
import { SITE, UI, type Lang } from "@/lib/config";
import type { Session } from "next-auth";
import SubscriptionDetails from "./components/SubscriptionDetails";
import BillingHistory from "./components/BillingHistory";
import { PlanSnapshot } from "./components/PlanSnapshot";
import { PlanHighlights } from "./components/PlanHighlights";
import { PlanUpgradeModal } from "./components/PlanUpgradeModal";
import CurrentPackageCard from "./components/CurrentPackageCard";
import type { DashboardSubscriptionDetails } from "./types";
import type { Currency, TierId } from "@/lib/types/pricing";

interface DemoBooking {
  id: string;
  full_name: string;
  email: string;
  telephone: string;
  appointment_date: string;
  appointment_time: string;
  duration: string;
  special_requirements?: string;
  language: string;
  status: "pending" | "confirmed" | "cancelled";
  created_at: string;
}

interface DashboardAccessStatus {
  hasAccess: boolean;
  reason?: string;
  onboardingComplete?: boolean;
  subscription?: {
    status: string;
    tierId: string;
    billingPeriod: string;
    currentPeriodEnd: string;
  };
  redirectUrl?: string;
}

interface DashboardClientProps {
  lang: Lang;
  session: Session;
  accessStatus: DashboardAccessStatus;
}

const SUPPORTED_CURRENCIES: Currency[] = [
  "GBP",
  "USD",
  "EUR",
  "SAR",
  "AED",
  "QAR",
  "KWD",
  "BHD",
  "OMR",
];

const normalizeCurrency = (value?: string | null): Currency => {
  if (!value) return "QAR";
  const upper = value.toUpperCase() as Currency;
  return SUPPORTED_CURRENCIES.includes(upper) ? upper : "QAR";
};

export default function DashboardClient({
  lang,
  session,
  accessStatus,
}: DashboardClientProps) {
  const router = useRouter();
  const { signOut } = useClerk();
  const t = UI[lang].t;
  const dir = UI[lang].dir;
  const isAr = lang === "ar";

  const [activeTab, setActiveTab] = useState<
    "overview" | "appointments" | "demo-bookings" | "clients" | "billing"
  >("overview");
  const [demoBookings, setDemoBookings] = useState<DemoBooking[]>([]);
  const [loadingBookings, setLoadingBookings] = useState(false);
  const [confirmingBooking, setConfirmingBooking] = useState<string | null>(
    null,
  );
  const [csrfToken, setCsrfToken] = useState("");
  const [subscriptionDetails, setSubscriptionDetails] =
    useState<DashboardSubscriptionDetails | null>(null);
  const [loadingSubscription, setLoadingSubscription] = useState(true);
  const [subscriptionError, setSubscriptionError] = useState<string | null>(
    null,
  );
  const [billingCurrency, setBillingCurrency] = useState<Currency>("QAR");
  const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
  const [upgradeTier, setUpgradeTier] = useState<TierId | null>(null);

  // Fetch CSRF token
  useEffect(() => {
    fetch("/api/csrf")
      .then((res) => res.json())
      .then((data) => setCsrfToken(data.csrfToken))
      .catch((err) => console.error("Failed to fetch CSRF token", err));
  }, []);

  // Fetch demo bookings
  useEffect(() => {
    async function fetchDemoBookings() {
      setLoadingBookings(true);
      try {
        const response = await fetch("/api/demo/bookings?all=true&limit=50");
        if (response.ok) {
          const data = await response.json();
          setDemoBookings(data.bookings || []);
        }
      } catch (error) {
        console.error("Failed to fetch demo bookings", error);
      } finally {
        setLoadingBookings(false);
      }
    }

    fetchDemoBookings();
  }, []);

  const loadSubscriptionDetails = useCallback(async () => {
    setLoadingSubscription(true);
    setSubscriptionError(null);
    try {
      const response = await fetch("/api/subscription/details");
      if (response.status === 404) {
        setSubscriptionDetails(null);
        setBillingCurrency("QAR");
      } else if (!response.ok) {
        const data = await response.json().catch(() => ({}));
        throw new Error(data.error || "Failed to load subscription");
      } else {
        const data: DashboardSubscriptionDetails = await response.json();
        setSubscriptionDetails(data);
        const derivedCurrency = normalizeCurrency(
          data.billingHistory?.[0]?.currency,
        );
        setBillingCurrency(derivedCurrency);
      }
    } catch (error) {
      console.error("Failed to load subscription details", error);
      setSubscriptionError(
        isAr
          ? "فشل تحميل بيانات الاشتراك."
          : "Failed to load subscription data.",
      );
    } finally {
      setLoadingSubscription(false);
    }
  }, [isAr]);

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

  // Confirm booking and send email
  const handleConfirmBooking = async (bookingId: string) => {
    if (!csrfToken) {
      alert(
        isAr
          ? "خطأ في الأمان. يرجى تحديث الصفحة."
          : "Security error. Please refresh the page.",
      );
      return;
    }

    setConfirmingBooking(bookingId);

    try {
      const response = await fetch("/api/demo/confirm", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({ bookingId }),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Failed to confirm booking");
      }

      // Update local state
      setDemoBookings((prev) =>
        prev.map((b) =>
          b.id === bookingId ? { ...b, status: "confirmed" } : b,
        ),
      );

      alert(
        isAr
          ? "تم تأكيد الموعد وإرسال بريد إلكتروني للعميل!"
          : "Booking confirmed and confirmation email sent to customer!",
      );
    } catch (error) {
      console.error("Failed to confirm booking", error);
      alert(
        isAr
          ? "فشل تأكيد الموعد. يرجى المحاولة مرة أخرى."
          : "Failed to confirm booking. Please try again.",
      );
    } finally {
      setConfirmingBooking(null);
    }
  };

  const handleLogout = async () => {
    try {
      await fetch("/api/auth/logout", { method: "POST" });
      await signOut({ redirectUrl: `/${lang}` });
    } catch (error) {
      console.error("Logout error", error);
    }
  };

  // Calculate statistics from demo bookings
  const totalDemoBookings = demoBookings.length;
  const pendingBookings = demoBookings.filter(
    (b) => b.status === "pending",
  ).length;
  const confirmedBookings = demoBookings.filter(
    (b) => b.status === "confirmed",
  ).length;

  const openUpgradeModal = (tier?: TierId) => {
    if (!subscriptionDetails) {
      router.push(`/${lang}/pricing`);
      return;
    }
    setUpgradeTier(tier ?? null);
    setUpgradeModalOpen(true);
  };

  const closeUpgradeModal = () => setUpgradeModalOpen(false);

  const handleUpgradeSuccess = () => {
    loadSubscriptionDetails();
  };

  return (
    <>
      <main className="min-h-screen bg-slate-50" dir={dir}>
        {/* Top App Bar */}
        <header className="border-b border-slate-200 bg-white/90 backdrop-blur-sm">
          <div className="flex items-center justify-between px-4 py-4 sm:px-6 lg:px-8">
            <div className="flex shrink-0 items-center gap-2">
              <Link
                href={`/${lang}`}
                className="flex shrink-0 items-center gap-2 text-2xl font-extrabold text-brand-green"
              >
                <img src="/mawidi-icon.svg" alt="Mawidi" className="h-10 w-auto" width={40} height={40} />
              </Link>
              <span className="rounded-full bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-700">
                {isAr ? "لوحة العيادة" : "Clinic Workspace"}
              </span>
            </div>
            <div className="flex items-center gap-4">
              {accessStatus?.subscription && (
                <div className="hidden items-center gap-2 rounded-full bg-slate-100 px-3 py-1 text-xs text-slate-700 sm:flex">
                  <span className="font-semibold text-emerald-700">
                    {accessStatus.subscription.tierId}
                  </span>
                  <span>•</span>
                  <span className="capitalize">
                    {accessStatus.subscription.billingPeriod === "monthly"
                      ? isAr
                        ? "شهري"
                        : "Monthly"
                      : isAr
                        ? "سنوي"
                        : "Yearly"}
                  </span>
                  <span>•</span>
                  <span>
                    {isAr ? "ينتهي" : "Renews"}{" "}
                    {new Date(
                      accessStatus.subscription.currentPeriodEnd,
                    ).toLocaleDateString(isAr ? "ar-SA" : "en-US")}
                  </span>
                </div>
              )}
              <div className="hidden flex-col items-end sm:flex">
                <span className="text-xs text-slate-500">
                  {isAr ? "مسجل باسم" : "Signed in as"}
                </span>
                <span className="text-sm font-medium text-slate-900">
                  {(session.user &&
                    (session.user.name || session.user.email)) ||
                    (isAr ? "حساب ماويدي" : "Mawidi Account")}
                </span>
              </div>
              <button
                onClick={handleLogout}
                className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-slate-700 transition-colors hover:border-brand-green hover:text-brand-green"
              >
                {t.logout || (isAr ? "تسجيل الخروج" : "Logout")}
              </button>
            </div>
          </div>
        </header>

        {/* Main Layout */}
        <div className="mx-auto flex max-w-7xl flex-col gap-6 px-4 py-6 sm:px-6 lg:px-8">
          {/* Welcome + Key Stats */}
          <section className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div>
              <h1 className="text-2xl font-semibold text-slate-900 sm:text-3xl">
                {isAr
                  ? `مرحباً، ${(session.user && session.user.name) || "فريق ماويدي"}`
                  : `Welcome back, ${(session.user && session.user.name) || "Mawidi Partner"}`}
              </h1>
              <p className="mt-1 text-sm text-slate-600">
                {isAr
                  ? "رؤية سريعة على مواعيدك، عملائك، واشتراكك في ماويدي."
                  : "Live view of your appointments, customers, and Mawidi subscription."}
              </p>
            </div>
            <div className="grid grid-cols-2 gap-3 text-xs md:grid-cols-3">
              <div className="rounded-xl bg-white px-3 py-2 shadow-sm">
                <p className="text-[10px] text-slate-500">
                  {isAr ? "طلبات التجربة" : "Demo Requests"}
                </p>
                <p className="mt-1 text-lg font-semibold text-emerald-600">
                  {totalDemoBookings}
                </p>
                <p className="text-[10px] text-slate-500">
                  {isAr ? "إجمالي" : "Total"}
                </p>
              </div>
              <div className="rounded-xl bg-white px-3 py-2 shadow-sm">
                <p className="text-[10px] text-slate-500">
                  {isAr ? "قيد الانتظار" : "Pending"}
                </p>
                <p className="mt-1 text-lg font-semibold text-sky-600">
                  {pendingBookings}
                </p>
                <p className="text-[10px] text-slate-500">
                  {isAr ? "حجوزات تجريبية" : "Demo bookings"}
                </p>
              </div>
              <div className="rounded-xl bg-white px-3 py-2 shadow-sm md:block hidden">
                <p className="text-[10px] text-slate-500">
                  {isAr ? "مؤكد" : "Confirmed"}
                </p>
                <p className="mt-1 text-xs font-semibold text-violet-600">
                  {confirmedBookings}
                </p>
                <p className="text-[10px] text-slate-500">
                  {isAr ? "مواعيد مؤكدة" : "Confirmed demos"}
                </p>
              </div>
            </div>
          </section>

          {/* Navigation Tabs */}
          <section className="flex flex-wrap gap-2 rounded-xl bg-white p-2 shadow-sm">
            {(
              [
                {
                  id: "overview",
                  labelEn: "Overview",
                  labelAr: "نظرة عامة",
                },
                {
                  id: "demo-bookings",
                  labelEn: "Demo Bookings",
                  labelAr: "حجوزات التجربة",
                },
                {
                  id: "appointments",
                  labelEn: "Appointments",
                  labelAr: "المواعيد",
                },
                {
                  id: "clients",
                  labelEn: "Clients",
                  labelAr: "العملاء",
                },
                {
                  id: "billing",
                  labelEn: "Billing & Plan",
                  labelAr: "الفوترة والخطة",
                },
              ] as const
            ).map((tab) => {
              const isActive = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-medium transition-all ${
                    isActive
                      ? "bg-brand-green text-white shadow-sm"
                      : "text-slate-600 hover:bg-slate-50"
                  }`}
                >
                  <span>
                    {tab.id === "overview" && "📊"}
                    {tab.id === "demo-bookings" && "🎯"}
                    {tab.id === "appointments" && "📅"}
                    {tab.id === "clients" && "👥"}
                    {tab.id === "billing" && "💳"}
                  </span>
                  <span>{isAr ? tab.labelAr : tab.labelEn}</span>
                </button>
              );
            })}
            {/* Workflows Link - Separate page for AI agents and integrations */}
            <Link
              href={`/${lang}/dashboard/workflows`}
              className="flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-medium transition-all text-slate-600 hover:bg-slate-50 border border-dashed border-slate-300 hover:border-brand-green hover:text-brand-green"
            >
              <span>⚡</span>
              <span>{isAr ? "سير العمل" : "Workflows"}</span>
            </Link>
          </section>

          {/* Overview */}
          {activeTab === "overview" && (
            <>
              {/* Workflow Management Quick Access Card */}
              <Link
                href={`/${lang}/dashboard/workflows`}
                className="group block rounded-xl bg-gradient-to-r from-violet-500 to-purple-600 p-5 shadow-sm hover:shadow-md transition-all"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <h2 className="text-sm font-semibold text-white">
                      {isAr ? "⚡ إدارة سير العمل" : "⚡ Workflow Management"}
                    </h2>
                    <p className="text-[11px] text-white/80 mt-1">
                      {isAr
                        ? "إدارة وكلاء الذكاء الاصطناعي، تكامل واتساب، والتحليلات"
                        : "Manage AI agents, WhatsApp integration, and analytics"}
                    </p>
                  </div>
                  <div className="rounded-full bg-white/20 p-2 group-hover:bg-white/30 transition-colors">
                    <svg
                      className="h-5 w-5 text-white"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M13 7l5 5m0 0l-5 5m5-5H6"
                      />
                    </svg>
                  </div>
                </div>
                <div className="mt-3 flex gap-2">
                  <span className="inline-flex items-center rounded-full bg-white/20 px-2 py-0.5 text-[10px] text-white">
                    {isAr ? "وكيل ذكي" : "AI Agent"}
                  </span>
                  <span className="inline-flex items-center rounded-full bg-white/20 px-2 py-0.5 text-[10px] text-white">
                    {isAr ? "واتساب" : "WhatsApp"}
                  </span>
                  <span className="inline-flex items-center rounded-full bg-white/20 px-2 py-0.5 text-[10px] text-white">
                    {isAr ? "التحليلات" : "Analytics"}
                  </span>
                </div>
              </Link>

              <section className="grid gap-4 lg:grid-cols-3">
                {/* Demo Bookings Preview */}
                <div className="space-y-4 lg:col-span-2">
                  <div className="rounded-xl bg-white p-5 shadow-sm">
                    <div className="flex items-center justify-between gap-2">
                      <div>
                        <h2 className="text-sm font-semibold text-slate-900">
                          {isAr ? "أحدث طلبات التجربة" : "Recent Demo Requests"}
                        </h2>
                        <p className="text-[11px] text-slate-500">
                          {isAr
                            ? "حجوزات تجريبية من العملاء المحتملين عبر الموقع الإلكتروني"
                            : "Demo bookings from potential customers via your website"}
                        </p>
                      </div>
                      <button
                        className="rounded-lg bg-brand-green/5 px-3 py-1 text-[10px] font-medium text-brand-green hover:bg-brand-green/10"
                        onClick={() => setActiveTab("demo-bookings")}
                      >
                        {isAr ? "عرض الكل" : "View all"} ({totalDemoBookings})
                      </button>
                    </div>
                    {demoBookings.length === 0 ? (
                      <div className="mt-4 flex flex-col items-center justify-center rounded-lg border border-dashed border-slate-200 py-8 text-center text-xs text-slate-500">
                        <p className="mb-1">
                          {isAr
                            ? "لا توجد طلبات تجريبية بعد."
                            : "No demo requests yet."}
                        </p>
                        <p className="mb-3">
                          {isAr
                            ? "شارك رابط صفحة التجربة مع العملاء المحتملين."
                            : "Share your demo page link with potential customers."}
                        </p>
                        <div className="flex flex-wrap justify-center gap-2">
                          <Link
                            href={`/${lang}/demo`}
                            className="rounded-lg bg-brand-green px-3 py-1.5 text-[10px] font-semibold text-white hover:bg-brand-greenHover"
                          >
                            {isAr ? "تجربة نموذج الحجز" : "Try demo form"}
                          </Link>
                        </div>
                      </div>
                    ) : (
                      <div className="mt-4 space-y-2">
                        {demoBookings.slice(0, 5).map((booking) => (
                          <div
                            key={booking.id}
                            className="flex items-center justify-between rounded-lg border border-slate-100 p-3 hover:bg-slate-50"
                          >
                            <div className="flex items-center gap-3">
                              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-brand-green/10 text-brand-green">
                                <span className="text-xs font-semibold">
                                  {booking.full_name.charAt(0).toUpperCase()}
                                </span>
                              </div>
                              <div>
                                <p className="text-xs font-medium text-slate-900">
                                  {booking.full_name}
                                </p>
                                <p className="text-[10px] text-slate-500">
                                  {new Date(
                                    booking.appointment_date,
                                  ).toLocaleDateString(
                                    isAr ? "ar-SA" : "en-US",
                                    { month: "short", day: "numeric" },
                                  )}{" "}
                                  at {booking.appointment_time}
                                </p>
                              </div>
                            </div>
                            <span
                              className={`inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium ${
                                booking.status === "confirmed"
                                  ? "bg-emerald-100 text-emerald-700"
                                  : booking.status === "pending"
                                    ? "bg-yellow-100 text-yellow-700"
                                    : "bg-slate-100 text-slate-600"
                              }`}
                            >
                              {booking.status === "confirmed"
                                ? isAr
                                  ? "مؤكد"
                                  : "Confirmed"
                                : booking.status === "pending"
                                  ? isAr
                                    ? "قيد الانتظار"
                                    : "Pending"
                                  : isAr
                                    ? "ملغى"
                                    : "Cancelled"}
                            </span>
                          </div>
                        ))}
                        {demoBookings.length > 5 && (
                          <button
                            onClick={() => setActiveTab("demo-bookings")}
                            className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-[10px] font-medium text-slate-700 hover:border-brand-green hover:text-brand-green"
                          >
                            {isAr
                              ? `عرض جميع الـ ${totalDemoBookings} حجز`
                              : `View all ${totalDemoBookings} bookings`}
                          </button>
                        )}
                      </div>
                    )}
                  </div>

                  {/* Today summary */}
                </div>
                {/* Today summary + Plan snapshot */}
                <div className="flex flex-col gap-4">
                  <PlanSnapshot
                    lang={lang}
                    subscriptionData={subscriptionDetails}
                    loading={loadingSubscription}
                    onUpgrade={() => openUpgradeModal()}
                    onViewBilling={() => setActiveTab("billing")}
                  />
                  {subscriptionError && (
                    <p className="text-xs text-rose-600">{subscriptionError}</p>
                  )}
                  <div className="rounded-xl bg-white p-4 shadow-sm">
                    <p className="text-[10px] text-slate-500">
                      {isAr ? "نسبة إشغال اليوم" : "Today occupancy"}
                    </p>
                    <p className="mt-1 text-2xl font-semibold text-emerald-600">
                      0%
                    </p>
                    <p className="text-[10px] text-slate-500">
                      {isAr
                        ? "سيتم تحديثها تلقائياً مع أول المواعيد."
                        : "Will update automatically as bookings come in."}
                    </p>
                  </div>
                </div>
              </section>
              {subscriptionDetails && (
                <section>
                  <PlanHighlights
                    lang={lang}
                    currentTierId={subscriptionDetails.subscription.tierId}
                    currency={billingCurrency}
                    billingPeriod={
                      subscriptionDetails.subscription.billingPeriod
                    }
                    onSelectTier={(tier) => openUpgradeModal(tier)}
                  />
                </section>
              )}
            </>
          )}

          {/* Demo Bookings Tab */}
          {activeTab === "demo-bookings" && (
            <section className="rounded-xl bg-white p-5 shadow-sm">
              <div className="flex items-center justify-between gap-2 mb-4">
                <div>
                  <h2 className="text-sm font-semibold text-slate-900">
                    {isAr ? "حجوزات التجربة" : "Demo Bookings"}
                  </h2>
                  <p className="text-[11px] text-slate-500">
                    {isAr
                      ? "جميع طلبات التجربة من الموقع الإلكتروني"
                      : "All demo requests from your website"}
                  </p>
                </div>
                <Link
                  href={`/${lang}/demo`}
                  className="rounded-lg bg-brand-green px-3 py-1.5 text-[10px] font-semibold text-white hover:bg-brand-greenHover"
                >
                  {isAr ? "عرض نموذج الحجز" : "View booking form"}
                </Link>
              </div>

              {loadingBookings ? (
                <div className="flex items-center justify-center py-12">
                  <div className="text-sm text-slate-500">
                    {isAr ? "جاري التحميل..." : "Loading..."}
                  </div>
                </div>
              ) : demoBookings.length === 0 ? (
                <div className="flex flex-col items-center justify-center rounded-lg border border-dashed border-slate-200 py-12 text-center text-xs text-slate-400">
                  <p className="mb-2">
                    {isAr
                      ? "لا توجد حجوزات تجريبية بعد."
                      : "No demo bookings yet."}
                  </p>
                  <p>
                    {isAr
                      ? "ستظهر طلبات التجربة من عملائك هنا."
                      : "Demo requests from your customers will appear here."}
                  </p>
                  <Link
                    href={`/${lang}/demo`}
                    className="mt-4 rounded-lg bg-brand-green px-4 py-2 text-[10px] font-semibold text-white hover:bg-brand-greenHover"
                  >
                    {isAr ? "تجربة نموذج الحجز" : "Try demo form"}
                  </Link>
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-xs">
                    <thead>
                      <tr className="border-b border-slate-100 bg-slate-50">
                        <th className="px-3 py-2 text-left font-semibold text-slate-600">
                          {isAr ? "التاريخ" : "Date"}
                        </th>
                        <th className="px-3 py-2 text-left font-semibold text-slate-600">
                          {isAr ? "الوقت" : "Time"}
                        </th>
                        <th className="px-3 py-2 text-left font-semibold text-slate-600">
                          {isAr ? "الاسم" : "Name"}
                        </th>
                        <th className="px-3 py-2 text-left font-semibold text-slate-600">
                          {isAr ? "البريد/الهاتف" : "Email/Phone"}
                        </th>
                        <th className="px-3 py-2 text-left font-semibold text-slate-600">
                          {isAr ? "المدة" : "Duration"}
                        </th>
                        <th className="px-3 py-2 text-left font-semibold text-slate-600">
                          {isAr ? "الحالة" : "Status"}
                        </th>
                        <th className="px-3 py-2 text-left font-semibold text-slate-600">
                          {isAr ? "اللغة" : "Language"}
                        </th>
                        <th className="px-3 py-2 text-left font-semibold text-slate-600">
                          {isAr ? "إجراءات" : "Actions"}
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {demoBookings.map((booking) => (
                        <tr
                          key={booking.id}
                          className="border-b border-slate-50 hover:bg-slate-50"
                        >
                          <td className="px-3 py-3 text-slate-700">
                            {new Date(
                              booking.appointment_date,
                            ).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                              year: "numeric",
                              month: "short",
                              day: "numeric",
                            })}
                          </td>
                          <td className="px-3 py-3 text-slate-700 font-medium">
                            {booking.appointment_time}
                          </td>
                          <td className="px-3 py-3 text-slate-900 font-medium">
                            {booking.full_name}
                          </td>
                          <td className="px-3 py-3 text-slate-600">
                            <div className="flex flex-col gap-0.5">
                              <span className="text-[10px]">
                                {booking.email}
                              </span>
                              <span className="text-[10px] text-slate-500">
                                {booking.telephone}
                              </span>
                            </div>
                          </td>
                          <td className="px-3 py-3 text-slate-700">
                            {booking.duration}
                          </td>
                          <td className="px-3 py-3">
                            <span
                              className={`inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium ${
                                booking.status === "confirmed"
                                  ? "bg-emerald-100 text-emerald-700"
                                  : booking.status === "pending"
                                    ? "bg-yellow-100 text-yellow-700"
                                    : "bg-slate-100 text-slate-600"
                              }`}
                            >
                              {booking.status === "confirmed"
                                ? isAr
                                  ? "مؤكد"
                                  : "Confirmed"
                                : booking.status === "pending"
                                  ? isAr
                                    ? "قيد الانتظار"
                                    : "Pending"
                                  : isAr
                                    ? "ملغى"
                                    : "Cancelled"}
                            </span>
                          </td>
                          <td className="px-3 py-3 text-slate-600">
                            <span className="text-[10px] uppercase">
                              {booking.language}
                            </span>
                          </td>
                          <td className="px-3 py-3">
                            {booking.status === "pending" && (
                              <button
                                onClick={() => handleConfirmBooking(booking.id)}
                                disabled={confirmingBooking === booking.id}
                                className="rounded-lg bg-brand-green px-3 py-1 text-[10px] font-semibold text-white hover:bg-brand-greenHover disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                {confirmingBooking === booking.id
                                  ? isAr
                                    ? "جاري التأكيد..."
                                    : "Confirming..."
                                  : isAr
                                    ? "تأكيد وإرسال بريد"
                                    : "Confirm & Email"}
                              </button>
                            )}
                            {booking.status === "confirmed" && (
                              <span className="text-[10px] text-emerald-600">
                                ✓ {isAr ? "تم الإرسال" : "Email sent"}
                              </span>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>

                  {/* Pagination hint */}
                  {demoBookings.length >= 50 && (
                    <p className="mt-4 text-center text-[10px] text-slate-500">
                      {isAr
                        ? "عرض أول 50 حجز. للمزيد، استخدم الفلاتر."
                        : "Showing first 50 bookings. Use filters for more."}
                    </p>
                  )}
                </div>
              )}
            </section>
          )}

          {/* Appointments Tab */}
          {activeTab === "appointments" && (
            <section className="rounded-xl bg-white p-5 shadow-sm">
              <div className="flex items-center justify-between gap-2">
                <div>
                  <h2 className="text-sm font-semibold text-slate-900">
                    {isAr ? "جدول المواعيد" : "Appointments schedule"}
                  </h2>
                  <p className="text-[11px] text-slate-500">
                    {isAr
                      ? "يعرض المواعيد القادمة حسب اليوم والعميل."
                      : "Shows upcoming bookings by day and client."}
                  </p>
                </div>
                <button className="rounded-lg bg-brand-green px-3 py-1.5 text-[10px] font-semibold text-white hover:bg-brand-greenHover">
                  {isAr ? "إضافة موعد" : "Add appointment"}
                </button>
              </div>
              <div className="mt-4 overflow-hidden rounded-lg border border-slate-100 text-xs">
                <div className="grid grid-cols-5 bg-slate-50 px-3 py-2 font-semibold text-slate-600">
                  <div>{isAr ? "التاريخ" : "Date"}</div>
                  <div>{isAr ? "الوقت" : "Time"}</div>
                  <div>{isAr ? "العميل" : "Client"}</div>
                  <div>{isAr ? "الخدمة" : "Service"}</div>
                  <div>{isAr ? "الحالة" : "Status"}</div>
                </div>
                <div className="flex flex-col items-center justify-center px-3 py-6 text-slate-400">
                  <p>
                    {isAr
                      ? 'لا توجد مواعيد مسجلة. استخدم زر "إضافة موعد" أو فعّل حجوزات واتساب.'
                      : 'No bookings yet. Use "Add appointment" or enable WhatsApp bookings.'}
                  </p>
                </div>
              </div>
            </section>
          )}

          {/* Clients Tab */}
          {activeTab === "clients" && (
            <section className="rounded-xl bg-white p-5 shadow-sm">
              <div className="flex items-center justify-between gap-2">
                <div>
                  <h2 className="text-sm font-semibold text-slate-900">
                    {isAr ? "سجل العملاء" : "Client directory"}
                  </h2>
                  <p className="text-[11px] text-slate-500">
                    {isAr
                      ? "تابع المرضى والعملاء الأكثر تكراراً ونشاطاً."
                      : "Track your most engaged and returning clients."}
                  </p>
                </div>
                <button className="rounded-lg bg-brand-green px-3 py-1.5 text-[10px] font-semibold text-white hover:bg-brand-greenHover">
                  {isAr ? "إضافة عميل" : "Add client"}
                </button>
              </div>
              <div className="mt-4 flex flex-col gap-3 text-xs">
                <div className="flex flex-wrap items-center gap-2">
                  <input
                    type="text"
                    placeholder={
                      isAr
                        ? "بحث بالاسم أو رقم الواتساب"
                        : "Search by name or WhatsApp number"
                    }
                    className="w-full max-w-xs rounded-lg border border-slate-200 px-3 py-2 text-[10px] focus:border-brand-green focus:outline-none focus:ring-1 focus:ring-brand-green/40"
                  />
                </div>
                <div className="mt-2 flex flex-col items-center justify-center rounded-lg border border-dashed border-slate-200 px-3 py-6 text-slate-400">
                  <p>
                    {isAr
                      ? "لم تتم إضافة أي عملاء بعد. سيتم إنشاؤهم تلقائياً عند تأكيد المواعيد."
                      : "No clients yet. Clients will appear automatically as bookings are confirmed."}
                  </p>
                </div>
              </div>
            </section>
          )}

          {/* Billing & Plan Tab */}
          {activeTab === "billing" && (
            <section className="space-y-6">
              {/* Current Package Card - Prominent display of user's subscription */}
              <CurrentPackageCard
                lang={lang}
                subscriptionData={subscriptionDetails}
                loading={loadingSubscription}
                onChangePlan={() => openUpgradeModal()}
                onViewHistory={() => router.push(`/${lang}/dashboard/billing`)}
              />

              {/* Subscription Details - Additional billing info */}
              <SubscriptionDetails lang={lang} />

              {/* Recent Billing History Preview */}
              <div>
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-lg font-semibold text-slate-900">
                    {isAr ? "آخر المعاملات" : "Recent Transactions"}
                  </h2>
                  <Link
                    href={`/${lang}/dashboard/billing`}
                    className="text-sm text-brand-green hover:underline"
                  >
                    {isAr ? "عرض الكل →" : "View all →"}
                  </Link>
                </div>
                <BillingHistory lang={lang} limit={5} />
              </div>
            </section>
          )}

          {/* Account Info (persistent footer card) */}
          <section className="mt-2 rounded-xl bg-white p-4 text-[10px] text-slate-600 shadow-sm">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div className="flex flex-col">
                <span className="text-[9px] uppercase tracking-wide text-slate-400">
                  {isAr ? "المالك" : "Account owner"}
                </span>
                <span className="text-xs font-semibold text-slate-900">
                  {(session.user &&
                    (session.user.name || session.user.email)) ||
                    (isAr ? "حساب ماويدي" : "Mawidi Account")}
                </span>
              </div>
              {session.user?.email && (
                <div className="flex flex-col">
                  <span className="text-[9px] uppercase tracking-wide text-slate-400">
                    {isAr ? "البريد الإلكتروني" : "Email"}
                  </span>
                  <span className="text-xs font-medium text-slate-900">
                    {session.user.email}
                  </span>
                </div>
              )}
              <div className="flex flex-wrap gap-2">
                <button className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-[9px] font-medium text-slate-700 hover:border-brand-green hover:text-brand-green">
                  {isAr ? "إعدادات الحساب" : "Account settings"}
                </button>
                <button
                  onClick={handleLogout}
                  className="rounded-lg bg-slate-900 px-3 py-1.5 text-[9px] font-semibold text-white hover:bg-slate-800"
                >
                  {t.logout || (isAr ? "تسجيل الخروج" : "Logout")}
                </button>
              </div>
            </div>
          </section>
        </div>
      </main>

      <PlanUpgradeModal
        lang={lang}
        isOpen={upgradeModalOpen}
        onClose={closeUpgradeModal}
        subscriptionData={subscriptionDetails}
        currency={billingCurrency}
        initialTier={upgradeTier || undefined}
        billingPeriod={
          subscriptionDetails?.subscription.billingPeriod || "monthly"
        }
        onSuccess={handleUpgradeSuccess}
      />
    </>
  );
}
