"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import {
  X,
  Calendar,
  Clock,
  User,
  Phone,
  Mail,
  FileText,
  CreditCard,
  CheckCircle2,
  AlertCircle,
  Stethoscope,
  Edit3,
  Trash2,
  Send,
  Loader2,
  Plus,
  MessageSquare,
  MoreVertical,
} from "lucide-react";

interface Booking {
  id: string;
  customerName: string;
  customerPhone: string;
  customerEmail?: string | null;
  service: string;
  appointmentDate: string;
  appointmentTime: string;
  duration?: number;
  staffMember?: string | null;
  depositAmount?: number | null;
  depositPaid?: boolean;
  depositPaidAt?: string | null;
  totalAmount?: number;
  status: string;
  source?: string;
  notes?: string | null;
  createdAt?: string;
  updatedAt?: string;
  sectorMetadata?: Record<string, unknown>;
}

interface BookingNote {
  id: string;
  bookingId: string;
  authorId: string;
  authorName: string;
  content: string;
  createdAt: string;
  updatedAt: string;
}

interface AppointmentDetailsModalProps {
  lang: Lang;
  booking: Booking | null;
  isOpen: boolean;
  onClose: () => void;
  onStatusChange?: (bookingId: string, newStatus: string) => void;
  onSendPaymentLink?: (bookingId: string) => void;
}

