/**
 * Viewings Calendar Component
 * Week/day view calendar for property viewings with status color coding,
 * broker filtering, viewing detail panel, and status action buttons
 */

"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import dynamic from "next/dynamic";
import type { Lang } from "@/lib/config";
import {
  ChevronLeft,
  ChevronRight,
  Plus,
  Loader2,
  Calendar,
  User,
  Building2,
  Filter,
  Phone,
  Mail,
  RefreshCw,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Eye,
  X,
  Upload,
} from "lucide-react";

const CreateViewingModal = dynamic(() => import("./CreateViewingModal"), {
  ssr: false,
});
const ViewingFeedbackModal = dynamic(() => import("./ViewingFeedbackModal"), {
  ssr: false,
});
const RealEstateBulkImportModal = dynamic(
  () => import("./RealEstateBulkImportModal"),
  { ssr: false },
);

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface Viewing {
  id: string;
  propertyTitle: string;
  propertyId: string;
  clientName: string;
  clientPhone: string;
  clientEmail?: string;
  viewingDate: string;
  viewingTime: string;
  duration: number;
  viewingType: string;
  brokerId: string;
  brokerName: string;
  status: string;
  notes?: string;
  feedbackRating?: number;
}

interface Broker {
  id: string;
  nameEn: string;
  nameAr: string;
}

interface ViewingsCalendarProps {
  lang: Lang;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function showToast(
  type: "success" | "error" | "info" | "warning",
  title: string,
  message: string,
) {
  const event = new CustomEvent("showToast", {
    detail: { type, title, message },
  });
  window.dispatchEvent(event);
}

const STATUS_COLORS: Record<
  string,
  { bg: string; border: string; text: string; dot: string }
> = {
  REQUESTED: {
    bg: "bg-amber-50",
    border: "border-amber-200",
    text: "text-amber-700",
    dot: "bg-amber-400",
  },
  CONFIRMED: {
    bg: "bg-blue-50",
    border: "border-blue-200",
    text: "text-blue-700",
    dot: "bg-blue-400",
  },
  COMPLETED: {
    bg: "bg-emerald-50",
    border: "border-emerald-200",
    text: "text-emerald-700",
    dot: "bg-emerald-400",
  },
  CANCELLED: {
    bg: "bg-red-50",
    border: "border-red-200",
    text: "text-red-700",
    dot: "bg-red-400",
  },
  NO_SHOW: {
    bg: "bg-slate-100",
    border: "border-slate-300",
    text: "text-slate-500",
    dot: "bg-slate-400",
  },
};

const STATUS_LABELS: Record<string, string> = {
  REQUESTED: "Requested",
  CONFIRMED: "Confirmed",
  COMPLETED: "Completed",
  CANCELLED: "Cancelled",
  NO_SHOW: "No Show",
};

const HOURS = Array.from({ length: 13 }, (_, i) => i + 7); // 7am - 7pm

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export default function ViewingsCalendar({ lang }: ViewingsCalendarProps) {
  const isAr = lang === "ar";

  const [viewings, setViewings] = useState<Viewing[]>([]);
  const [brokers, setBrokers] = useState<Broker[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentDate, setCurrentDate] = useState(new Date());
  const [viewMode, setViewMode] = useState<"week" | "day">("week");
  const [filterBroker, setFilterBroker] = useState("");
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [selectedSlot, setSelectedSlot] = useState<{
    date: string;
    time: string;
  } | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Detail panel
  const [selectedViewing, setSelectedViewing] = useState<Viewing | null>(null);
  const [showDetailPanel, setShowDetailPanel] = useState(false);
  const [updatingStatus, setUpdatingStatus] = useState(false);

  // Feedback
  const [showFeedbackModal, setShowFeedbackModal] = useState(false);

  // Get week dates — MUST be memoised, otherwise the array reference
  // changes on every render which causes fetchViewings (which depends
  // on weekDates) to be a new function on every render, which causes
  // the effect that depends on fetchViewings to re-fire forever, which
  // leaves the calendar stuck in a loading state.
  const weekDates = useMemo<Date[]>(() => {
    const dates: Date[] = [];
    const startOfWeek = new Date(currentDate);
    const day = startOfWeek.getDay();
    startOfWeek.setDate(startOfWeek.getDate() - day);
    for (let i = 0; i < 7; i++) {
      const d = new Date(startOfWeek);
      d.setDate(d.getDate() + i);
      dates.push(d);
    }
    return dates;
  }, [currentDate]);

  const fetchViewings = useCallback(async () => {
    try {
      setLoading(true);
      const startDate =
        viewMode === "week"
          ? weekDates[0].toISOString().split("T")[0]
          : currentDate.toISOString().split("T")[0];
      const endDate =
        viewMode === "week"
          ? weekDates[6].toISOString().split("T")[0]
          : currentDate.toISOString().split("T")[0];

      const params = new URLSearchParams();
      params.set("startDate", startDate);
      params.set("endDate", endDate);
      if (filterBroker) params.set("brokerId", filterBroker);

      const res = await fetch(
        `/api/real-estate/viewings/calendar?${params.toString()}`,
      );
      const data = await res.json();
      if (data.success) {
        setViewings(data.viewings || []);
      }
    } catch (error) {
      console.error("Failed to fetch viewings:", error);
    } finally {
      setLoading(false);
    }
  }, [currentDate, viewMode, filterBroker, weekDates]);

  const fetchBrokers = useCallback(async () => {
    try {
      const res = await fetch("/api/real-estate/brokers?activeOnly=true");
      const data = await res.json();
      if (data.success) {
        setBrokers(data.brokers || []);
      }
    } catch (error) {
      console.error("Failed to fetch brokers:", error);
    }
  }, []);

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

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

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await fetchViewings();
    setTimeout(() => setIsRefreshing(false), 500);
  };

