"use client";

import { useState, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Search,
  RefreshCw,
  Download,
  Trash2,
  ChevronLeft,
  ChevronRight,
  Loader2,
  Inbox,
  XCircle,
  Filter,
  SlidersHorizontal,
  X,
} from "lucide-react";
import {
  fetchLeads,
  updateLeadStatus,
  deleteLead,
  exportLeadsCSV,
} from "@/lib/api";
import type { Lead, LeadStatus, PaginatedLeadsResponse } from "@/lib/types";
import { cn } from "@/lib/utils";

// ── Constants ─────────────────────────────────────────────────────────────────

const ALL_STATUSES: LeadStatus[] = [
  "New", "Contacted", "Qualified", "Converted", "Rejected",
];
const PAGE_SIZE = 20;
const TOTAL_COLS = 12; // Date|Customer|Mobile|Email|City|PIN|State|Car|Variant|Source|Status|Actions

const STATUS_BADGE: Record<LeadStatus, string> = {
  New:       "bg-blue-100 text-blue-700 border-blue-200",
  Contacted: "bg-yellow-100 text-yellow-700 border-yellow-200",
  Qualified: "bg-purple-100 text-purple-700 border-purple-200",
  Converted: "bg-green-100 text-green-700 border-green-200",
  Rejected:  "bg-red-100 text-red-700 border-red-200",
};

// ── Helpers ───────────────────────────────────────────────────────────────────

function fmtDate(iso: string) {
  try {
    return new Date(iso).toLocaleDateString("en-IN", {
      day: "2-digit", month: "short", year: "numeric",
    });
  } catch { return "—"; }
}

// ── Skeleton ──────────────────────────────────────────────────────────────────

