/**
 * Appointments List Component
 * Date-grouped booking list with deposit status badges and CRM integrations
 */

"use client";

import { useState, useEffect } from "react";
import type { Lang } from "@/lib/config";
// Booking shape used for review request dialog state — must match ReviewRequestDialog's Booking interface
interface Booking {
  id: string;
  customerName: string;
  customerPhone: string;
  customerEmail?: string | null;
  service: string;
  [key: string]: unknown;
}
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";
import {
  Calendar,
  Settings,
  Link2,
  CheckCircle2,
  AlertCircle,
  Clock,
  Plus,
  Filter,
  RefreshCw,
  ChevronRight,
  CreditCard,
  Loader2,
  Copy,
  Check,
} from "lucide-react";
import dynamic from "next/dynamic";

// Lazy load modals to prevent circular dependency issues
const CRMIntegrationsModal = dynamic(() => import("./CRMIntegrationsModal"), {
  ssr: false,
});
const CreateAppointmentModal = dynamic(
  () => import("./CreateAppointmentModal"),
  {
    ssr: false,
  },
);
const AppointmentDetailsModal = dynamic(
  () => import("./AppointmentDetailsModal"),
  {
    ssr: false,
  },
);
const AppointmentTypesManager = dynamic(
  () => import("./AppointmentTypesManager"),
  {
    ssr: false,
  },
);
const ReviewRequestDialog = dynamic(
  () => import("@/components/dashboard/reviews/ReviewRequestDialog"),
  { ssr: false },
);

interface Integration {
  id: string;
  type: string;
  status: "connected" | "disconnected" | "error" | "pending_setup";
  lastSyncAt: string | null;
}

interface AppointmentsListProps {
  lang: Lang;
  bookings: any[];
  onRefresh: () => void;
  userIndustry?: string | null;
}