export default function AppointmentDetailsModal({
  lang,
  booking,
  isOpen,
  onClose,
  onStatusChange,
  onSendPaymentLink,
}: AppointmentDetailsModalProps) {
  const isAr = lang === "ar";
  const [isUpdating, setIsUpdating] = useState(false);
  const [activeTab, setActiveTab] = useState<"details" | "payment" | "notes">(
    "details",
  );

  // Notes state
  const [notes, setNotes] = useState<BookingNote[]>([]);
  const [isLoadingNotes, setIsLoadingNotes] = useState(false);
  const [newNoteContent, setNewNoteContent] = useState("");
  const [isSubmittingNote, setIsSubmittingNote] = useState(false);
  const [editingNoteId, setEditingNoteId] = useState<string | null>(null);
  const [editingContent, setEditingContent] = useState("");
  const [noteMenuOpen, setNoteMenuOpen] = useState<string | null>(null);

  // Fetch notes when modal opens or booking changes
  const fetchNotes = useCallback(async () => {
    if (!booking?.id) return;

    setIsLoadingNotes(true);
    try {
      const response = await fetch(`/api/bookings/${booking.id}/notes`);
      if (response.ok) {
        const data = await response.json();
        setNotes(data.notes || []);
      }
    } catch (error) {
      console.error("Failed to fetch notes:", error);
    } finally {
      setIsLoadingNotes(false);
    }
  }, [booking?.id]);

  useEffect(() => {
    if (isOpen && booking?.id && activeTab === "notes") {
      fetchNotes();
    }
  }, [isOpen, booking?.id, activeTab, fetchNotes]);

  // Reset state when modal closes
  useEffect(() => {
    if (!isOpen) {
      setNotes([]);
      setNewNoteContent("");
      setEditingNoteId(null);
      setEditingContent("");
      setNoteMenuOpen(null);
    }
  }, [isOpen]);

  // Add a new note
  const handleAddNote = async () => {
    if (!booking?.id || !newNoteContent.trim()) return;

    setIsSubmittingNote(true);
    try {
      const response = await fetch(`/api/bookings/${booking.id}/notes`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content: newNoteContent.trim() }),
      });

      if (response.ok) {
        const data = await response.json();
        setNotes((prev) => [data.note, ...prev]);
        setNewNoteContent("");
      }
    } catch (error) {
      console.error("Failed to add note:", error);
    } finally {
      setIsSubmittingNote(false);
    }
  };

  // Update an existing note
  const handleUpdateNote = async (noteId: string) => {
    if (!booking?.id || !editingContent.trim()) return;

    setIsSubmittingNote(true);
    try {
      const response = await fetch(
        `/api/bookings/${booking.id}/notes/${noteId}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ content: editingContent.trim() }),
        },
      );

      if (response.ok) {
        const data = await response.json();
        setNotes((prev) =>
          prev.map((note) => (note.id === noteId ? data.note : note)),
        );
        setEditingNoteId(null);
        setEditingContent("");
      }
    } catch (error) {
      console.error("Failed to update note:", error);
    } finally {
      setIsSubmittingNote(false);
    }
  };

  // Delete a note
  const handleDeleteNote = async (noteId: string) => {
    if (!booking?.id) return;

    try {
      const response = await fetch(
        `/api/bookings/${booking.id}/notes/${noteId}`,
        {
          method: "DELETE",
        },
      );

      if (response.ok) {
        setNotes((prev) => prev.filter((note) => note.id !== noteId));
      }
    } catch (error) {
      console.error("Failed to delete note:", error);
    }
    setNoteMenuOpen(null);
  };

  // Start editing a note
  const startEditing = (note: BookingNote) => {
    setEditingNoteId(note.id);
    setEditingContent(note.content);
    setNoteMenuOpen(null);
  };

  // Cancel editing
  const cancelEditing = () => {
    setEditingNoteId(null);
    setEditingContent("");
  };

  if (!isOpen || !booking) return null;

  const t = {
    title: isAr ? "تفاصيل الموعد" : "Appointment Details",
    customerInfo: isAr ? "معلومات العميل" : "Customer Information",
    appointmentInfo: isAr ? "معلومات الموعد" : "Appointment Information",
    paymentInfo: isAr ? "معلومات الدفع" : "Payment Information",
    notes: isAr ? "ملاحظات" : "Notes",
    name: isAr ? "الاسم" : "Name",
    phone: isAr ? "الهاتف" : "Phone",
    email: isAr ? "البريد الإلكتروني" : "Email",
    service: isAr ? "الخدمة" : "Service",
    date: isAr ? "التاريخ" : "Date",
    time: isAr ? "الوقت" : "Time",
    duration: isAr ? "المدة" : "Duration",
    staff: isAr ? "الموظف" : "Staff Member",
    status: isAr ? "الحالة" : "Status",
    source: isAr ? "المصدر" : "Source",
    deposit: isAr ? "العربون" : "Deposit",
    total: isAr ? "الإجمالي" : "Total",
    paid: isAr ? "مدفوع" : "Paid",
    pending: isAr ? "معلق" : "Pending",
    paidOn: isAr ? "تاريخ الدفع" : "Paid on",
    noNotes: isAr ? "لا توجد ملاحظات" : "No notes available",
    minutes: isAr ? "دقيقة" : "minutes",
    close: isAr ? "إغلاق" : "Close",
    sendPaymentLink: isAr ? "إرسال رابط الدفع" : "Send Payment Link",
    markConfirmed: isAr ? "تأكيد الموعد" : "Confirm Appointment",
    markCompleted: isAr ? "تحديد كمكتمل" : "Mark Completed",
    markCancelled: isAr ? "إلغاء الموعد" : "Cancel Appointment",
    createdAt: isAr ? "تاريخ الإنشاء" : "Created",
    updatedAt: isAr ? "آخر تحديث" : "Last Updated",
    tabDetails: isAr ? "التفاصيل" : "Details",
    tabPayment: isAr ? "الدفع" : "Payment",
    tabNotes: isAr ? "الملاحظات" : "Notes",
    notProvided: isAr ? "غير متوفر" : "Not provided",
    // Notes translations
    addNote: isAr ? "إضافة ملاحظة" : "Add Note",
    addNoteButton: isAr ? "إضافة" : "Add",
    notePlaceholder: isAr
      ? "اكتب ملاحظة للفريق..."
      : "Write a note for the team...",
    internalNotesTitle: isAr ? "ملاحظات داخلية" : "Internal Notes",
    internalNotesDesc: isAr
      ? "هذه الملاحظات مرئية فقط للمسؤولين والموظفين"
      : "These notes are only visible to admin and staff",
    editNote: isAr ? "تعديل" : "Edit",
    deleteNote: isAr ? "حذف" : "Delete",
    saveNote: isAr ? "حفظ" : "Save",
    cancelEdit: isAr ? "إلغاء" : "Cancel",
    loadingNotes: isAr ? "جاري تحميل الملاحظات..." : "Loading notes...",
    noteBy: isAr ? "بواسطة" : "by",
    edited: isAr ? "(معدّلة)" : "(edited)",
  };

  const statusLabels: Record<string, { label: string; color: string }> = {
    pending: { label: isAr ? "معلق" : "Pending", color: "amber" },
    confirmed: { label: isAr ? "مؤكد" : "Confirmed", color: "emerald" },
    completed: { label: isAr ? "مكتمل" : "Completed", color: "slate" },
    cancelled: { label: isAr ? "ملغي" : "Cancelled", color: "rose" },
    no_show: { label: isAr ? "لم يحضر" : "No-show", color: "orange" },
  };

  const sourceLabels: Record<string, string> = {
    manual: isAr ? "إدخال يدوي" : "Manual Entry",
    whatsapp: isAr ? "واتساب" : "WhatsApp",
    website: isAr ? "الموقع" : "Website",
    google_calendar: isAr ? "تقويم جوجل" : "Google Calendar",
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  const formatDateTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleString(isAr ? "ar-SA" : "en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const handleStatusChange = (newStatus: string) => {
    if (!onStatusChange) return;
    setIsUpdating(true);
    try {
      onStatusChange(booking.id, newStatus);
    } finally {
      setIsUpdating(false);
    }
  };

  const statusInfo = statusLabels[booking.status] || statusLabels.pending;

  // Static color variants mapping for Tailwind JIT compiler
  const statusColorVariants: Record<string, string> = {
    amber: "bg-amber-100 text-amber-700",
    emerald: "bg-emerald-100 text-emerald-700",
    slate: "bg-slate-100 text-slate-700",
    rose: "bg-rose-100 text-rose-700",
    orange: "bg-orange-100 text-orange-700",
    blue: "bg-blue-100 text-blue-700",
    green: "bg-green-100 text-green-700",
    purple: "bg-purple-100 text-purple-700",
    red: "bg-red-100 text-red-700",
    yellow: "bg-yellow-100 text-yellow-700",
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div
        className="relative w-full max-w-2xl max-h-[90vh] overflow-hidden rounded-2xl bg-white shadow-2xl"
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* Header */}
        <div className="bg-gradient-to-r from-brand-green to-emerald-600 px-6 py-5">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-white/20 flex items-center justify-center">
                <Calendar className="w-5 h-5 text-white" />
              </div>
              <div>
                <h2 className="text-lg font-bold text-white">{t.title}</h2>
                <p className="text-emerald-100 text-sm">{booking.service}</p>
              </div>
            </div>
            <button
              type="button"
              aria-label="Close"
              onClick={onClose}
              className="rounded-lg bg-white/10 p-2 text-white hover:bg-white/20 transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Status Badge */}
          <div className="mt-4 flex items-center gap-2">
            <span
              className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ${statusColorVariants[statusInfo.color] || statusColorVariants.blue}`}
            >
              {booking.status === "confirmed" ||
              booking.status === "completed" ? (
                <CheckCircle2 className="w-3.5 h-3.5" />
              ) : booking.status === "cancelled" ||
                booking.status === "no_show" ? (
                <AlertCircle className="w-3.5 h-3.5" />
              ) : (
                <Clock className="w-3.5 h-3.5" />
              )}
              {statusInfo.label}
            </span>
            {booking.depositPaid && (
              <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-100 px-3 py-1 text-xs font-semibold text-emerald-700">
                <CreditCard className="w-3.5 h-3.5" />
                {t.paid} - QAR {booking.depositAmount}
              </span>
            )}
          </div>
        </div>

        {/* Tabs */}
        <div className="border-b border-slate-200 px-6">
          <div className="flex gap-1">
            {(["details", "payment", "notes"] as const).map((tab) => (
              <button
                key={tab}
                onClick={() => setActiveTab(tab)}
                className={`px-4 py-3 text-sm font-medium transition-colors relative ${
                  activeTab === tab
                    ? "text-brand-green"
                    : "text-slate-500 hover:text-slate-700"
                }`}
              >
                {tab === "details" && t.tabDetails}
                {tab === "payment" && t.tabPayment}
                {tab === "notes" && t.tabNotes}
                {activeTab === tab && (
                  <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-brand-green rounded-full" />
                )}
              </button>
            ))}
          </div>
        </div>

        {/* Content */}
        <div className="overflow-y-auto max-h-[calc(90vh-280px)] p-6">
          {activeTab === "details" && (
            <div className="space-y-6">
              {/* Customer Information */}
              <div>
                <h3 className="text-sm font-semibold text-slate-900 mb-3 flex items-center gap-2">
                  <User className="w-4 h-4 text-slate-400" />
                  {t.customerInfo}
                </h3>
                <div className="bg-slate-50 rounded-xl p-4 space-y-3">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-brand-green/10 flex items-center justify-center">
                      <User className="w-5 h-5 text-brand-green" />
                    </div>
                    <div>
                      <p className="font-semibold text-slate-900">
                        {booking.customerName}
                      </p>
                      <p className="text-sm text-slate-500">{t.name}</p>
                    </div>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div className="flex items-center gap-2 text-sm">
                      <Phone className="w-4 h-4 text-slate-400" />
                      <span className="text-slate-600">
                        {booking.customerPhone}
                      </span>
                    </div>
                    <div className="flex items-center gap-2 text-sm">
                      <Mail className="w-4 h-4 text-slate-400" />
                      <span className="text-slate-600">
                        {booking.customerEmail || t.notProvided}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Appointment Information */}
              <div>
                <h3 className="text-sm font-semibold text-slate-900 mb-3 flex items-center gap-2">
                  <Calendar className="w-4 h-4 text-slate-400" />
                  {t.appointmentInfo}
                </h3>
                <div className="bg-slate-50 rounded-xl p-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <p className="text-xs text-slate-500 mb-1">{t.service}</p>
                      <p className="font-medium text-slate-900 flex items-center gap-2">
                        <Stethoscope className="w-4 h-4 text-brand-green" />
                        {booking.service}
                      </p>
                    </div>
                    <div>
                      <p className="text-xs text-slate-500 mb-1">{t.date}</p>
                      <p className="font-medium text-slate-900">
                        {formatDate(booking.appointmentDate)}
                      </p>
                    </div>
                    <div>
                      <p className="text-xs text-slate-500 mb-1">{t.time}</p>
                      <p className="font-medium text-slate-900 flex items-center gap-2">
                        <Clock className="w-4 h-4 text-slate-400" />
                        {booking.appointmentTime}
                      </p>
                    </div>
                    <div>
                      <p className="text-xs text-slate-500 mb-1">
                        {t.duration}
                      </p>
                      <p className="font-medium text-slate-900">
                        {booking.duration || 30} {t.minutes}
                      </p>
                    </div>
                    {booking.staffMember && (
                      <div>
                        <p className="text-xs text-slate-500 mb-1">{t.staff}</p>
                        <p className="font-medium text-slate-900">
                          {booking.staffMember}
                        </p>
                      </div>
                    )}
                    <div>
                      <p className="text-xs text-slate-500 mb-1">{t.source}</p>
                      <p className="font-medium text-slate-900">
                        {sourceLabels[booking.source || "manual"] ||
                          booking.source}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Sector Metadata */}
              {booking.sectorMetadata &&
                Object.keys(booking.sectorMetadata).length > 0 && (
                  <div>
                    <h3 className="text-sm font-semibold text-slate-900 mb-3 flex items-center gap-2">
                      <FileText className="w-4 h-4 text-slate-400" />
                      {isAr ? "تفاصيل القطاع" : "Sector Details"}
                    </h3>
                    <div className="bg-slate-50 rounded-xl p-4">
                      <div className="grid grid-cols-2 gap-3">
                        {Object.entries(booking.sectorMetadata).map(
                          ([key, value]) => {
                            if (
                              value === undefined ||
                              value === null ||
                              value === ""
                            )
                              return null;
                            const label = key
                              .replace(/_/g, " ")
                              .replace(/\b\w/g, (c) => c.toUpperCase());
                            return (
                              <div key={key}>
                                <p className="text-xs text-slate-500 mb-1">
                                  {label}
                                </p>
                                <p className="font-medium text-slate-900 text-sm">
                                  {String(value)}
                                </p>
                              </div>
                            );
                          },
                        )}
                      </div>
                    </div>
                  </div>
                )}

              {/* Timestamps */}
              {(booking.createdAt || booking.updatedAt) && (
                <div className="text-xs text-slate-400 flex flex-wrap gap-4">
                  {booking.createdAt && (
                    <span>
                      {t.createdAt}: {formatDateTime(booking.createdAt)}
                    </span>
                  )}
                  {booking.updatedAt && (
                    <span>
                      {t.updatedAt}: {formatDateTime(booking.updatedAt)}
                    </span>
                  )}
                </div>
              )}
            </div>
          )}

          {activeTab === "payment" && (
            <div className="space-y-6">
              {/* Payment Status */}
              <div
                className={`rounded-xl p-5 ${
                  booking.depositPaid
                    ? "bg-emerald-50 border border-emerald-200"
                    : "bg-amber-50 border border-amber-200"
                }`}
              >
                <div className="flex items-center gap-3 mb-3">
                  {booking.depositPaid ? (
                    <CheckCircle2 className="w-6 h-6 text-emerald-600" />
                  ) : (
                    <AlertCircle className="w-6 h-6 text-amber-600" />
                  )}
                  <span
                    className={`font-semibold text-lg ${
                      booking.depositPaid
                        ? "text-emerald-900"
                        : "text-amber-900"
                    }`}
                  >
                    {booking.depositPaid ? t.paid : t.pending}
                  </span>
                </div>
                {booking.depositPaidAt && (
                  <p className="text-sm text-emerald-700">
                    {t.paidOn}: {formatDateTime(booking.depositPaidAt)}
                  </p>
                )}
              </div>

              {/* Payment Details */}
              <div className="bg-slate-50 rounded-xl p-4">
                <div className="space-y-3">
                  <div className="flex justify-between items-center py-2 border-b border-slate-200">
                    <span className="text-slate-600">{t.deposit}</span>
                    <span className="font-semibold text-slate-900">
                      QAR {booking.depositAmount?.toFixed(2) || "0.00"}
                    </span>
                  </div>
                  <div className="flex justify-between items-center py-2">
                    <span className="text-slate-600">{t.total}</span>
                    <span className="font-semibold text-slate-900">
                      QAR {booking.totalAmount?.toFixed(2) || "0.00"}
                    </span>
                  </div>
                </div>
              </div>

              {/* Send Payment Link */}
              {!booking.depositPaid &&
                booking.depositAmount &&
                onSendPaymentLink && (
                  <button
                    onClick={() => onSendPaymentLink(booking.id)}
                    className="w-full flex items-center justify-center gap-2 rounded-xl bg-violet-600 px-4 py-3 text-sm font-semibold text-white hover:bg-violet-700 transition-colors"
                  >
                    <Send className="w-4 h-4" />
                    {t.sendPaymentLink}
                  </button>
                )}
            </div>
          )}

          {activeTab === "notes" && (
            <div className="space-y-4">
              {/* Header */}
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-sm font-semibold text-slate-900 flex items-center gap-2">
                    <MessageSquare className="w-4 h-4 text-slate-400" />
                    {t.internalNotesTitle}
                  </h3>
                  <p className="text-xs text-slate-500 mt-0.5">
                    {t.internalNotesDesc}
                  </p>
                </div>
                {notes.length > 0 && (
                  <span className="text-xs text-slate-400">
                    {notes.length}{" "}
                    {isAr ? "ملاحظة" : notes.length === 1 ? "note" : "notes"}
                  </span>
                )}
              </div>

              {/* Add Note Form */}
              <div className="bg-slate-50 rounded-xl p-4">
                <textarea
                  value={newNoteContent}
                  onChange={(e) => setNewNoteContent(e.target.value)}
                  placeholder={t.notePlaceholder}
                  rows={3}
                  className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green/50 focus:border-brand-green resize-none bg-white"
                />
                <div className="flex justify-end mt-2">
                  <button
                    onClick={handleAddNote}
                    disabled={isSubmittingNote || !newNoteContent.trim()}
                    className="inline-flex items-center gap-1.5 rounded-lg bg-brand-green px-3 py-1.5 text-xs font-semibold text-white hover:bg-brand-green/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isSubmittingNote ? (
                      <Loader2 className="w-3.5 h-3.5 animate-spin" />
                    ) : (
                      <Plus className="w-3.5 h-3.5" />
                    )}
                    {t.addNoteButton}
                  </button>
                </div>
              </div>

              {/* Legacy Note (if exists) */}
              {booking.notes && (
                <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
                  <div className="flex items-start gap-3">
                    <FileText className="w-5 h-5 text-amber-500 mt-0.5 flex-shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-medium text-amber-700 mb-1">
                        {isAr ? "ملاحظة أصلية" : "Original Note"}
                      </p>
                      <p className="text-sm text-slate-700 whitespace-pre-wrap">
                        {booking.notes}
                      </p>
                    </div>
                  </div>
                </div>
              )}

              {/* Notes List */}
              {isLoadingNotes ? (
                <div className="text-center py-8">
                  <Loader2 className="w-8 h-8 text-brand-green animate-spin mx-auto mb-2" />
                  <p className="text-sm text-slate-500">{t.loadingNotes}</p>
                </div>
              ) : notes.length > 0 ? (
                <div className="space-y-3">
                  {notes.map((note) => {
                    const noteDate = new Date(note.createdAt);
                    const isEdited = note.updatedAt !== note.createdAt;

                    return (
                      <div
                        key={note.id}
                        className="bg-white border border-slate-200 rounded-xl p-4 hover:border-slate-300 transition-colors"
                      >
                        {editingNoteId === note.id ? (
                          // Edit Mode
                          <div>
                            <textarea
                              value={editingContent}
                              onChange={(e) =>
                                setEditingContent(e.target.value)
                              }
                              rows={3}
                              className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green/50 focus:border-brand-green resize-none"
                              autoFocus
                            />
                            <div className="flex justify-end gap-2 mt-2">
                              <button
                                onClick={cancelEditing}
                                className="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-50 transition-colors"
                              >
                                {t.cancelEdit}
                              </button>
                              <button
                                onClick={() => handleUpdateNote(note.id)}
                                disabled={
                                  isSubmittingNote || !editingContent.trim()
                                }
                                className="inline-flex items-center gap-1 rounded-lg bg-brand-green px-3 py-1.5 text-xs font-semibold text-white hover:bg-brand-green/90 transition-colors disabled:opacity-50"
                              >
                                {isSubmittingNote ? (
                                  <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                ) : null}
                                {t.saveNote}
                              </button>
                            </div>
                          </div>
                        ) : (
                          // View Mode
                          <div>
                            <div className="flex items-start justify-between gap-2">
                              <p className="text-sm text-slate-700 whitespace-pre-wrap flex-1">
                                {note.content}
                              </p>
                              <div className="relative flex-shrink-0">
                                <button
                                  onClick={() =>
                                    setNoteMenuOpen(
                                      noteMenuOpen === note.id ? null : note.id,
                                    )
                                  }
                                  className="p-1 rounded-lg hover:bg-slate-100 transition-colors text-slate-400 hover:text-slate-600"
                                >
                                  <MoreVertical className="w-4 h-4" />
                                </button>
                                {noteMenuOpen === note.id && (
                                  <div
                                    className={`absolute ${isAr ? "left-0" : "right-0"} top-full mt-1 w-32 bg-white border border-slate-200 rounded-lg shadow-lg z-10 overflow-hidden`}
                                  >
                                    <button
                                      onClick={() => startEditing(note)}
                                      className="w-full flex items-center gap-2 px-3 py-2 text-xs text-slate-700 hover:bg-slate-50 transition-colors"
                                    >
                                      <Edit3 className="w-3.5 h-3.5" />
                                      {t.editNote}
                                    </button>
                                    <button
                                      onClick={() => handleDeleteNote(note.id)}
                                      className="w-full flex items-center gap-2 px-3 py-2 text-xs text-rose-600 hover:bg-rose-50 transition-colors"
                                    >
                                      <Trash2 className="w-3.5 h-3.5" />
                                      {t.deleteNote}
                                    </button>
                                  </div>
                                )}
                              </div>
                            </div>
                            <div className="flex items-center gap-2 mt-3 text-xs text-slate-400">
                              <span className="font-medium text-slate-500">
                                {note.authorName}
                              </span>
                              <span>•</span>
                              <span>
                                {noteDate.toLocaleDateString(
                                  isAr ? "ar-SA" : "en-US",
                                  {
                                    month: "short",
                                    day: "numeric",
                                    year: "numeric",
                                  },
                                )}{" "}
                                {noteDate.toLocaleTimeString(
                                  isAr ? "ar-SA" : "en-US",
                                  {
                                    hour: "2-digit",
                                    minute: "2-digit",
                                  },
                                )}
                              </span>
                              {isEdited && (
                                <span className="text-slate-400">
                                  {t.edited}
                                </span>
                              )}
                            </div>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              ) : !booking.notes ? (
                <div className="text-center py-8">
                  <MessageSquare className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                  <p className="text-slate-500">{t.noNotes}</p>
                  <p className="text-xs text-slate-400 mt-1">
                    {isAr
                      ? "أضف ملاحظة باستخدام النموذج أعلاه"
                      : "Add a note using the form above"}
                  </p>
                </div>
              ) : null}
            </div>
          )}
        </div>

        {/* Footer Actions */}
        <div className="border-t border-slate-200 px-6 py-4 bg-slate-50">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div className="flex gap-2">
              {booking.status === "pending" && (
                <button
                  onClick={() => handleStatusChange("confirmed")}
                  disabled={isUpdating}
                  className="inline-flex items-center gap-1.5 rounded-lg bg-emerald-100 px-3 py-2 text-xs font-semibold text-emerald-700 hover:bg-emerald-200 transition-colors disabled:opacity-50"
                >
                  {isUpdating ? (
                    <Loader2 className="w-3.5 h-3.5 animate-spin" />
                  ) : (
                    <CheckCircle2 className="w-3.5 h-3.5" />
                  )}
                  {t.markConfirmed}
                </button>
              )}
              {(booking.status === "pending" ||
                booking.status === "confirmed") && (
                <button
                  onClick={() => handleStatusChange("completed")}
                  disabled={isUpdating}
                  className="inline-flex items-center gap-1.5 rounded-lg bg-slate-100 px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-200 transition-colors disabled:opacity-50"
                >
                  {isUpdating ? (
                    <Loader2 className="w-3.5 h-3.5 animate-spin" />
                  ) : (
                    <CheckCircle2 className="w-3.5 h-3.5" />
                  )}
                  {t.markCompleted}
                </button>
              )}
              {booking.status !== "cancelled" &&
                booking.status !== "completed" && (
                  <button
                    onClick={() => handleStatusChange("cancelled")}
                    disabled={isUpdating}
                    className="inline-flex items-center gap-1.5 rounded-lg bg-rose-100 px-3 py-2 text-xs font-semibold text-rose-700 hover:bg-rose-200 transition-colors disabled:opacity-50"
                  >
                    {isUpdating ? (
                      <Loader2 className="w-3.5 h-3.5 animate-spin" />
                    ) : (
                      <AlertCircle className="w-3.5 h-3.5" />
                    )}
                    {t.markCancelled}
                  </button>
                )}
            </div>
            <button
              onClick={onClose}
              className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
            >
              {t.close}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