function SkeletonRow() {
  return (
    <tr className="border-b border-gray-100 animate-pulse">
      {Array.from({ length: TOTAL_COLS }).map((_, i) => (
        <td key={i} className="px-4 py-4">
          <div className="h-4 bg-gray-100 rounded-lg" />
        </td>
      ))}
    </tr>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────

export default function AdminLeadsPage() {
  // ── Data state ───────────────────────────────────────────────────────────────
  const [data,          setData]         = useState<PaginatedLeadsResponse | null>(null);
  const [loading,       setLoading]      = useState(true);
  const [error,         setError]        = useState<string | null>(null);
  const [page,          setPage]         = useState(1);

  // ── Search ───────────────────────────────────────────────────────────────────
  const [search,        setSearch]       = useState("");
  const [searchInput,   setSearchInput]  = useState("");

  // ── Filters ──────────────────────────────────────────────────────────────────
  const [statusFilter,  setStatusFilter] = useState("");
  const [cityFilter,    setCityFilter]   = useState("");
  const [carFilter,     setCarFilter]    = useState("");
  const [variantFilter, setVariantFilter]= useState("");
  const [dateFrom,      setDateFrom]     = useState("");
  const [dateTo,        setDateTo]       = useState("");

  // ── UI state ─────────────────────────────────────────────────────────────────
  const [updatingId,       setUpdatingId]       = useState<string | null>(null);
  const [deletingId,       setDeletingId]       = useState<string | null>(null);
  const [confirmDelete,    setConfirmDelete]    = useState<string | null>(null);
  const [exporting,        setExporting]        = useState(false);
  const [showMobileFilters,setShowMobileFilters]= useState(false);

  // Active filter badge count (excludes search which has its own clear)
  const activeFilterCount = [
    statusFilter, cityFilter, carFilter, variantFilter, dateFrom, dateTo,
  ].filter(Boolean).length;

  // ── Data loading ─────────────────────────────────────────────────────────────

  const loadLeads = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetchLeads({
        page,
        limit:    PAGE_SIZE,
        status:   statusFilter  || undefined,
        search:   search        || undefined,
        city:     cityFilter    || undefined,
        car:      carFilter     || undefined,
        variant:  variantFilter || undefined,
        dateFrom: dateFrom      || undefined,
        dateTo:   dateTo        || undefined,
      });
      setData(res);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to load leads");
    } finally {
      setLoading(false);
    }
  }, [page, search, statusFilter, cityFilter, carFilter, variantFilter, dateFrom, dateTo]);

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

  // ── Handlers ─────────────────────────────────────────────────────────────────

  function handleSearch(e: React.FormEvent) {
    e.preventDefault();
    setSearch(searchInput);
    setPage(1);
  }

  function clearFilters() {
    setStatusFilter(""); setCityFilter(""); setCarFilter("");
    setVariantFilter(""); setDateFrom(""); setDateTo("");
    setPage(1);
    setShowMobileFilters(false);
  }

  async function handleStatusChange(lead: Lead, newStatus: LeadStatus) {
    setUpdatingId(lead.id);
    try {
      await updateLeadStatus(lead.id, newStatus);
      setData((prev) =>
        prev
          ? { ...prev, leads: prev.leads.map((l) => l.id === lead.id ? { ...l, status: newStatus } : l) }
          : prev
      );
    } catch {
      await loadLeads();
    } finally {
      setUpdatingId(null);
    }
  }

  async function handleDelete(id: string) {
    setDeletingId(id);
    setConfirmDelete(null);
    try {
      await deleteLead(id);
      setData((prev) =>
        prev
          ? { ...prev, leads: prev.leads.filter((l) => l.id !== id), total: prev.total - 1 }
          : prev
      );
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Delete failed");
    } finally {
      setDeletingId(null);
    }
  }

  async function handleExport() {
    setExporting(true);
    try {
      await exportLeadsCSV();
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Export failed");
    } finally {
      setExporting(false);
    }
  }

  const leads      = data?.leads ?? [];
  const total      = data?.total ?? 0;
  const totalPages = data?.totalPages ?? 1;
  const from       = total === 0 ? 0 : (page - 1) * PAGE_SIZE + 1;
  const to         = Math.min(page * PAGE_SIZE, total);

  // ── Shared input style helpers ────────────────────────────────────────────────
  const inputCls  = "rounded-xl border border-gray-200 bg-gray-50 px-3 py-2.5 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:bg-white transition-colors";
  const selectCls = cn(inputCls, "appearance-none cursor-pointer font-medium");

  // ── Search form (shared across breakpoints) ───────────────────────────────────
  function SearchForm({ className }: { className?: string }) {
    return (
      <form onSubmit={handleSearch} className={cn("flex gap-2", className)}>
        <div className="relative flex-1 min-w-0">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search name, mobile, car, city, PIN…"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            className="w-full rounded-2xl border border-gray-200 bg-gray-50 px-4 py-2.5 pl-10 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:bg-white transition-colors"
          />
        </div>
        <button type="submit" className="px-4 py-2.5 rounded-2xl border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:border-blue-300 transition-all shrink-0">
          Search
        </button>
        {(search || searchInput) && (
          <button
            type="button"
            onClick={() => { setSearchInput(""); setSearch(""); setPage(1); }}
            className="px-3 py-2.5 rounded-2xl border border-gray-200 bg-white text-gray-500 hover:text-gray-700 transition-all"
          >
            <XCircle className="w-4 h-4" />
          </button>
        )}
      </form>
    );
  }

  return (
    <div className="max-w-[1280px] mx-auto px-4 sm:px-6 py-8 space-y-6 min-w-0">

      {/* ── Page header ───────────────────────────────────────────────────── */}
      <div className="flex flex-col xs:flex-row xs:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-black text-gray-900">Lead Management</h1>
          <p className="text-sm text-gray-500 mt-1">
            {total > 0
              ? `${total.toLocaleString()} lead${total !== 1 ? "s" : ""}${activeFilterCount > 0 ? " (filtered)" : ""}`
              : "Manage incoming leads"}
          </p>
        </div>
        <button
          onClick={handleExport}
          disabled={exporting}
          className="flex items-center justify-center gap-2 w-full xs:w-auto px-4 py-2.5 rounded-2xl bg-gradient-to-r from-blue-600 to-cyan-500 text-white text-sm font-bold shadow-lg shadow-blue-100 hover:shadow-xl transition-all disabled:opacity-70 shrink-0"
        >
          {exporting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
          Export CSV
        </button>
      </div>

      {/* ── Error banner ──────────────────────────────────────────────────── */}
      {error && (
        <div className="rounded-2xl bg-red-50 border border-red-200 p-4 flex items-start sm:items-center gap-3 text-sm text-red-700">
          <XCircle className="w-5 h-5 shrink-0 mt-0.5 sm:mt-0" />
          <p className="flex-1 min-w-0 break-words">{error}</p>
          <button onClick={() => setError(null)} className="shrink-0 text-red-500 hover:text-red-700">
            <XCircle className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* ── Filter panel ──────────────────────────────────────────────────── */}
      <div className="rounded-[24px] bg-white border border-gray-200/60 p-5 shadow-[0_4px_20px_rgba(0,0,0,0.05)]">

        {/* ─── MOBILE (< sm): search + slide-up filter sheet ─── */}
        <div className="flex gap-2 sm:hidden">
          <SearchForm className="flex-1" />
          <button
            onClick={() => setShowMobileFilters(true)}
            className={cn(
              "relative flex items-center justify-center w-11 h-[42px] rounded-2xl border text-sm font-semibold transition-all shrink-0",
              activeFilterCount > 0
                ? "border-blue-300 bg-blue-50 text-blue-700"
                : "border-gray-200 bg-white text-gray-600 hover:border-gray-300"
            )}
            aria-label="Open filters"
          >
            <SlidersHorizontal className="w-4 h-4" />
            {activeFilterCount > 0 && (
              <span className="absolute -top-1.5 -right-1.5 min-w-[18px] h-[18px] px-1 bg-blue-600 text-white text-[9px] font-black rounded-full flex items-center justify-center">
                {activeFilterCount}
              </span>
            )}
          </button>
        </div>

        {/* ─── TABLET (sm – lg): 2 rows ─── */}
        <div className="hidden sm:flex lg:hidden flex-col gap-3">
          {/* Row 1: search + status + refresh */}
          <div className="flex gap-3 items-center">
            <SearchForm className="flex-1" />
            <select
              value={statusFilter}
              onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
              className={cn(selectCls, "w-[160px] shrink-0")}
            >
              <option value="">All Statuses</option>
              {ALL_STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
            </select>
            <button
              onClick={loadLeads}
              disabled={loading}
              className="flex items-center gap-2 px-4 py-2.5 rounded-2xl border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:border-blue-200 transition-all shrink-0"
            >
              <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} />
              Refresh
            </button>
          </div>
          {/* Row 2: city + car + variant + dates + clear */}
          <div className="flex gap-3 flex-wrap items-center">
            <input type="text" placeholder="City…" value={cityFilter}
              onChange={(e) => { setCityFilter(e.target.value); setPage(1); }}
              className={cn(inputCls, "w-[130px]")} />
            <input type="text" placeholder="Car…" value={carFilter}
              onChange={(e) => { setCarFilter(e.target.value); setPage(1); }}
              className={cn(inputCls, "w-[140px]")} />
            <input type="text" placeholder="Variant…" value={variantFilter}
              onChange={(e) => { setVariantFilter(e.target.value); setPage(1); }}
              className={cn(inputCls, "w-[130px]")} />
            <input type="date" value={dateFrom}
              onChange={(e) => { setDateFrom(e.target.value); setPage(1); }}
              className={cn(inputCls, "w-[148px]")} title="From date" />
            <input type="date" value={dateTo}
              onChange={(e) => { setDateTo(e.target.value); setPage(1); }}
              className={cn(inputCls, "w-[148px]")} title="To date" />
            {activeFilterCount > 0 && (
              <button
                onClick={clearFilters}
                className="flex items-center gap-1.5 px-3 py-2.5 rounded-2xl border border-red-200 bg-red-50 text-sm font-semibold text-red-600 hover:bg-red-100 transition-all"
              >
                <X className="w-3.5 h-3.5" /> Clear ({activeFilterCount})
              </button>
            )}
          </div>
        </div>

        {/* ─── DESKTOP (lg+): all filters inline ─── */}
        <div className="hidden lg:flex gap-3 items-center flex-wrap">
          <SearchForm className="flex-1 min-w-[260px]" />
          <select
            value={statusFilter}
            onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
            className={cn(selectCls, "w-[150px] shrink-0")}
          >
            <option value="">All Statuses</option>
            {ALL_STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
          <input type="text" placeholder="City…" value={cityFilter}
            onChange={(e) => { setCityFilter(e.target.value); setPage(1); }}
            className={cn(inputCls, "w-[120px] shrink-0")} />
          <input type="text" placeholder="Car…" value={carFilter}
            onChange={(e) => { setCarFilter(e.target.value); setPage(1); }}
            className={cn(inputCls, "w-[130px] shrink-0")} />
          <input type="text" placeholder="Variant…" value={variantFilter}
            onChange={(e) => { setVariantFilter(e.target.value); setPage(1); }}
            className={cn(inputCls, "w-[120px] shrink-0")} />
          <input type="date" value={dateFrom}
            onChange={(e) => { setDateFrom(e.target.value); setPage(1); }}
            className={cn(inputCls, "w-[148px] shrink-0")} title="From date" />
          <input type="date" value={dateTo}
            onChange={(e) => { setDateTo(e.target.value); setPage(1); }}
            className={cn(inputCls, "w-[148px] shrink-0")} title="To date" />
          {activeFilterCount > 0 && (
            <button
              onClick={clearFilters}
              className="flex items-center gap-1.5 px-3 py-2.5 rounded-2xl border border-red-200 bg-red-50 text-sm font-semibold text-red-600 hover:bg-red-100 transition-all shrink-0"
            >
              <X className="w-3.5 h-3.5" /> Clear ({activeFilterCount})
            </button>
          )}
          <button
            onClick={loadLeads}
            disabled={loading}
            title="Refresh"
            className="flex items-center gap-2 p-2.5 rounded-2xl border border-gray-200 bg-white text-gray-700 hover:border-blue-200 transition-all shrink-0"
          >
            <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} />
          </button>
        </div>
      </div>

      {/* ── Lead table ────────────────────────────────────────────────────── */}
      <div className="rounded-[24px] bg-white border border-gray-200/60 shadow-[0_4px_20px_rgba(0,0,0,0.05)] overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[1200px]">
            <thead className="bg-gradient-to-r from-gray-50 to-blue-50 border-b border-gray-100">
              <tr>
                {[
                  "Date", "Customer", "Mobile", "Email",
                  "City", "PIN", "State",
                  "Car", "Variant", "Source",
                  "Status", "Actions",
                ].map((h) => (
                  <th
                    key={h}
                    className="px-4 py-4 text-left text-xs uppercase tracking-wider text-gray-500 font-black whitespace-nowrap"
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>

            <tbody>
              {loading ? (
                Array.from({ length: 8 }).map((_, i) => <SkeletonRow key={i} />)
              ) : leads.length === 0 ? (
                <tr>
                  <td colSpan={TOTAL_COLS}>
                    <div className="flex flex-col items-center justify-center py-20 text-center">
                      <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mb-4">
                        <Inbox className="w-8 h-8 text-gray-400" />
                      </div>
                      <p className="text-lg font-black text-gray-700">No leads found</p>
                      <p className="text-sm text-gray-400 mt-1">
                        {search || activeFilterCount > 0
                          ? "No leads match your filters."
                          : "Leads will appear here once customers enquire."}
                      </p>
                      {activeFilterCount > 0 && (
                        <button
                          onClick={clearFilters}
                          className="mt-3 text-sm font-semibold text-blue-600 hover:underline"
                        >
                          Clear filters
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ) : (
                leads.map((lead) => (
                  <motion.tr
                    key={lead.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    className="border-b border-gray-100 hover:bg-blue-50/30 transition-colors"
                  >
                    {/* Date */}
                    <td className="px-4 py-4 text-xs text-gray-500 whitespace-nowrap">
                      {fmtDate(lead.createdAt)}
                    </td>
                    {/* Customer */}
                    <td className="px-4 py-4">
                      <p className="text-sm font-bold text-gray-800 whitespace-nowrap">{lead.name}</p>
                    </td>
                    {/* Mobile */}
                    <td className="px-4 py-4 text-sm text-gray-700 font-mono whitespace-nowrap">
                      {lead.mobile}
                    </td>
                    {/* Email */}
                    <td className="px-4 py-4 text-sm text-gray-500 max-w-[140px] truncate">
                      {lead.email || "—"}
                    </td>
                    {/* City */}
                    <td className="px-4 py-4 text-sm text-gray-700 whitespace-nowrap">
                      {lead.city}
                    </td>
                    {/* PIN Code */}
                    <td className="px-4 py-4 text-sm font-mono text-gray-600 whitespace-nowrap">
                      {lead.pinCode || "—"}
                    </td>
                    {/* State */}
                    <td className="px-4 py-4 text-sm text-gray-600 whitespace-nowrap">
                      {lead.state || "—"}
                    </td>
                    {/* Car */}
                    <td className="px-4 py-4 text-sm font-semibold text-gray-800 whitespace-nowrap max-w-[150px] truncate">
                      {lead.carName}
                    </td>
                    {/* Variant */}
                    <td className="px-4 py-4 text-xs text-gray-500 whitespace-nowrap">
                      {lead.variant || "—"}
                    </td>
                    {/* Source */}
                    <td className="px-4 py-4">
                      <span className="inline-flex items-center px-2 py-0.5 rounded-lg bg-gray-100 text-gray-600 text-[10px] font-semibold uppercase tracking-wide whitespace-nowrap">
                        {(lead.source || "web").replace(/_/g, " ")}
                      </span>
                    </td>
                    {/* Status badge */}
                    <td className="px-4 py-4">
                      <span className={cn(
                        "inline-flex items-center px-3 py-1 rounded-2xl text-xs font-bold border",
                        STATUS_BADGE[lead.status]
                      )}>
                        {lead.status}
                      </span>
                    </td>
                    {/* Actions */}
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-2">
                        {updatingId === lead.id ? (
                          <Loader2 className="w-4 h-4 animate-spin text-blue-500" />
                        ) : (
                          <select
                            value={lead.status}
                            onChange={(e) => handleStatusChange(lead, e.target.value as LeadStatus)}
                            className="text-xs rounded-xl border border-gray-200 bg-gray-50 px-2 py-1.5 font-semibold text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-400 appearance-none pr-6 cursor-pointer"
                          >
                            {ALL_STATUSES.map((s) => (
                              <option key={s} value={s}>{s}</option>
                            ))}
                          </select>
                        )}
                        {confirmDelete === lead.id ? (
                          <div className="flex items-center gap-1">
                            <button
                              onClick={() => handleDelete(lead.id)}
                              disabled={deletingId === lead.id}
                              className="px-2 py-1 rounded-xl bg-red-500 text-white text-xs font-bold hover:bg-red-600 transition-colors"
                            >
                              {deletingId === lead.id
                                ? <Loader2 className="w-3 h-3 animate-spin" />
                                : "Yes"}
                            </button>
                            <button
                              onClick={() => setConfirmDelete(null)}
                              className="px-2 py-1 rounded-xl bg-gray-100 text-gray-700 text-xs font-bold hover:bg-gray-200 transition-colors"
                            >
                              No
                            </button>
                          </div>
                        ) : (
                          <button
                            onClick={() => setConfirmDelete(lead.id)}
                            className="p-1.5 rounded-xl text-gray-400 hover:text-red-500 hover:bg-red-50 transition-all"
                            aria-label="Delete lead"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </motion.tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {total > 0 && (
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 px-4 sm:px-6 py-4 border-t border-gray-100 bg-gray-50/50">
            <p className="text-sm text-gray-500 text-center sm:text-left min-w-0">
              {from}–{to} of <span className="font-bold text-gray-800">{total.toLocaleString()}</span> leads
            </p>
            <div className="flex items-center justify-center sm:justify-end gap-2 shrink-0">
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page <= 1 || loading}
                className="p-2 rounded-2xl border border-gray-200 bg-white text-gray-600 hover:border-blue-300 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              <span className="text-sm font-bold text-gray-700 px-2">
                {page} / {totalPages}
              </span>
              <button
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page >= totalPages || loading}
                className="p-2 rounded-2xl border border-gray-200 bg-white text-gray-600 hover:border-blue-300 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* ── Mobile bottom-sheet filters ───────────────────────────────────── */}
      <AnimatePresence>
        {showMobileFilters && (
          <>
            {/* Backdrop */}
            <motion.div
              key="mobile-filter-backdrop"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 z-[60] bg-black/50 sm:hidden"
              onClick={() => setShowMobileFilters(false)}
            />

            {/* Sheet */}
            <motion.div
              key="mobile-filter-sheet"
              initial={{ y: "100%" }}
              animate={{ y: 0 }}
              exit={{ y: "100%" }}
              transition={{ type: "spring", damping: 30, stiffness: 300 }}
              className="fixed bottom-0 left-0 right-0 z-[61] bg-white rounded-t-[24px] shadow-2xl sm:hidden max-h-[85vh] overflow-y-auto"
            >
              <div className="p-5">
                {/* Drag handle */}
                <div className="w-10 h-1 bg-gray-300 rounded-full mx-auto mb-4" />

                {/* Sheet header */}
                <div className="flex items-center justify-between mb-5">
                  <div className="flex items-center gap-2">
                    <Filter className="w-4 h-4 text-blue-600" />
                    <h3 className="text-lg font-black text-gray-900">Filters</h3>
                    {activeFilterCount > 0 && (
                      <span className="inline-flex items-center px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 text-xs font-bold">
                        {activeFilterCount} active
                      </span>
                    )}
                  </div>
                  <button
                    onClick={() => setShowMobileFilters(false)}
                    className="p-2 rounded-xl text-gray-500 hover:bg-gray-100 transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>

                {/* Filter controls */}
                <div className="space-y-4">
                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-wider text-gray-500 mb-1.5">Status</p>
                    <select
                      value={statusFilter}
                      onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
                      className={cn(selectCls, "w-full")}
                    >
                      <option value="">All Statuses</option>
                      {ALL_STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
                    </select>
                  </div>

                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-wider text-gray-500 mb-1.5">City</p>
                    <input type="text" placeholder="Filter by city…" value={cityFilter}
                      onChange={(e) => { setCityFilter(e.target.value); setPage(1); }}
                      className={cn(inputCls, "w-full")} />
                  </div>

                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-wider text-gray-500 mb-1.5">Car</p>
                    <input type="text" placeholder="Filter by car…" value={carFilter}
                      onChange={(e) => { setCarFilter(e.target.value); setPage(1); }}
                      className={cn(inputCls, "w-full")} />
                  </div>

                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-wider text-gray-500 mb-1.5">Variant</p>
                    <input type="text" placeholder="Filter by variant…" value={variantFilter}
                      onChange={(e) => { setVariantFilter(e.target.value); setPage(1); }}
                      className={cn(inputCls, "w-full")} />
                  </div>

                  <div>
                    <p className="text-[11px] font-bold uppercase tracking-wider text-gray-500 mb-1.5">Date Range</p>
                    <div className="grid grid-cols-1 min-[360px]:grid-cols-2 gap-3">
                      <div>
                        <p className="text-[10px] text-gray-400 mb-1">From</p>
                        <input type="date" value={dateFrom}
                          onChange={(e) => { setDateFrom(e.target.value); setPage(1); }}
                          className={cn(inputCls, "w-full")} />
                      </div>
                      <div>
                        <p className="text-[10px] text-gray-400 mb-1">To</p>
                        <input type="date" value={dateTo}
                          onChange={(e) => { setDateTo(e.target.value); setPage(1); }}
                          className={cn(inputCls, "w-full")} />
                      </div>
                    </div>
                  </div>
                </div>

                {/* Sheet action buttons */}
                <div className="flex gap-3 mt-6 pb-[calc(1.25rem+env(safe-area-inset-bottom,0px))]">
                  {activeFilterCount > 0 && (
                    <button
                      onClick={clearFilters}
                      className="flex-1 py-3 rounded-2xl border border-red-200 bg-red-50 text-sm font-bold text-red-600 hover:bg-red-100 transition-colors"
                    >
                      Clear All
                    </button>
                  )}
                  <button
                    onClick={() => setShowMobileFilters(false)}
                    className="flex-[2] py-3 rounded-2xl bg-blue-600 text-white text-sm font-bold hover:bg-blue-700 transition-colors"
                  >
                    Apply Filters
                  </button>
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}