  const navigatePrev = () => {
    const d = new Date(currentDate);
    d.setDate(d.getDate() - (viewMode === "week" ? 7 : 1));
    setCurrentDate(d);
  };

  const navigateNext = () => {
    const d = new Date(currentDate);
    d.setDate(d.getDate() + (viewMode === "week" ? 7 : 1));
    setCurrentDate(d);
  };

  const goToToday = () => {
    setCurrentDate(new Date());
  };

  const handleSlotClick = (date: Date, hour: number) => {
    const dateStr = date.toISOString().split("T")[0];
    const timeStr = `${String(hour).padStart(2, "0")}:00`;
    setSelectedSlot({ date: dateStr, time: timeStr });
    setShowCreateModal(true);
  };

  const handleViewingClick = (viewing: Viewing, e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedViewing(viewing);
    setShowDetailPanel(true);
  };

  const getViewingsForSlot = (date: Date, hour: number) => {
    const dateStr = date.toISOString().split("T")[0];
    return viewings.filter((v) => {
      const vDate = v.viewingDate.split("T")[0];
      const vHour = parseInt(v.viewingTime.split(":")[0]);
      return vDate === dateStr && vHour === hour;
    });
  };

  const getViewingColor = (status: string) => {
    return STATUS_COLORS[status] || STATUS_COLORS.REQUESTED;
  };

  const isToday = (date: Date) => {
    const today = new Date();
    return date.toDateString() === today.toDateString();
  };