export default function AppointmentsList({
  lang,
  bookings,
  onRefresh,
  userIndustry,
}: AppointmentsListProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [filterDeposit, setFilterDeposit] = useState<string>("all");
  const [showIntegrationsModal, setShowIntegrationsModal] = useState(false);
  const [showCreateAppointmentModal, setShowCreateAppointmentModal] =
    useState(false);
  const [connectedIntegrations, setConnectedIntegrations] = useState<
    Integration[]
  >([]);
  const [loadingIntegrations, setLoadingIntegrations] = useState(true);
  const [lastRefresh, setLastRefresh] = useState<Date>(new Date());
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Payment link state
  const [sendingPaymentLink, setSendingPaymentLink] = useState<string | null>(
    null,
  );
  const [paymentLinkSuccess, setPaymentLinkSuccess] = useState<string | null>(
    null,
  );
  const [paymentLinkError, setPaymentLinkError] = useState<string | null>(null);
  const [copiedLink, setCopiedLink] = useState<string | null>(null);

  // Mark as paid state
  const [markingAsPaid, setMarkingAsPaid] = useState<string | null>(null);
  const [markPaidSuccess, setMarkPaidSuccess] = useState<string | null>(null);

  // Details modal state
  const [selectedBooking, setSelectedBooking] = useState<any | null>(null);
  const [showDetailsModal, setShowDetailsModal] = useState(false);
  const [showTypesManager, setShowTypesManager] = useState(false);
  const [subTab, setSubTab] = useState<"appointments" | "service-types">(
    "appointments",
  );

  // Review request dialog state
  const [reviewDialogBooking, setReviewDialogBooking] =
    useState<Booking | null>(null);
  const [awaitingReviewIds, setAwaitingReviewIds] = useState<Set<string>>(
    new Set(),
  );
  const [autoSentReview, setAutoSentReview] = useState<{
    sent: boolean;
    channel?: "email" | "whatsapp";
  }>({ sent: false });

  // Handle refresh with animation
  const handleRefresh = async () => {
    setIsRefreshing(true);
    onRefresh();
    setLastRefresh(new Date());
    setTimeout(() => setIsRefreshing(false), 500);
  };

  // Auto-refresh every 30 seconds for appointments
  useEffect(() => {
    const interval = setInterval(() => {
      onRefresh();
      setLastRefresh(new Date());
    }, 30000);
    return () => clearInterval(interval);
  }, [onRefresh]);

  // Send payment link to customer
  const handleSendPaymentLink = async (
    bookingId: string,
    customerEmail: string | null,
  ) => {
    if (!customerEmail) {
      setPaymentLinkError(
        isAr ? "لا يوجد بريد إلكتروني للعميل" : "No customer email available",
      );
      setTimeout(() => setPaymentLinkError(null), 3000);
      return;
    }

    setSendingPaymentLink(bookingId);
    setPaymentLinkError(null);

    try {
      const response = await fetch(`/api/bookings/${bookingId}/payment-link`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ sendEmail: true, language: lang }),
      });

      const data = await response.json();

      if (data.success) {
        setPaymentLinkSuccess(bookingId);
        setTimeout(() => setPaymentLinkSuccess(null), 3000);

        // Copy link to clipboard
        if (data.paymentUrl) {
          await navigator.clipboard.writeText(data.paymentUrl);
          setCopiedLink(bookingId);
          setTimeout(() => setCopiedLink(null), 2000);
        }
      } else {
        setPaymentLinkError(
          data.error ||
            (isAr
              ? "فشل في إنشاء رابط الدفع"
              : "Failed to create payment link"),
        );
        setTimeout(() => setPaymentLinkError(null), 3000);
      }
    } catch (error) {
      console.error("Payment link error:", error);
      setPaymentLinkError(
        isAr ? "حدث خطأ أثناء إنشاء رابط الدفع" : "Error creating payment link",
      );
      setTimeout(() => setPaymentLinkError(null), 3000);
    } finally {
      setSendingPaymentLink(null);
    }
  };

  // Mark booking as paid manually
  const handleMarkAsPaid = async (bookingId: string) => {
    setMarkingAsPaid(bookingId);
    setPaymentLinkError(null);

    try {
      const response = await fetch(`/api/bookings/${bookingId}/mark-paid`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ paymentMethod: "manual" }),
      });

      const data = await response.json();

      if (data.success) {
        setMarkPaidSuccess(bookingId);
        // Refresh data to show updated status
        await handleRefresh();
        setTimeout(() => setMarkPaidSuccess(null), 3000);
      } else {
        setPaymentLinkError(
          data.error ||
            (isAr ? "فشل في تحديث الحالة" : "Failed to update status"),
        );
        setTimeout(() => setPaymentLinkError(null), 3000);
      }
    } catch (error) {
      console.error("Mark as paid error:", error);
      setPaymentLinkError(
        isAr ? "حدث خطأ أثناء تحديث الحالة" : "Error updating status",
      );
      setTimeout(() => setPaymentLinkError(null), 3000);
    } finally {
      setMarkingAsPaid(null);
    }
  };

  // Update booking status
  const handleStatusChange = async (bookingId: string, newStatus: string) => {
    try {
      const response = await fetch(`/api/bookings/${bookingId}/status`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: newStatus }),
      });

      const data = await response.json();

      if (data.success) {
        await handleRefresh();
        // Update the selected booking if it's open (use functional update to avoid stale closure)
        setSelectedBooking((prev: Record<string, unknown> | null) => {
          if (prev?.id === bookingId) {
            return { ...prev, status: newStatus };
          }
          return prev;
        });

        // When marked as completed, close details modal and open review request dialog
        if (newStatus === "completed") {
          const booking = bookings.find((b) => b.id === bookingId);
          if (booking && (booking.customerEmail || booking.customerPhone)) {
            setShowDetailsModal(false);
            setSelectedBooking(null);
            setAutoSentReview({
              sent: Boolean(data.reviewSent),
              channel: data.reviewChannel as "email" | "whatsapp" | undefined,
            });
            setReviewDialogBooking(booking);
          }
        }
      } else {
        setPaymentLinkError(
          data.error ||
            (isAr ? "فشل في تحديث الحالة" : "Failed to update status"),
        );
        setTimeout(() => setPaymentLinkError(null), 3000);
      }
    } catch (error) {
      console.error("Status update error:", error);
      setPaymentLinkError(
        isAr ? "حدث خطأ أثناء تحديث الحالة" : "Error updating status",
      );
      setTimeout(() => setPaymentLinkError(null), 3000);
    }
  };

  // Open details modal
  const handleViewDetails = (booking: any) => {
    setSelectedBooking(booking);
    setShowDetailsModal(true);
  };

  // Load connected integrations status
  useEffect(() => {
    const loadIntegrations = async () => {
      try {
        setLoadingIntegrations(true);
        const response = await fetch("/api/integrations");
        if (response.ok) {
          const data = await response.json();
          setConnectedIntegrations(
            (data.integrations || []).filter(
              (i: Integration) => i.status === "connected",
            ),
          );
        }
      } catch (error) {
        console.error("Failed to load integrations:", error);
      } finally {
        setLoadingIntegrations(false);
      }
    };
    loadIntegrations();
  }, []);

  // Group bookings by date
  const groupedBookings = bookings.reduce((groups: any, booking: any) => {
    const date = new Date(booking.appointmentDate).toDateString();
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(booking);
    return groups;
  }, {});

  // Filter bookings
  const filteredDates = Object.keys(groupedBookings).filter((date) => {
    const dateBookings = groupedBookings[date];
    return dateBookings.some((b: any) => {
      const statusMatch = filterStatus === "all" || b.status === filterStatus;
      const depositMatch =
        filterDeposit === "all" ||
        (filterDeposit === "paid" && b.depositPaid) ||
        (filterDeposit === "pending" && !b.depositPaid && b.depositAmount);
      return statusMatch && depositMatch;
    });
  });

  // Sort dates chronologically
  filteredDates.sort((a, b) => new Date(a).getTime() - new Date(b).getTime());

  // Calculate deposit statistics
  const depositStats = bookings.reduce(
    (stats, booking) => {
      if (booking.depositAmount || booking.totalAmount) {
        stats.total++;
        if (booking.depositPaid) {
          stats.paid++;
          stats.paidAmount += booking.depositAmount || 0;
        } else {
          stats.pending++;
          stats.pendingAmount += booking.depositAmount || 0;
        }
      }
      return stats;
    },
    { total: 0, paid: 0, pending: 0, paidAmount: 0, pendingAmount: 0 },
  );

  const getStatusBadge = (status: string) => {
    const badges: any = {
      pending: {
        bg: "bg-amber-100",
        text: "text-amber-700",
        label: dt.statusPending,
      },
      confirmed: {
        bg: "bg-emerald-100",
        text: "text-emerald-700",
        label: dt.statusConfirmed,
      },
      completed: {
        bg: "bg-slate-100",
        text: "text-slate-600",
        label: dt.statusCompleted,
      },
      cancelled: {
        bg: "bg-rose-100",
        text: "text-rose-700",
        label: dt.statusCancelled,
      },
      no_show: {
        bg: "bg-orange-100",
        text: "text-orange-700",
        label: isAr ? "لم يحضر" : "No-show",
      },
    };
    const badge = badges[status] || badges.pending;
    return (
      <span
        className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${badge.bg} ${badge.text}`}
      >
        {badge.label}
      </span>
    );
  };

  const getIntegrationIcon = (type: string) => {
    switch (type) {
      case "google_calendar":
        return (
          <svg className="w-4 h-4" 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>
        );
      case "outlook_calendar":
        return (
          <svg className="w-4 h-4" 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"
            />
          </svg>
        );
      case "salesforce":
        return (
          <svg className="w-4 h-4" 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>
        );
      case "hubspot":
        return (
          <svg className="w-4 h-4" 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.873z"
            />
          </svg>
        );
      default:
        return <Link2 className="w-4 h-4" />;
    }
  };

  return (
    <>
      {/* Sub-tab toggle */}
      <div className="flex gap-1 p-1 bg-slate-100 rounded-lg w-fit mb-4">
        <button
          onClick={() => setSubTab("appointments")}
          className={`px-4 py-1.5 rounded-md text-sm font-medium transition-all ${
            subTab === "appointments"
              ? "bg-white text-slate-800 shadow-sm"
              : "text-slate-500 hover:text-slate-700"
          }`}
        >
          {isAr ? "المواعيد" : "Appointments"}
        </button>
        <button
          onClick={() => setSubTab("service-types")}
          className={`px-4 py-1.5 rounded-md text-sm font-medium transition-all ${
            subTab === "service-types"
              ? "bg-white text-slate-800 shadow-sm"
              : "text-slate-500 hover:text-slate-700"
          }`}
        >
          {isAr ? "أنواع الخدمات" : "Service Types"}
        </button>
      </div>

      {subTab === "service-types" && (
        <AppointmentTypesManager lang={lang} userIndustry={userIndustry} />
      )}

      {subTab === "appointments" && (
        <>
          {/* Payment Link Error Toast */}
          {paymentLinkError && (
            <div className="mb-4 rounded-xl bg-red-50 border border-red-200 p-4 flex items-center gap-3 animate-fadeIn">
              <AlertCircle className="w-5 h-5 text-red-500 shrink-0" />
              <p className="text-sm text-red-700">{paymentLinkError}</p>
            </div>
          )}

          <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm overflow-hidden">
            {/* Header */}
            <div className="border-b border-slate-100 p-5">
              <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                  <div className="flex items-center gap-3">
                    <h2 className="text-lg font-bold text-slate-900">
                      {dt.appointments}
                    </h2>
                    {/* Refresh button with last update time */}
                    <button
                      onClick={handleRefresh}
                      disabled={isRefreshing}
                      className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50 px-2.5 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-100 hover:border-slate-300 transition-all disabled:opacity-50"
                      title={isAr ? "تحديث البيانات" : "Refresh data"}
                    >
                      <RefreshCw
                        className={`w-3.5 h-3.5 ${isRefreshing ? "animate-spin" : ""}`}
                      />
                      <span
                        className="hidden sm:inline"
                        suppressHydrationWarning
                      >
                        {lastRefresh.toLocaleTimeString(
                          isAr ? "ar-SA" : "en-US",
                          {
                            hour: "2-digit",
                            minute: "2-digit",
                          },
                        )}
                      </span>
                    </button>
                  </div>
                  <p className="text-sm text-slate-500 mt-0.5">
                    {dt.appointmentsDesc}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  {/* Connected Integrations Badge */}
                  {connectedIntegrations.length > 0 && (
                    <div className="hidden sm:flex items-center gap-1.5 rounded-full bg-emerald-50 border border-emerald-200 px-3 py-1.5">
                      <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
                      <div className="flex items-center gap-1">
                        {connectedIntegrations
                          .slice(0, 3)
                          .map((integration) => (
                            <span
                              key={integration.id}
                              className="flex items-center"
                              title={integration.type}
                            >
                              {getIntegrationIcon(integration.type)}
                            </span>
                          ))}
                      </div>
                      <span className="text-xs font-semibold text-emerald-700">
                        {isAr ? "متصل" : "Synced"}
                      </span>
                    </div>
                  )}

                  {/* Manage Services / Catalog Button */}
                  <button
                    onClick={() => setShowTypesManager(true)}
                    className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm hover:shadow-md hover:border-brand-green hover:-translate-y-0.5 transition-all"
                  >
                    <Settings className="w-4 h-4 text-slate-500" />
                    <span className="hidden sm:inline">
                      {isAr ? "إدارة الخدمات" : "Manage Services"}
                    </span>
                  </button>

                  {/* Integrations Settings Button */}
                  <button
                    onClick={() => setShowIntegrationsModal(true)}
                    className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm hover:shadow-md hover:border-brand-green hover:-translate-y-0.5 transition-all"
                  >
                    <Settings className="w-4 h-4 text-slate-500" />
                    <span className="hidden sm:inline">
                      {isAr ? "ربط التقويم" : "Connect Calendar"}
                    </span>
                    <span className="sm:hidden">
                      <Link2 className="w-4 h-4" />
                    </span>
                  </button>

                  {/* Create Booking Button */}
                  <button
                    onClick={() => setShowCreateAppointmentModal(true)}
                    className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 hover:-translate-y-0.5 transition-all"
                  >
                    <Plus className="w-4 h-4" />
                    <span className="hidden sm:inline">
                      {dt.createManualBooking}
                    </span>
                  </button>
                </div>
              </div>

              {/* Integration Status Banner */}
              {connectedIntegrations.length > 0 && (
                <div className="mt-4 rounded-xl bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200/50 p-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-500">
                        <RefreshCw className="w-4 h-4 text-white" />
                      </div>
                      <div>
                        <p className="text-sm font-semibold text-emerald-900">
                          {isAr ? "المزامنة نشطة" : "Sync Active"}
                        </p>
                        <p className="text-xs text-emerald-700">
                          {isAr
                            ? `متصل بـ ${connectedIntegrations.length} خدمة`
                            : `Connected to ${connectedIntegrations.length} service${connectedIntegrations.length > 1 ? "s" : ""}`}
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={() => setShowIntegrationsModal(true)}
                      className="text-xs font-semibold text-emerald-700 hover:text-emerald-900 flex items-center gap-1 transition-colors"
                    >
                      {isAr ? "إدارة" : "Manage"}
                      <ChevronRight className="w-3 h-3" />
                    </button>
                  </div>
                </div>
              )}

              {/* No Integration Banner */}
              {!loadingIntegrations && connectedIntegrations.length === 0 && (
                <div className="mt-4 rounded-xl bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200/50 p-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-amber-500">
                        <Calendar className="w-4 h-4 text-white" />
                      </div>
                      <div>
                        <p className="text-sm font-semibold text-amber-900">
                          {isAr ? "مزامنة التقويم" : "Sync Your Calendar"}
                        </p>
                        <p className="text-xs text-amber-700">
                          {isAr
                            ? "اربط Google Calendar أو Outlook لمزامنة المواعيد تلقائياً"
                            : "Connect Google Calendar or Outlook to auto-sync appointments"}
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={() => setShowIntegrationsModal(true)}
                      className="inline-flex items-center gap-1.5 rounded-lg bg-amber-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-amber-600 transition-colors"
                    >
                      <Link2 className="w-3 h-3" />
                      {isAr ? "ربط الآن" : "Connect Now"}
                    </button>
                  </div>
                </div>
              )}

              {/* Filters */}
              <div className="mt-4 flex flex-wrap gap-3">
                <div className="relative">
                  <Filter className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />
                  <select
                    value={filterStatus}
                    onChange={(e) => setFilterStatus(e.target.value)}
                    className="appearance-none rounded-xl border border-slate-200 bg-slate-50 pl-9 pr-8 py-2.5 text-sm font-medium text-slate-700 focus:border-brand-green focus:bg-white focus:outline-none focus:ring-2 focus:ring-brand-green/20 transition-all"
                  >
                    <option value="all">
                      {isAr ? "جميع الحالات" : "All statuses"}
                    </option>
                    <option value="pending">{dt.statusPending}</option>
                    <option value="confirmed">{dt.statusConfirmed}</option>
                    <option value="completed">{dt.statusCompleted}</option>
                    <option value="cancelled">{dt.statusCancelled}</option>
                  </select>
                </div>

                <select
                  value={filterDeposit}
                  onChange={(e) => setFilterDeposit(e.target.value)}
                  className="appearance-none rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm font-medium text-slate-700 focus:border-brand-green focus:bg-white focus:outline-none focus:ring-2 focus:ring-brand-green/20 transition-all"
                >
                  <option value="all">{dt.allDeposits}</option>
                  <option value="paid">{dt.depositPaid}</option>
                  <option value="pending">{dt.depositPending}</option>
                </select>
              </div>

              {/* Deposit Statistics Summary */}
              {depositStats.total > 0 && (
                <div className="mt-4 grid grid-cols-2 sm:grid-cols-4 gap-3">
                  <div className="rounded-xl bg-slate-50 border border-slate-200 p-3 text-center">
                    <p className="text-2xl font-bold text-slate-700">
                      {depositStats.total}
                    </p>
                    <p className="text-xs text-slate-500">
                      {isAr ? "إجمالي الحجوزات" : "Total Bookings"}
                    </p>
                  </div>
                  <div className="rounded-xl bg-emerald-50 border border-emerald-200 p-3 text-center">
                    <p className="text-2xl font-bold text-emerald-600">
                      {depositStats.paid}
                    </p>
                    <p className="text-xs text-emerald-700">
                      {isAr ? "عربونات مدفوعة" : "Deposits Paid"}
                    </p>
                  </div>
                  <div className="rounded-xl bg-amber-50 border border-amber-200 p-3 text-center">
                    <p className="text-2xl font-bold text-amber-600">
                      {depositStats.pending}
                    </p>
                    <p className="text-xs text-amber-700">
                      {isAr ? "عربونات معلقة" : "Deposits Pending"}
                    </p>
                  </div>
                  <div className="rounded-xl bg-violet-50 border border-violet-200 p-3 text-center">
                    <p className="text-2xl font-bold text-violet-600">
                      QAR {depositStats.paidAmount.toFixed(0)}
                    </p>
                    <p className="text-xs text-violet-700">
                      {isAr ? "إجمالي المحصل" : "Total Collected"}
                    </p>
                  </div>
                </div>
              )}
            </div>

            {/* Grouped Appointments */}
            <div className="divide-y divide-slate-100">
              {filteredDates.length === 0 ? (
                <div className="flex flex-col items-center justify-center p-12 text-center">
                  <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
                    <Calendar className="w-8 h-8 text-slate-400" />
                  </div>
                  <p className="text-sm font-medium text-slate-600">
                    {dt.noAppointmentsYet}
                  </p>
                  <p className="mt-1 text-xs text-slate-400 max-w-[250px]">
                    {dt.noAppointmentsYetDesc}
                  </p>
                  <button
                    onClick={() => setShowCreateAppointmentModal(true)}
                    className="mt-4 inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
                  >
                    <Plus className="w-4 h-4" />
                    {dt.createManualBooking}
                  </button>
                </div>
              ) : (
                filteredDates.map((date) => {
                  const dateBookings = groupedBookings[date].filter(
                    (b: any) => {
                      const statusMatch =
                        filterStatus === "all" || b.status === filterStatus;
                      const depositMatch =
                        filterDeposit === "all" ||
                        (filterDeposit === "paid" && b.depositPaid) ||
                        (filterDeposit === "pending" &&
                          !b.depositPaid &&
                          b.depositAmount);
                      return statusMatch && depositMatch;
                    },
                  );

                  if (dateBookings.length === 0) return null;

                  const dateObj = new Date(date);
                  const isToday =
                    dateObj.toDateString() === new Date().toDateString();
                  const isTomorrow =
                    dateObj.toDateString() ===
                    new Date(Date.now() + 86400000).toDateString();

                  let dateLabel = dateObj.toLocaleDateString(
                    isAr ? "ar-SA" : "en-US",
                    {
                      weekday: "long",
                      year: "numeric",
                      month: "long",
                      day: "numeric",
                    },
                  );

                  if (isToday)
                    dateLabel = `${isAr ? "اليوم" : "Today"} - ${dateLabel}`;
                  if (isTomorrow)
                    dateLabel = `${isAr ? "غداً" : "Tomorrow"} - ${dateLabel}`;

                  return (
                    <div key={date} className="p-5">
                      {/* Date Header */}
                      <div className="flex items-center gap-2 mb-4">
                        <h3 className="text-sm font-bold text-slate-900">
                          {dateLabel}
                        </h3>
                        {isToday && (
                          <span className="rounded-full bg-brand-green px-2 py-0.5 text-xs font-semibold text-white">
                            {isAr ? "اليوم" : "Today"}
                          </span>
                        )}
                        <span className="text-xs text-slate-400">
                          ({dateBookings.length}{" "}
                          {isAr ? "موعد" : "appointments"})
                        </span>
                      </div>

                      {/* Bookings for this date */}
                      <div className="space-y-3">
                        {dateBookings.map((booking: any) => (
                          <div
                            key={booking.id}
                            className="group flex items-center justify-between rounded-xl border border-slate-200 bg-slate-50/50 p-4 transition-all hover:border-brand-green hover:bg-white hover:shadow-md"
                          >
                            {/* Left: Time + Customer */}
                            <div className="flex items-center gap-4">
                              <div className="flex flex-col items-center justify-center w-16 rounded-lg bg-white border border-slate-200 py-2 group-hover:border-brand-green transition-colors">
                                <p className="text-sm font-bold text-brand-green">
                                  {booking.appointmentTime}
                                </p>
                                <p className="text-[10px] text-slate-400">
                                  {booking.duration}m
                                </p>
                              </div>
                              <div>
                                <p className="text-sm font-semibold text-slate-900">
                                  {booking.customerName}
                                </p>
                                <p className="text-xs text-slate-600">
                                  {booking.service}
                                </p>
                                <p className="text-xs text-slate-400">
                                  {booking.customerPhone}
                                </p>
                              </div>
                            </div>

                            {/* Right: Status + Deposit + Actions */}
                            <div className="flex items-center gap-3">
                              {/* Deposit Badge - Always visible */}
                              {booking.depositPaid && (
                                <span className="inline-flex items-center gap-1 sm:gap-1.5 rounded-full bg-emerald-100 px-2 sm:px-3 py-1 text-[10px] sm:text-xs font-semibold text-emerald-700 ring-2 ring-emerald-200 shadow-sm">
                                  <CheckCircle2 className="w-3 h-3" />
                                  <span className="hidden xs:inline">
                                    {dt.depositPaidBadge}
                                  </span>
                                  <span className="xs:hidden">
                                    {isAr ? "مدفوع" : "Paid"}
                                  </span>
                                  {booking.depositAmount && (
                                    <span className="hidden sm:inline">
                                      - QAR {booking.depositAmount}
                                    </span>
                                  )}
                                </span>
                              )}
                              {!booking.depositPaid &&
                                booking.depositAmount && (
                                  <span className="inline-flex items-center gap-1 sm:gap-1.5 rounded-full bg-amber-100 px-2 sm:px-3 py-1 text-[10px] sm:text-xs font-semibold text-amber-700">
                                    <Clock className="w-3 h-3" />
                                    <span className="hidden xs:inline">
                                      {dt.depositPendingBadge}
                                    </span>
                                    <span className="xs:hidden">
                                      {isAr ? "معلق" : "Due"}
                                    </span>
                                    <span className="hidden sm:inline">
                                      - QAR {booking.depositAmount}
                                    </span>
                                  </span>
                                )}

                              {/* Status Badge */}
                              {getStatusBadge(booking.status)}

                              {/* Awaiting Review Badge */}
                              {awaitingReviewIds.has(booking.id) && (
                                <span className="inline-flex items-center gap-1 rounded-full bg-amber-50 border border-amber-200 px-2.5 py-1 text-[10px] font-semibold text-amber-700">
                                  <Clock className="w-3 h-3" />
                                  <span className="hidden sm:inline">
                                    {isAr
                                      ? "بانتظار التقييم"
                                      : "Awaiting Review"}
                                  </span>
                                </span>
                              )}

                              {/* Send Payment Link Button - for unpaid deposits */}
                              {!booking.depositPaid &&
                                (booking.depositAmount ||
                                  booking.totalAmount) && (
                                  <button
                                    onClick={() =>
                                      handleSendPaymentLink(
                                        booking.id,
                                        booking.customerEmail,
                                      )
                                    }
                                    disabled={sendingPaymentLink === booking.id}
                                    className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-all ${
                                      paymentLinkSuccess === booking.id
                                        ? "bg-emerald-100 text-emerald-700 border border-emerald-200"
                                        : sendingPaymentLink === booking.id
                                          ? "bg-slate-100 text-slate-500 border border-slate-200 cursor-wait"
                                          : "bg-violet-100 text-violet-700 border border-violet-200 hover:bg-violet-200"
                                    }`}
                                    title={
                                      booking.customerEmail
                                        ? isAr
                                          ? "إرسال رابط الدفع عبر البريد الإلكتروني"
                                          : "Send payment link via email"
                                        : isAr
                                          ? "لا يوجد بريد إلكتروني"
                                          : "No email available"
                                    }
                                  >
                                    {sendingPaymentLink === booking.id ? (
                                      <>
                                        <Loader2 className="w-3 h-3 animate-spin" />
                                        <span className="hidden sm:inline">
                                          {isAr
                                            ? "جاري الإرسال..."
                                            : "Sending..."}
                                        </span>
                                      </>
                                    ) : paymentLinkSuccess === booking.id ? (
                                      <>
                                        <Check className="w-3 h-3" />
                                        <span className="hidden sm:inline">
                                          {isAr ? "تم الإرسال!" : "Sent!"}
                                        </span>
                                      </>
                                    ) : copiedLink === booking.id ? (
                                      <>
                                        <Copy className="w-3 h-3" />
                                        <span className="hidden sm:inline">
                                          {isAr ? "تم النسخ!" : "Copied!"}
                                        </span>
                                      </>
                                    ) : (
                                      <>
                                        <CreditCard className="w-3 h-3" />
                                        <span className="hidden sm:inline">
                                          {isAr ? "رابط الدفع" : "Payment Link"}
                                        </span>
                                      </>
                                    )}
                                  </button>
                                )}

                              {/* Mark as Paid Button - for unpaid deposits */}
                              {!booking.depositPaid &&
                                (booking.depositAmount ||
                                  booking.totalAmount) && (
                                  <button
                                    onClick={() => handleMarkAsPaid(booking.id)}
                                    disabled={markingAsPaid === booking.id}
                                    className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-all ${
                                      markPaidSuccess === booking.id
                                        ? "bg-emerald-100 text-emerald-700 border border-emerald-200"
                                        : markingAsPaid === booking.id
                                          ? "bg-slate-100 text-slate-500 border border-slate-200 cursor-wait"
                                          : "bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100"
                                    }`}
                                    title={
                                      isAr
                                        ? "تحديد كمدفوع يدوياً"
                                        : "Mark as paid manually"
                                    }
                                  >
                                    {markingAsPaid === booking.id ? (
                                      <>
                                        <Loader2 className="w-3 h-3 animate-spin" />
                                        <span className="hidden sm:inline">
                                          {isAr
                                            ? "جاري التحديث..."
                                            : "Updating..."}
                                        </span>
                                      </>
                                    ) : markPaidSuccess === booking.id ? (
                                      <>
                                        <CheckCircle2 className="w-3 h-3" />
                                        <span className="hidden sm:inline">
                                          {isAr ? "تم!" : "Done!"}
                                        </span>
                                      </>
                                    ) : (
                                      <>
                                        <CheckCircle2 className="w-3 h-3" />
                                        <span className="hidden sm:inline">
                                          {isAr ? "تم الدفع" : "Mark Paid"}
                                        </span>
                                      </>
                                    )}
                                  </button>
                                )}

                              {/* Actions Menu */}
                              <button
                                onClick={() => handleViewDetails(booking)}
                                className="rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:border-brand-green hover:text-brand-green transition-all"
                              >
                                {dt.viewDetails}
                              </button>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })
              )}
            </div>
          </div>
        </>
      )}

      {/* CRM Integrations Modal */}
      <CRMIntegrationsModal
        lang={lang}
        isOpen={showIntegrationsModal}
        onClose={() => setShowIntegrationsModal(false)}
        onIntegrationChange={onRefresh}
      />

      {/* Create Appointment Modal */}
      <CreateAppointmentModal
        lang={lang}
        isOpen={showCreateAppointmentModal}
        onClose={() => setShowCreateAppointmentModal(false)}
        onSuccess={onRefresh}
        userIndustry={userIndustry}
      />

      {/* Appointment Details Modal */}
      <AppointmentDetailsModal
        lang={lang}
        booking={selectedBooking}
        isOpen={showDetailsModal}
        onClose={() => {
          setShowDetailsModal(false);
          setSelectedBooking(null);
        }}
        onStatusChange={handleStatusChange}
        onSendPaymentLink={(bookingId) => {
          const booking = bookings.find((b) => b.id === bookingId);
          if (booking) {
            handleSendPaymentLink(bookingId, booking.customerEmail);
          }
        }}
      />

      {/* Services / Catalog Manager */}
      <AppointmentTypesManager
        lang={lang}
        isOpen={showTypesManager}
        onClose={() => setShowTypesManager(false)}
      />

      {/* Review Request Dialog — opens automatically when appointment is marked completed */}
      <ReviewRequestDialog
        lang={lang}
        booking={reviewDialogBooking}
        isOpen={reviewDialogBooking !== null}
        onClose={() => setReviewDialogBooking(null)}
        autoSent={autoSentReview.sent}
        autoSentChannel={autoSentReview.channel}
        onSent={(bookingId) => {
          setAwaitingReviewIds((prev) => new Set([...prev, bookingId]));
          setReviewDialogBooking(null);
        }}
      />
    </>
  );
}
