"use client";

import React, { useState, useEffect, useMemo } from "react";
import Link from "next/link";
import { useAuth } from "@/context/AuthContext";
import {
  fetchCustomerInquiries,
  CustomerInquiryItem,
  CustomerInquiriesData
} from "@/services/inquiryService";
import {
  Calendar,
  MessageSquare,
  Home,
  Mail,
  Clock,
  MapPin,
  Phone,
  User,
  CheckCircle2,
  AlertCircle,
  Clock3,
  Search,
  Filter,
  Eye,
  ArrowRight,
  ShieldCheck,
  Building2,
  Sparkles,
  RefreshCw,
  ExternalLink,
  ChevronRight,
  Send,
  X,
  FileText,
  BadgePercent
} from "lucide-react";

export default function CustomerInquiriesPage() {
  const { user, isLoggedIn, openAuthModal } = useAuth();

  const [inquiriesData, setInquiriesData] = useState<CustomerInquiriesData>({
    summary: { total: 0, tours: 0, agent_inquiries: 0, sell_listings: 0, general_inquiries: 0 },
    all: [],
    tours: [],
    agent_inquiries: [],
    sell_listings: [],
    general_inquiries: [],
  });

  const [activeTab, setActiveTab] = useState<"all" | "tours" | "agent_inquiries" | "sell_listings" | "general_inquiries">("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [isLoading, setIsLoading] = useState(true);
  const [selectedInquiry, setSelectedInquiry] = useState<CustomerInquiryItem | null>(null);

  // Guest lookup email
  const [guestEmail, setGuestEmail] = useState("");
  const [lookupEmailInput, setLookupEmailInput] = useState("");
  const [hasSearchedGuest, setHasSearchedGuest] = useState(false);

  const loadData = async (targetEmail?: string) => {
    setIsLoading(true);
    try {
      const emailToUse = targetEmail !== undefined ? targetEmail : (user?.email || guestEmail);
      const token = typeof window !== "undefined" ? (localStorage.getItem("dh_customer_token") || localStorage.getItem("dreamhomes_token")) : null;
      const res = await fetchCustomerInquiries(token, emailToUse);
      if (res.success && res.data) {
        setInquiriesData(res.data);
      }
    } catch (e) {
      console.error("Failed to load inquiries:", e);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (isLoggedIn) {
      loadData();
    } else if (guestEmail) {
      loadData(guestEmail);
    } else {
      setIsLoading(false);
    }
  }, [isLoggedIn, user]);

  const handleGuestSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (!lookupEmailInput.trim()) return;
    setGuestEmail(lookupEmailInput.trim());
    setHasSearchedGuest(true);
    loadData(lookupEmailInput.trim());
  };

  // Get current active tab list
  const currentList = useMemo(() => {
    let list: CustomerInquiryItem[] = [];
    if (activeTab === "all") list = inquiriesData.all;
    else if (activeTab === "tours") list = inquiriesData.tours;
    else if (activeTab === "agent_inquiries") list = inquiriesData.agent_inquiries;
    else if (activeTab === "sell_listings") list = inquiriesData.sell_listings;
    else if (activeTab === "general_inquiries") list = inquiriesData.general_inquiries;

    return list.filter((item) => {
      // Search filter
      const q = searchQuery.toLowerCase();
      const matchSearch =
        !q ||
        item.order_number?.toLowerCase().includes(q) ||
        item.property?.title?.toLowerCase().includes(q) ||
        item.category_label?.toLowerCase().includes(q) ||
        item.message?.toLowerCase().includes(q) ||
        item.subject?.toLowerCase().includes(q) ||
        item.agent?.name?.toLowerCase().includes(q);

      // Status filter
      const matchStatus = statusFilter === "all" || item.status.toLowerCase() === statusFilter.toLowerCase();

      return matchSearch && matchStatus;
    });
  }, [inquiriesData, activeTab, searchQuery, statusFilter]);

  const formatPrice = (val?: number | string | null) => {
    if (!val || Number(val) === 0) return "Price on Request";
    return `LKR ${Number(val).toLocaleString()}`;
  };

  const getStatusBadge = (status: string) => {
    const st = status.toLowerCase();
    if (st === "confirmed" || st === "completed" || st === "resolved" || st === "won") {
      return (
        <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-bold bg-emerald-500/15 text-emerald-400 border border-emerald-500/30">
          <CheckCircle2 className="w-3 h-3" />
          <span>{status}</span>
        </span>
      );
    }
    if (st === "rescheduled" || st === "in progress" || st === "processing" || st === "contacted") {
      return (
        <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-bold bg-amber-500/15 text-amber-300 border border-amber-500/30">
          <Clock3 className="w-3 h-3" />
          <span>{status}</span>
        </span>
      );
    }
    if (st === "cancelled" || st === "lost" || st === "rejected") {
      return (
        <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-bold bg-rose-500/15 text-rose-400 border border-rose-500/30">
          <AlertCircle className="w-3 h-3" />
          <span>{status}</span>
        </span>
      );
    }
    return (
      <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-bold bg-indigo-500/15 text-indigo-300 border border-indigo-500/30 animate-pulse">
        <Clock className="w-3 h-3" />
        <span>{status || "Pending Action"}</span>
      </span>
    );
  };

  const getTabIcon = (tab: string) => {
    switch (tab) {
      case "tours":
        return <Calendar className="w-4 h-4" />;
      case "agent_inquiries":
        return <MessageSquare className="w-4 h-4" />;
      case "sell_listings":
        return <Home className="w-4 h-4" />;
      case "general_inquiries":
        return <Mail className="w-4 h-4" />;
      default:
        return <Building2 className="w-4 h-4" />;
    }
  };

  return (
    <div className="min-h-screen bg-[#070708] text-slate-100 pt-24 pb-20 px-4 sm:px-6 lg:px-8">
      <div className="max-w-7xl mx-auto space-y-8">
        
        {/* Page Hero Header */}
        <div className="relative rounded-3xl p-6 sm:p-10 overflow-hidden bg-gradient-to-r from-zinc-950 via-[#10131A] to-zinc-950 border border-white/10 shadow-2xl">
          <div className="absolute top-0 right-0 w-96 h-96 bg-[#FFE259]/5 rounded-full blur-3xl pointer-events-none" />
          <div className="relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-6">
            <div className="space-y-2">
              <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#FFE259]/10 border border-[#FFE259]/20 text-[#FFE259] text-xs font-bold uppercase tracking-wider">
                <ShieldCheck className="w-3.5 h-3.5" />
                <span>Customer Portal</span>
              </div>
              <h1 className="text-2xl sm:text-3xl lg:text-4xl font-extrabold text-white tracking-tight">
                My Inquiries &amp; Property Applications
              </h1>
              <p className="text-slate-400 text-xs sm:text-sm max-w-2xl">
                Track the status of your booked property viewings, agent consultations, and seller listings across Colombo and prime growth corridors.
              </p>
            </div>

            <div className="flex flex-wrap items-center gap-3">
              <button
                type="button"
                onClick={() => loadData()}
                disabled={isLoading}
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-200 hover:text-white border border-white/10 text-xs font-bold transition-all cursor-pointer"
              >
                <RefreshCw className={`w-3.5 h-3.5 ${isLoading ? "animate-spin text-[#FFE259]" : ""}`} />
                <span>Refresh Status</span>
              </button>

              <Link
                href="/sell"
                className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-[#D48B00] via-[#FFA726] to-[#FFE259] text-black font-extrabold text-xs shadow-lg shadow-[#FFA726]/20 hover:scale-102 transition-all"
              >
                <Home className="w-3.5 h-3.5" />
                <span>List New Property</span>
              </Link>
            </div>
          </div>
        </div>

        {/* Guest Verification Box (If Not Logged In) */}
        {!isLoggedIn && (
          <div className="p-6 bg-zinc-900/80 rounded-3xl border border-[#FFE259]/20 shadow-xl space-y-4">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div>
                <h3 className="text-sm font-bold text-white flex items-center gap-2">
                  <User className="w-4 h-4 text-[#FFE259]" />
                  <span>Looking for your submitted inquiries as a Guest?</span>
                </h3>
                <p className="text-xs text-slate-400 mt-0.5">
                  Enter the email address you used when booking a tour or listing a property to view all your history.
                </p>
              </div>
              <button
                type="button"
                onClick={() => openAuthModal()}
                className="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-[#059669] hover:bg-[#047857] text-white text-xs font-extrabold transition-all cursor-pointer shrink-0"
              >
                <span>Sign In to Account</span>
                <ArrowRight className="w-3.5 h-3.5" />
              </button>
            </div>

            <form onSubmit={handleGuestSearch} className="flex flex-col sm:flex-row gap-3 pt-2">
              <div className="relative flex-1">
                <Mail className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                <input
                  type="email"
                  required
                  placeholder="Enter your email (e.g. john@example.com)..."
                  value={lookupEmailInput}
                  onChange={(e) => setLookupEmailInput(e.target.value)}
                  className="w-full pl-10 pr-4 py-2.5 rounded-xl bg-black/40 border border-white/10 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-[#FFE259]"
                />
              </div>
              <button
                type="submit"
                className="px-6 py-2.5 rounded-xl bg-[#FFE259] hover:bg-[#FFA726] text-black font-extrabold text-xs transition-all cursor-pointer shrink-0"
              >
                Lookup Inquiries
              </button>
            </form>
          </div>
        )}

        {/* 4 Summary Metric Cards */}
        <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          
          {/* Card 1: All Inquiries */}
          <div
            onClick={() => setActiveTab("all")}
            className={`p-5 rounded-3xl border transition-all cursor-pointer ${
              activeTab === "all"
                ? "bg-white/10 border-[#FFE259] shadow-lg shadow-[#FFE259]/10"
                : "bg-zinc-900/60 hover:bg-zinc-900 border-white/5"
            }`}
          >
            <div className="flex items-center justify-between">
              <span className="text-[11px] font-bold uppercase tracking-wider text-slate-400">Total Requests</span>
              <div className="w-8 h-8 rounded-xl bg-white/10 flex items-center justify-center text-white">
                <Building2 className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-3">
              <span className="text-2xl sm:text-3xl font-black text-white">{inquiriesData.summary.total}</span>
              <p className="text-[11px] text-slate-400 mt-1">All applications &amp; requests</p>
            </div>
          </div>

          {/* Card 2: Tours */}
          <div
            onClick={() => setActiveTab("tours")}
            className={`p-5 rounded-3xl border transition-all cursor-pointer ${
              activeTab === "tours"
                ? "bg-indigo-950/40 border-indigo-400 shadow-lg shadow-indigo-500/10"
                : "bg-zinc-900/60 hover:bg-zinc-900 border-white/5"
            }`}
          >
            <div className="flex items-center justify-between">
              <span className="text-[11px] font-bold uppercase tracking-wider text-indigo-400">Property Tours</span>
              <div className="w-8 h-8 rounded-xl bg-indigo-500/20 flex items-center justify-center text-indigo-300">
                <Calendar className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-3">
              <span className="text-2xl sm:text-3xl font-black text-white">{inquiriesData.summary.tours}</span>
              <p className="text-[11px] text-indigo-300/80 mt-1">In-person &amp; 360 Video viewings</p>
            </div>
          </div>

          {/* Card 3: Agent Consultations */}
          <div
            onClick={() => setActiveTab("agent_inquiries")}
            className={`p-5 rounded-3xl border transition-all cursor-pointer ${
              activeTab === "agent_inquiries"
                ? "bg-sky-950/40 border-sky-400 shadow-lg shadow-sky-500/10"
                : "bg-zinc-900/60 hover:bg-zinc-900 border-white/5"
            }`}
          >
            <div className="flex items-center justify-between">
              <span className="text-[11px] font-bold uppercase tracking-wider text-sky-400">Agent Messages</span>
              <div className="w-8 h-8 rounded-xl bg-sky-500/20 flex items-center justify-center text-sky-300">
                <MessageSquare className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-3">
              <span className="text-2xl sm:text-3xl font-black text-white">{inquiriesData.summary.agent_inquiries}</span>
              <p className="text-[11px] text-sky-300/80 mt-1">Direct agent inquiries</p>
            </div>
          </div>

          {/* Card 4: Sell & Rent Submissions */}
          <div
            onClick={() => setActiveTab("sell_listings")}
            className={`p-5 rounded-3xl border transition-all cursor-pointer ${
              activeTab === "sell_listings"
                ? "bg-emerald-950/40 border-emerald-400 shadow-lg shadow-emerald-500/10"
                : "bg-zinc-900/60 hover:bg-zinc-900 border-white/5"
            }`}
          >
            <div className="flex items-center justify-between">
              <span className="text-[11px] font-bold uppercase tracking-wider text-emerald-400">Seller Listings</span>
              <div className="w-8 h-8 rounded-xl bg-emerald-500/20 flex items-center justify-center text-emerald-300">
                <Home className="w-4 h-4" />
              </div>
            </div>
            <div className="mt-3">
              <span className="text-2xl sm:text-3xl font-black text-white">{inquiriesData.summary.sell_listings}</span>
              <p className="text-[11px] text-emerald-300/80 mt-1">Submitted for sale or rent</p>
            </div>
          </div>

        </div>

        {/* Filter Navigation Tabs + Search Controls */}
        <div className="p-4 bg-zinc-900/90 rounded-3xl border border-white/10 space-y-4">
          <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
            
            {/* Category Filter Tabs */}
            <div className="flex items-center gap-1.5 overflow-x-auto pb-1 lg:pb-0 scrollbar-none">
              {[
                { id: "all", label: "All Inquiries", count: inquiriesData.summary.total },
                { id: "tours", label: "Property Tours", count: inquiriesData.summary.tours },
                { id: "agent_inquiries", label: "Agent Inquiries", count: inquiriesData.summary.agent_inquiries },
                { id: "sell_listings", label: "Seller Listings", count: inquiriesData.summary.sell_listings },
                { id: "general_inquiries", label: "Help & Messages", count: inquiriesData.summary.general_inquiries },
              ].map((tab) => (
                <button
                  key={tab.id}
                  type="button"
                  onClick={() => setActiveTab(tab.id as any)}
                  className={`inline-flex items-center gap-2 px-4 py-2 rounded-2xl text-xs font-extrabold whitespace-nowrap transition-all cursor-pointer ${
                    activeTab === tab.id
                      ? "bg-gradient-to-r from-[#D48B00] via-[#FFA726] to-[#FFE259] text-black shadow-md shadow-[#FFA726]/20"
                      : "bg-white/5 hover:bg-white/10 text-slate-300 hover:text-white border border-white/5"
                  }`}
                >
                  {getTabIcon(tab.id)}
                  <span>{tab.label}</span>
                  <span className={`px-1.5 py-0.5 rounded-full text-[10px] font-bold ${
                    activeTab === tab.id ? "bg-black/20 text-black" : "bg-white/10 text-slate-300"
                  }`}>
                    {tab.count}
                  </span>
                </button>
              ))}
            </div>

            {/* Search & Status Filter */}
            <div className="flex flex-wrap items-center gap-3">
              <div className="relative min-w-[220px] flex-1 sm:flex-initial">
                <Search className="w-3.5 h-3.5 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  placeholder="Search title, ref#, agent..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-9 pr-3 py-2 rounded-xl bg-black/40 border border-white/10 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-[#FFE259]"
                />
              </div>

              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="px-3 py-2 rounded-xl bg-black/40 border border-white/10 text-xs text-slate-200 focus:outline-none focus:border-[#FFE259] cursor-pointer"
              >
                <option value="all">All Statuses</option>
                <option value="pending">Pending</option>
                <option value="confirmed">Confirmed</option>
                <option value="completed">Completed</option>
                <option value="rescheduled">Rescheduled</option>
                <option value="cancelled">Cancelled</option>
              </select>
            </div>

          </div>
        </div>

        {/* Inquiries Records List */}
        {isLoading ? (
          <div className="p-16 text-center space-y-3 bg-zinc-900/30 rounded-3xl border border-white/5">
            <RefreshCw className="w-8 h-8 text-[#FFE259] animate-spin mx-auto" />
            <p className="text-slate-400 text-xs font-semibold">Loading your inquiry history...</p>
          </div>
        ) : currentList.length === 0 ? (
          <div className="p-16 text-center space-y-4 bg-zinc-900/30 rounded-3xl border border-white/5">
            <div className="w-14 h-14 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center text-slate-400 mx-auto">
              <Building2 className="w-7 h-7" />
            </div>
            <div className="space-y-1">
              <h3 className="text-base font-bold text-white">No Inquiries Found</h3>
              <p className="text-xs text-slate-400 max-w-md mx-auto">
                {searchQuery || statusFilter !== "all"
                  ? "No inquiry applications matched your filter criteria."
                  : "You haven't submitted any property viewings or listing inquiries yet."}
              </p>
            </div>
            <div className="pt-2 flex justify-center gap-3">
              <Link
                href="/properties"
                className="px-5 py-2.5 rounded-xl bg-white/10 hover:bg-white/15 text-white font-bold text-xs transition-colors"
              >
                Explore Properties
              </Link>
              <Link
                href="/sell"
                className="px-5 py-2.5 rounded-xl bg-[#FFE259] text-black font-extrabold text-xs hover:bg-[#FFA726] transition-colors"
              >
                List a Property
              </Link>
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            {currentList.map((item) => (
              <div
                key={item.id}
                className="p-5 sm:p-6 bg-zinc-900/70 hover:bg-zinc-900 rounded-3xl border border-white/10 hover:border-white/20 transition-all space-y-4 group"
              >
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-4 border-b border-white/5">
                  
                  {/* Left: Reference Number & Type */}
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-2xl bg-[#FFE259]/10 border border-[#FFE259]/20 flex items-center justify-center text-[#FFE259] shrink-0">
                      {getTabIcon(item.inquiry_type)}
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-xs font-extrabold text-[#FFE259]">{item.order_number}</span>
                        <span className="text-[11px] text-slate-400 font-semibold">• {item.category_label}</span>
                      </div>
                      <span className="text-[11px] text-slate-500">{item.formatted_date}</span>
                    </div>
                  </div>

                  {/* Right: Status Badge & View Button */}
                  <div className="flex items-center gap-3">
                    {getStatusBadge(item.status)}
                    <button
                      type="button"
                      onClick={() => setSelectedInquiry(item)}
                      className="inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl bg-white/5 hover:bg-[#FFE259] text-slate-300 hover:text-black text-xs font-bold transition-all border border-white/10 cursor-pointer"
                    >
                      <Eye className="w-3.5 h-3.5" />
                      <span>View Brief</span>
                    </button>
                  </div>

                </div>

                {/* Card Content Grid */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs">
                  
                  {/* Property / Topic Title */}
                  <div className="md:col-span-2 space-y-2">
                    {item.property ? (
                      <div className="flex items-start gap-3">
                        {item.property.image && (
                          <img
                            src={item.property.image}
                            alt={item.property.title}
                            className="w-16 h-16 rounded-xl object-cover border border-white/10 shrink-0"
                          />
                        )}
                        <div className="space-y-1">
                          <Link
                            href={`/properties/${item.property.slug || item.property.id}`}
                            className="text-sm font-bold text-white hover:text-[#FFE259] transition-colors line-clamp-1"
                          >
                            {item.property.title}
                          </Link>
                          {item.property.location && (
                            <div className="flex items-center gap-1 text-slate-400 text-[11px]">
                              <MapPin className="w-3 h-3 text-[#FFE259]" />
                              <span>{item.property.location}</span>
                            </div>
                          )}
                          <span className="font-extrabold text-[#FFE259] text-xs">
                            {formatPrice(item.property.price)}
                          </span>
                        </div>
                      </div>
                    ) : (
                      <div>
                        <h4 className="font-bold text-white text-sm">
                          {item.subject || "General Consultation Brief"}
                        </h4>
                        {item.message && (
                          <p className="text-slate-400 text-xs mt-1 line-clamp-2 leading-relaxed">
                            {item.message}
                          </p>
                        )}
                      </div>
                    )}

                    {/* Tour Date & Format Tag (If Tour) */}
                    {item.tour_date && (
                      <div className="inline-flex items-center gap-2 px-3 py-1 rounded-xl bg-indigo-500/10 border border-indigo-500/20 text-indigo-300 font-bold text-[11px]">
                        <Clock className="w-3.5 h-3.5" />
                        <span>
                          Viewing Date: {item.tour_date} @ {item.tour_time_slot || "Anytime"} (
                          {item.tour_format === "video" ? "360 Video Tour" : "In-Person Tour"})
                        </span>
                      </div>
                    )}
                  </div>

                  {/* Assigned Agent Profile */}
                  <div className="p-3 bg-black/40 rounded-2xl border border-white/5 flex items-center justify-between gap-3">
                    {item.agent ? (
                      <>
                        <div className="flex items-center gap-2.5 min-w-0">
                          <img
                            src={item.agent.avatar || "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=100&q=80"}
                            alt={item.agent.name}
                            className="w-9 h-9 rounded-full object-cover border border-white/20 shrink-0"
                          />
                          <div className="min-w-0">
                            <span className="text-[10px] uppercase font-bold text-slate-400 block">Appointed Agent</span>
                            <strong className="text-xs text-white truncate block font-bold">{item.agent.name}</strong>
                          </div>
                        </div>
                        {item.agent.phone && (
                          <a
                            href={`https://wa.me/${item.agent.phone.replace(/[^0-9]/g, "")}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="p-2 rounded-xl bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500 hover:text-white transition-colors shrink-0"
                            title="WhatsApp Agent"
                          >
                            <Phone className="w-3.5 h-3.5" />
                          </a>
                        )}
                      </>
                    ) : (
                      <div className="text-slate-400 text-[11px] italic">
                        Routed to Agency Headquarters team
                      </div>
                    )}
                  </div>

                </div>

              </div>
            ))}
          </div>
        )}

      </div>

      {/* Inquiry Detail Modal */}
      {selectedInquiry && (
        <div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-md flex items-center justify-center p-4">
          <div className="bg-[#0e0e11] border border-white/20 rounded-3xl max-w-xl w-full max-h-[90vh] overflow-y-auto p-6 sm:p-8 space-y-6 shadow-2xl animate-in zoom-in-95 duration-150">
            
            {/* Modal Header */}
            <div className="flex items-center justify-between pb-4 border-b border-white/10">
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <span className="font-mono text-sm font-black text-[#FFE259]">{selectedInquiry.order_number}</span>
                  {getStatusBadge(selectedInquiry.status)}
                </div>
                <span className="text-xs text-slate-400">{selectedInquiry.category_label} • {selectedInquiry.formatted_date}</span>
              </div>
              <button
                type="button"
                onClick={() => setSelectedInquiry(null)}
                className="p-2 rounded-xl bg-white/10 hover:bg-white/20 text-slate-300 hover:text-white transition-colors cursor-pointer"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Property Specification Details (If Attached) */}
            {selectedInquiry.property && (
              <div className="p-4 rounded-2xl bg-zinc-900 border border-white/10 space-y-2">
                <span className="text-[10px] font-bold uppercase tracking-wider text-[#FFE259]">Target Property</span>
                <h4 className="text-sm font-bold text-white">{selectedInquiry.property.title}</h4>
                <div className="flex items-center justify-between text-xs text-slate-300 pt-1">
                  <span>{selectedInquiry.property.location}</span>
                  <strong className="text-[#FFE259] font-bold">{formatPrice(selectedInquiry.property.price)}</strong>
                </div>
              </div>
            )}

            {/* Tour Appointment Details */}
            {selectedInquiry.tour_date && (
              <div className="p-4 rounded-2xl bg-indigo-950/40 border border-indigo-400/30 space-y-1.5 text-xs text-slate-200">
                <span className="text-[10px] font-extrabold uppercase tracking-wider text-indigo-300">Appointment Slot</span>
                <p className="font-bold text-white text-sm">
                  {selectedInquiry.tour_date} @ {selectedInquiry.tour_time_slot || "Agreed Time"}
                </p>
                <span className="text-indigo-300 block text-[11px]">
                  Format: {selectedInquiry.tour_format === "video" ? "Live 360 Virtual Video Tour" : "In-Person Guided Property Viewing"}
                </span>
              </div>
            )}

            {/* Message & Specifications */}
            <div className="space-y-2">
              <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400">Submission Notes &amp; Message</span>
              <div className="p-4 rounded-2xl bg-black/50 border border-white/10 text-xs text-slate-300 leading-relaxed max-h-48 overflow-y-auto whitespace-pre-wrap font-sans">
                {selectedInquiry.message || selectedInquiry.notes || "No additional message provided."}
              </div>
            </div>

            {/* Assigned Agent Contact Card */}
            {selectedInquiry.agent && (
              <div className="p-4 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-between gap-3">
                <div className="flex items-center gap-3">
                  <img
                    src={selectedInquiry.agent.avatar || "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=100&q=80"}
                    alt={selectedInquiry.agent.name}
                    className="w-11 h-11 rounded-full object-cover border border-white/20"
                  />
                  <div>
                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400">Appointed Agent</span>
                    <h5 className="font-bold text-white text-xs">{selectedInquiry.agent.name}</h5>
                    <span className="text-[11px] text-slate-400">{selectedInquiry.agent.email}</span>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  {selectedInquiry.agent.phone && (
                    <a
                      href={`tel:${selectedInquiry.agent.phone}`}
                      className="p-2.5 rounded-xl bg-white/10 hover:bg-white/20 text-white transition-colors"
                      title="Call Agent"
                    >
                      <Phone className="w-4 h-4" />
                    </a>
                  )}
                  {selectedInquiry.agent.phone && (
                    <a
                      href={`https://wa.me/${selectedInquiry.agent.phone.replace(/[^0-9]/g, "")}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="px-3.5 py-2 rounded-xl bg-[#059669] hover:bg-[#047857] text-white text-xs font-bold transition-colors inline-flex items-center gap-1.5"
                    >
                      <MessageSquare className="w-3.5 h-3.5" />
                      <span>WhatsApp</span>
                    </a>
                  )}
                </div>
              </div>
            )}

            {/* Modal Actions Footer */}
            <div className="pt-2 flex justify-end">
              <button
                type="button"
                onClick={() => setSelectedInquiry(null)}
                className="px-6 py-2.5 rounded-xl bg-white/10 hover:bg-white/20 text-white font-bold text-xs transition-colors cursor-pointer"
              >
                Close Brief
              </button>
            </div>

          </div>
        </div>
      )}

    </div>
  );
}