  // Status update handler
  const updateViewingStatus = async (viewingId: string, newStatus: string) => {
    setUpdatingStatus(true);
    try {
      const res = await fetch(`/api/real-estate/viewings/${viewingId}/status`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: newStatus }),
      });
      const data = await res.json();
      if (data.success) {
        showToast(
          "success",
          "Status Updated",
          `Viewing marked as ${STATUS_LABELS[newStatus]}`,
        );
        fetchViewings();
        if (selectedViewing?.id === viewingId) {
          setSelectedViewing({ ...selectedViewing, status: newStatus });
        }
      } else {
        showToast("error", "Error", data.error || "Failed to update status");
      }
    } catch (error) {
      console.error("Failed to update viewing status:", error);
      showToast("error", "Error", "An error occurred while updating status");
    } finally {
      setUpdatingStatus(false);
    }
  };

  return (
    <>
      <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">
                  {isAr ? "تقويم المعاينات" : "Viewings Calendar"}
                </h2>
                <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"
                >
                  <RefreshCw
                    className={`w-3.5 h-3.5 ${isRefreshing ? "animate-spin" : ""}`}
                  />
                </button>
              </div>
              <p className="text-sm text-slate-500 mt-0.5">
                {isAr ? "جدول معاينات العقارات" : "Property viewing schedule"}
              </p>
            </div>
            <div className="flex items-center gap-2">
              {/* View Toggle */}
              <div className="flex items-center rounded-lg border border-slate-200 overflow-hidden">
                <button
                  onClick={() => setViewMode("week")}
                  className={`px-3 py-2 text-xs font-medium transition-colors ${
                    viewMode === "week"
                      ? "bg-brand-green text-white"
                      : "bg-white text-slate-500 hover:bg-slate-50"
                  }`}
                >
                  {isAr ? "أسبوع" : "Week"}
                </button>
                <button
                  onClick={() => setViewMode("day")}
                  className={`px-3 py-2 text-xs font-medium transition-colors ${
                    viewMode === "day"
                      ? "bg-brand-green text-white"
                      : "bg-white text-slate-500 hover:bg-slate-50"
                  }`}
                >
                  {isAr ? "يوم" : "Day"}
                </button>
              </div>

              {/* Broker Filter */}
              <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={filterBroker}
                  onChange={(e) => setFilterBroker(e.target.value)}
                  className="appearance-none rounded-xl border border-slate-200 bg-slate-50 pl-9 pr-8 py-2 text-xs font-medium text-slate-700 focus:border-brand-green focus:bg-white focus:outline-none transition-all"
                >
                  <option value="">
                    {isAr ? "جميع الوسطاء" : "All Brokers"}
                  </option>
                  {brokers.map((b) => (
                    <option key={b.id} value={b.id}>
                      {isAr ? b.nameAr : b.nameEn}
                    </option>
                  ))}
                </select>
              </div>

              <button
                onClick={() => setShowImportModal(true)}
                className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
              >
                <Upload className="w-4 h-4" />
                <span className="hidden sm:inline">
                  {isAr ? "استيراد CSV" : "Import CSV"}
                </span>
              </button>
              <button
                onClick={() => {
                  setSelectedSlot(null);
                  setShowCreateModal(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">
                  {isAr ? "جدولة معاينة" : "New Viewing"}
                </span>
              </button>
            </div>
          </div>

          {/* Date Navigation */}
          <div className="mt-4 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <button
                onClick={navigatePrev}
                className="p-2 rounded-lg border border-slate-200 hover:bg-slate-50 transition-colors"
              >
                <ChevronLeft className="w-4 h-4 text-slate-600" />
              </button>
              <button
                onClick={goToToday}
                className="px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-50 transition-colors"
              >
                {isAr ? "اليوم" : "Today"}
              </button>
              <button
                onClick={navigateNext}
                className="p-2 rounded-lg border border-slate-200 hover:bg-slate-50 transition-colors"
              >
                <ChevronRight className="w-4 h-4 text-slate-600" />
              </button>
            </div>
            <h3 className="text-sm font-bold text-slate-800">
              {viewMode === "week" ? (
                <>
                  {weekDates[0].toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                    month: "short",
                    day: "numeric",
                  })}
                  {" - "}
                  {weekDates[6].toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                    month: "short",
                    day: "numeric",
                    year: "numeric",
                  })}
                </>
              ) : (
                currentDate.toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                  weekday: "long",
                  month: "long",
                  day: "numeric",
                  year: "numeric",
                })
              )}
            </h3>
          </div>

          {/* Status Legend */}
          <div className="mt-3 flex flex-wrap items-center gap-4">
            {Object.entries(STATUS_LABELS).map(([key, label]) => {
              const color = STATUS_COLORS[key];
              return (
                <span
                  key={key}
                  className="flex items-center gap-1.5 text-xs text-slate-500"
                >
                  <span className={`w-2.5 h-2.5 rounded-full ${color.dot}`} />
                  {label}
                </span>
              );
            })}
          </div>
        </div>

        {/* Calendar Grid */}
        <div className="overflow-x-auto">
          {loading ? (
            <div className="flex items-center justify-center py-16">
              <Loader2 className="w-8 h-8 text-brand-green animate-spin" />
            </div>
          ) : (
            <table className="w-full min-w-[700px]">
              <thead>
                <tr>
                  <th className="w-16 p-2 border-b border-r border-slate-200 bg-slate-50 text-xs font-medium text-slate-500">
                    {isAr ? "الوقت" : "Time"}
                  </th>
                  {(viewMode === "week" ? weekDates : [currentDate]).map(
                    (date) => (
                      <th
                        key={date.toISOString()}
                        className={`p-2 border-b border-r border-slate-200 text-center ${
                          isToday(date) ? "bg-emerald-50" : "bg-slate-50"
                        }`}
                      >
                        <p className="text-xs font-medium text-slate-500">
                          {date.toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                            weekday: "short",
                          })}
                        </p>
                        <p
                          className={`text-sm font-bold ${isToday(date) ? "text-brand-green" : "text-slate-800"}`}
                        >
                          {date.getDate()}
                        </p>
                      </th>
                    ),
                  )}
                </tr>
              </thead>
              <tbody>
                {HOURS.map((hour) => (
                  <tr key={hour}>
                    <td className="p-2 border-b border-r border-slate-200 bg-slate-50 text-xs text-slate-500 text-center align-top">
                      {`${String(hour).padStart(2, "0")}:00`}
                    </td>
                    {(viewMode === "week" ? weekDates : [currentDate]).map(
                      (date) => {
                        const slotViewings = getViewingsForSlot(date, hour);
                        return (
                          <td
                            key={`${date.toISOString()}-${hour}`}
                            className={`p-1 border-b border-r border-slate-200 align-top min-h-[60px] h-16 cursor-pointer hover:bg-emerald-50/50 transition-colors ${
                              isToday(date) ? "bg-emerald-50/30" : ""
                            }`}
                            onClick={() => handleSlotClick(date, hour)}
                          >
                            {slotViewings.map((viewing) => {
                              const color = getViewingColor(viewing.status);
                              return (
                                <div
                                  key={viewing.id}
                                  className={`rounded-md border px-2 py-1 mb-1 text-[10px] leading-tight cursor-pointer transition-all hover:shadow-md hover:-translate-y-0.5 ${color.bg} ${color.border}`}
                                  onClick={(e) =>
                                    handleViewingClick(viewing, e)
                                  }
                                >
                                  <div className="flex items-center gap-1">
                                    <span
                                      className={`w-1.5 h-1.5 rounded-full ${color.dot} shrink-0`}
                                    />
                                    <span className={`font-bold ${color.text}`}>
                                      {viewing.viewingTime}
                                    </span>
                                  </div>
                                  <p className="font-medium text-slate-800 truncate mt-0.5">
                                    {viewing.clientName}
                                  </p>
                                  <p className="truncate text-slate-500">
                                    {viewing.propertyTitle}
                                  </p>
                                </div>
                              );
                            })}
                          </td>
                        );
                      },
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {/* Viewing Detail Side Panel */}
      {showDetailPanel && selectedViewing && (
        <div
          className="fixed inset-0 z-50 flex justify-end"
          onClick={() => setShowDetailPanel(false)}
        >
          <div className="absolute inset-0 bg-slate-900/50 backdrop-blur-sm" />
          <div
            className="relative w-full max-w-md bg-white shadow-2xl overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Panel Header */}
            <div className="sticky top-0 bg-white border-b border-slate-100 p-5 z-10">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-bold text-slate-900">
                  {isAr ? "تفاصيل المعاينة" : "Viewing Details"}
                </h3>
                <button
                  onClick={() => setShowDetailPanel(false)}
                  className="flex h-9 w-9 items-center justify-center rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-all"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>

            {/* Panel Content */}
            <div className="p-5 space-y-5">
              {/* Status Badge */}
              <div>
                {(() => {
                  const color = getViewingColor(selectedViewing.status);
                  return (
                    <span
                      className={`inline-flex rounded-full px-3 py-1 text-xs font-semibold ${color.bg} ${color.text} border ${color.border}`}
                    >
                      {STATUS_LABELS[selectedViewing.status] ||
                        selectedViewing.status}
                    </span>
                  );
                })()}
              </div>

              {/* Property */}
              <div className="flex items-start gap-3 p-3 rounded-xl bg-slate-50 border border-slate-200">
                <Building2 className="w-5 h-5 text-brand-green mt-0.5 shrink-0" />
                <div>
                  <p className="text-sm font-bold text-slate-900">
                    {selectedViewing.propertyTitle}
                  </p>
                  <p className="text-xs text-slate-500 mt-0.5 capitalize">
                    {selectedViewing.viewingType.replace(/_/g, " ")}
                  </p>
                </div>
              </div>

              {/* Date/Time */}
              <div className="flex items-center gap-3 p-3 rounded-xl bg-slate-50 border border-slate-200">
                <Calendar className="w-5 h-5 text-blue-500 shrink-0" />
                <div>
                  <p className="text-sm font-semibold text-slate-900">
                    {new Date(selectedViewing.viewingDate).toLocaleDateString(
                      isAr ? "ar-SA" : "en-US",
                      {
                        weekday: "long",
                        month: "long",
                        day: "numeric",
                        year: "numeric",
                      },
                    )}
                  </p>
                  <p className="text-xs text-slate-500 mt-0.5">
                    {selectedViewing.viewingTime} ({selectedViewing.duration}{" "}
                    min)
                  </p>
                </div>
              </div>

              {/* Client Info */}
              <div>
                <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                  {isAr ? "العميل" : "Client"}
                </h4>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm text-slate-700">
                    <User className="w-4 h-4 text-slate-400" />
                    <span className="font-medium">
                      {selectedViewing.clientName}
                    </span>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-slate-700">
                    <Phone className="w-4 h-4 text-slate-400" />
                    <span>{selectedViewing.clientPhone}</span>
                  </div>
                  {selectedViewing.clientEmail && (
                    <div className="flex items-center gap-2 text-sm text-slate-700">
                      <Mail className="w-4 h-4 text-slate-400" />
                      <span>{selectedViewing.clientEmail}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Broker */}
              {selectedViewing.brokerName && (
                <div>
                  <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                    {isAr ? "الوسيط" : "Assigned Broker"}
                  </h4>
                  <p className="text-sm font-medium text-slate-700">
                    {selectedViewing.brokerName}
                  </p>
                </div>
              )}

              {/* Notes */}
              {selectedViewing.notes && (
                <div>
                  <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                    {isAr ? "ملاحظات" : "Notes"}
                  </h4>
                  <p className="text-sm text-slate-600 whitespace-pre-wrap">
                    {selectedViewing.notes}
                  </p>
                </div>
              )}

              {/* Action Buttons */}
              <div>
                <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3">
                  {isAr ? "الإجراءات" : "Actions"}
                </h4>
                <div className="grid grid-cols-2 gap-2">
                  {selectedViewing.status === "REQUESTED" && (
                    <button
                      onClick={() =>
                        updateViewingStatus(selectedViewing.id, "CONFIRMED")
                      }
                      disabled={updatingStatus}
                      className="flex items-center justify-center gap-2 rounded-xl bg-blue-500 px-3 py-2.5 text-sm font-semibold text-white hover:bg-blue-600 transition-all disabled:opacity-50"
                    >
                      {updatingStatus ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <CheckCircle2 className="w-4 h-4" />
                      )}
                      {isAr ? "تأكيد" : "Confirm"}
                    </button>
                  )}
                  {(selectedViewing.status === "CONFIRMED" ||
                    selectedViewing.status === "REQUESTED") && (
                    <button
                      onClick={() =>
                        updateViewingStatus(selectedViewing.id, "COMPLETED")
                      }
                      disabled={updatingStatus}
                      className="flex items-center justify-center gap-2 rounded-xl bg-emerald-500 px-3 py-2.5 text-sm font-semibold text-white hover:bg-emerald-600 transition-all disabled:opacity-50"
                    >
                      {updatingStatus ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <CheckCircle2 className="w-4 h-4" />
                      )}
                      {isAr ? "مكتمل" : "Complete"}
                    </button>
                  )}
                  {selectedViewing.status !== "CANCELLED" &&
                    selectedViewing.status !== "COMPLETED" &&
                    selectedViewing.status !== "NO_SHOW" && (
                      <button
                        onClick={() =>
                          updateViewingStatus(selectedViewing.id, "CANCELLED")
                        }
                        disabled={updatingStatus}
                        className="flex items-center justify-center gap-2 rounded-xl bg-red-500 px-3 py-2.5 text-sm font-semibold text-white hover:bg-red-600 transition-all disabled:opacity-50"
                      >
                        {updatingStatus ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <XCircle className="w-4 h-4" />
                        )}
                        {isAr ? "إلغاء" : "Cancel"}
                      </button>
                    )}
                  {(selectedViewing.status === "CONFIRMED" ||
                    selectedViewing.status === "REQUESTED") && (
                    <button
                      onClick={() =>
                        updateViewingStatus(selectedViewing.id, "NO_SHOW")
                      }
                      disabled={updatingStatus}
                      className="flex items-center justify-center gap-2 rounded-xl bg-slate-500 px-3 py-2.5 text-sm font-semibold text-white hover:bg-slate-600 transition-all disabled:opacity-50"
                    >
                      {updatingStatus ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <AlertCircle className="w-4 h-4" />
                      )}
                      {isAr ? "لم يحضر" : "No Show"}
                    </button>
                  )}
                  {selectedViewing.status === "COMPLETED" && (
                    <button
                      onClick={() => setShowFeedbackModal(true)}
                      className="col-span-2 flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 px-3 py-2.5 text-sm font-semibold text-white hover:shadow-lg transition-all"
                    >
                      <Eye className="w-4 h-4" />
                      {isAr ? "إضافة تقييم" : "Add Feedback"}
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Bulk Import Modal */}
      <RealEstateBulkImportModal
        lang={lang}
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
        onImportComplete={() => {
          fetchViewings();
          setShowImportModal(false);
        }}
        initialEntityType="viewings"
      />

      {/* Create Viewing Modal */}
      <CreateViewingModal
        lang={lang}
        isOpen={showCreateModal}
        onClose={() => {
          setShowCreateModal(false);
          setSelectedSlot(null);
        }}
        onSuccess={() => {
          setShowCreateModal(false);
          setSelectedSlot(null);
          fetchViewings();
        }}
        preselectedDate={selectedSlot?.date}
        preselectedTime={selectedSlot?.time}
      />

      {/* Feedback Modal */}
      {selectedViewing && (
        <ViewingFeedbackModal
          lang={lang}
          viewingId={selectedViewing.id}
          isOpen={showFeedbackModal}
          onClose={() => setShowFeedbackModal(false)}
          onSuccess={() => {
            setShowFeedbackModal(false);
            fetchViewings();
            showToast(
              "success",
              "Feedback Saved",
              "Viewing feedback has been recorded",
            );
          }}
        />
      )}
    </>
  );
}
