import { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams, Link } from "react-router-dom";
import axios from "axios";
import { toast } from "sonner";
import {
  Wrench, LogOut, Package, FileText, Truck, Receipt, CheckCircle2,
  Clock, AlertCircle, Loader2, ArrowRight, Search, DollarSign,
  ThumbsUp, ThumbsDown, MapPin, Car, Plus, Trash2, Edit3, CreditCard,
  Home, LayoutGrid, X
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

const STATUS_MAP = {
  new: { label: "Submitted", color: "bg-blue-900/40 text-blue-300 border-blue-800/50", icon: Clock },
  quoted: { label: "Quoted", color: "bg-amber-900/40 text-amber-300 border-amber-800/50", icon: DollarSign },
  in_progress: { label: "In Progress", color: "bg-cyan-900/40 text-cyan-300 border-cyan-800/50", icon: Package },
  completed: { label: "Completed", color: "bg-emerald-900/40 text-emerald-300 border-emerald-800/50", icon: CheckCircle2 },
  cancelled: { label: "Cancelled", color: "bg-red-900/40 text-red-300 border-red-800/50", icon: AlertCircle },
};

const QUOTE_STATUS = {
  pending: "bg-amber-900/40 text-amber-300 border-amber-800/50",
  approved: "bg-emerald-900/40 text-emerald-300 border-emerald-800/50",
  rejected: "bg-red-900/40 text-red-300 border-red-800/50",
};

const ORDER_STATUS = {
  processing: { label: "Processing", progress: 25 },
  shipped: { label: "Shipped", progress: 65 },
  delivered: { label: "Delivered", progress: 100 },
};

/* ============================================================
   SIDEBAR NAV
   ============================================================ */
const NAV_ITEMS = [
  { key: "overview", label: "Overview", icon: LayoutGrid },
  { key: "vehicles", label: "My Garage", icon: Car },
  { key: "requests", label: "Requests", icon: FileText },
  { key: "quotes", label: "Quotes", icon: DollarSign },
  { key: "orders", label: "Orders", icon: Package },
  { key: "invoices", label: "Invoices", icon: Receipt },
  { key: "shipments", label: "Shipments", icon: Truck },
];

/* ============================================================
   MAIN DASHBOARD
   ============================================================ */
export default function UserDashboard() {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState("overview");
  const [loading, setLoading] = useState(true);
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // Data
  const [overview, setOverview] = useState(null);
  const [requests, setRequests] = useState([]);
  const [quotes, setQuotes] = useState([]);
  const [orders, setOrders] = useState([]);
  const [invoices, setInvoices] = useState([]);
  const [shipments, setShipments] = useState([]);
  const [vehicles, setVehicles] = useState([]);

  // Dialogs
  const [newRequestOpen, setNewRequestOpen] = useState(false);
  const [vehicleDialogOpen, setVehicleDialogOpen] = useState(false);
  const [editingVehicle, setEditingVehicle] = useState(null);
  const [payingInvoice, setPayingInvoice] = useState(null);

  // Form state
  const [vinLoading, setVinLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [payLoading, setPayLoading] = useState(false);
  const [form, setForm] = useState({ vehicle_year: "", make: "", model: "", engine: "", part_needed: "", vin: "", budget: "", name: "", email: "", phone: "", notes: "" });
  const [vehicleForm, setVehicleForm] = useState({ year: "", make: "", model: "", vin: "", engine: "", trim: "", nickname: "" });
  const [vehVinLoading, setVehVinLoading] = useState(false);

  const token = localStorage.getItem("user_token");
  const userName = localStorage.getItem("user_name") || "User";
  const headers = useMemo(() => ({ Authorization: `Bearer ${token}` }), [token]);

  // Handle payment return from Stripe
  useEffect(() => {
    const paymentStatus = searchParams.get("payment");
    const sessionId = searchParams.get("session_id");
    if (paymentStatus === "success" && sessionId) {
      pollPaymentStatus(sessionId);
      setSearchParams({});
    } else if (paymentStatus === "cancelled") {
      toast.error("Payment was cancelled.");
      setSearchParams({});
    }
    // eslint-disable-next-line
  }, []);

  const pollPaymentStatus = async (sessionId, attempts = 0) => {
    if (attempts >= 6) { toast.error("Payment status check timed out. Check your invoices for updates."); return; }
    try {
      const { data } = await axios.get(`${API}/payments/status/${sessionId}`, { headers });
      if (data.payment_status === "paid") {
        toast.success("Payment successful! Invoice marked as paid.");
        loadData();
        setActiveTab("invoices");
        return;
      }
      setTimeout(() => pollPaymentStatus(sessionId, attempts + 1), 2500);
    } catch {
      if (attempts < 3) setTimeout(() => pollPaymentStatus(sessionId, attempts + 1), 2500);
    }
  };

  const loadData = useCallback(async () => {
    try {
      const [ovRes, reqRes, quoteRes, orderRes, invRes, shipRes, vehRes] = await Promise.all([
        axios.get(`${API}/user/overview`, { headers }),
        axios.get(`${API}/user/part-requests`, { headers }),
        axios.get(`${API}/user/quotes`, { headers }),
        axios.get(`${API}/user/orders`, { headers }),
        axios.get(`${API}/user/invoices`, { headers }),
        axios.get(`${API}/user/shipments`, { headers }),
        axios.get(`${API}/user/vehicles`, { headers }),
      ]);
      setOverview(ovRes.data);
      setRequests(reqRes.data);
      setQuotes(quoteRes.data);
      setOrders(orderRes.data);
      setInvoices(invRes.data);
      setShipments(shipRes.data);
      setVehicles(vehRes.data);
    } catch {
      toast.error("Session expired. Please login again.");
      localStorage.removeItem("user_token");
      navigate("/account");
    }
    setLoading(false);
  }, [headers, navigate]);

  useEffect(() => {
    if (!token) { navigate("/account"); return; }
    loadData();
  }, [token, navigate, loadData]);

  // --- Handlers ---
  const handleVinDecode = async (targetForm, setTargetForm, setLoadingFn) => {
    const vin = targetForm.vin;
    if (!vin || vin.length !== 17) { toast.error("Enter a valid 17-character VIN"); return; }
    setLoadingFn(true);
    try {
      const { data } = await axios.get(`${API}/vin-decode/${vin}`);
      setTargetForm(p => ({
        ...p,
        ...(targetForm === form ? {
          vehicle_year: data.year || p.vehicle_year, make: data.make || p.make, model: data.model || p.model, engine: data.engine || p.engine
        } : {
          year: data.year || p.year, make: data.make || p.make, model: data.model || p.model, engine: data.engine || p.engine
        })
      }));
      toast.success("VIN decoded!");
    } catch { toast.error("VIN decode failed."); }
    setLoadingFn(false);
  };

  const handleSubmitRequest = async (e) => {
    e.preventDefault();
    if (!form.part_needed || !form.name || !form.email) { toast.error("Fill in Part Needed, Name, and Email."); return; }
    setSubmitLoading(true);
    try {
      await axios.post(`${API}/user/part-requests`, form, { headers });
      toast.success("Part request submitted!");
      setNewRequestOpen(false);
      setForm({ vehicle_year: "", make: "", model: "", engine: "", part_needed: "", vin: "", budget: "", name: userName, email: localStorage.getItem("user_email") || "", phone: "", notes: "" });
      loadData();
    } catch { toast.error("Failed to submit request."); }
    setSubmitLoading(false);
  };

  const handleQuoteAction = async (quoteId, action) => {
    try {
      await axios.post(`${API}/user/quotes/${quoteId}/action`, { action }, { headers });
      toast.success(action === "approve" ? "Quote approved! Order created." : "Quote rejected.");
      loadData();
    } catch (err) { toast.error(err.response?.data?.detail || "Action failed."); }
  };

  const handleSaveVehicle = async (e) => {
    e.preventDefault();
    if (!vehicleForm.year || !vehicleForm.make || !vehicleForm.model) { toast.error("Year, Make, and Model are required."); return; }
    setSubmitLoading(true);
    try {
      if (editingVehicle) {
        await axios.patch(`${API}/user/vehicles/${editingVehicle.id}`, vehicleForm, { headers });
        toast.success("Vehicle updated!");
      } else {
        await axios.post(`${API}/user/vehicles`, vehicleForm, { headers });
        toast.success("Vehicle added to garage!");
      }
      setVehicleDialogOpen(false);
      setEditingVehicle(null);
      setVehicleForm({ year: "", make: "", model: "", vin: "", engine: "", trim: "", nickname: "" });
      loadData();
    } catch { toast.error("Failed to save vehicle."); }
    setSubmitLoading(false);
  };

  const handleDeleteVehicle = async (id) => {
    try {
      await axios.delete(`${API}/user/vehicles/${id}`, { headers });
      toast.success("Vehicle removed.");
      loadData();
    } catch { toast.error("Failed to remove vehicle."); }
  };

  const handlePayInvoice = async (invoice) => {
    setPayLoading(true);
    try {
      const origin = window.location.origin;
      const { data } = await axios.post(`${API}/payments/checkout`, {
        invoice_id: invoice.id,
        origin_url: origin,
      }, { headers });
      if (data.url) {
        window.location.href = data.url;
      }
    } catch (err) {
      toast.error(err.response?.data?.detail || "Failed to initiate payment.");
    }
    setPayLoading(false);
  };

  const logout = () => {
    localStorage.removeItem("user_token");
    localStorage.removeItem("user_name");
    localStorage.removeItem("user_email");
    localStorage.removeItem("user_id");
    navigate("/");
  };

  const update = (f) => (e) => setForm({ ...form, [f]: e.target.value });
  const updateVeh = (f) => (e) => setVehicleForm({ ...vehicleForm, [f]: e.target.value });
  const inputCls = "bg-[#1E1E1E] border-#2A2A2A focus:border-[#3B82F6] focus:ring-1 focus:ring-[#3B82F6]/50 rounded-none h-11 text-white placeholder:text-[#444] text-sm";

  if (loading) return <div className="min-h-screen bg-[#0B0B0B] flex items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-[#3B82F6]" /></div>;

  return (
    <div data-testid="user-dashboard" className="min-h-screen bg-[#0B0B0B] flex">
      {/* SIDEBAR */}
      <aside className={`fixed inset-y-0 left-0 z-40 w-64 bg-[#0B0B0B] border-r border-#2A2A2A transform transition-transform duration-200 lg:relative lg:translate-x-0 ${sidebarOpen ? "translate-x-0" : "-translate-x-full"}`}>
        <div className="p-5 border-b border-#2A2A2A">
          <Link to="/" className="flex items-center gap-2.5">
            <Wrench className="h-5 w-5 text-[#3B82F6]" />
            <span className="font-semibold text-lg uppercase tracking-[0.08em] font-['Inter'] text-white">
              QC <span className="text-[#3B82F6]">Auto</span>
            </span>
          </Link>
        </div>
        <nav className="p-3 space-y-0.5">
          {NAV_ITEMS.map((item) => (
            <button
              key={item.key}
              data-testid={`nav-${item.key}`}
              onClick={() => { setActiveTab(item.key); setSidebarOpen(false); }}
              className={`w-full flex items-center gap-3 px-4 py-2.5 text-[12px] uppercase tracking-[0.1em] font-medium transition-colors ${
                activeTab === item.key
                  ? "bg-[#3B82F6]/10 text-[#3B82F6] border-l-2 border-[#3B82F6]"
                  : "text-[#777] hover:text-white hover:bg-white/[0.03] border-l-2 border-transparent"
              }`}
            >
              <item.icon className="h-4 w-4" />
              {item.label}
              {item.key === "invoices" && overview?.unpaid_invoices_count > 0 && (
                <span className="ml-auto bg-[#3B82F6] text-white text-[9px] font-bold px-1.5 py-0.5 rounded-sm">{overview.unpaid_invoices_count}</span>
              )}
              {item.key === "quotes" && overview?.pending_quotes > 0 && (
                <span className="ml-auto bg-amber-600 text-white text-[9px] font-bold px-1.5 py-0.5 rounded-sm">{overview.pending_quotes}</span>
              )}
            </button>
          ))}
        </nav>
        <div className="absolute bottom-0 left-0 right-0 p-4 border-t border-#2A2A2A">
          <div className="text-[11px] text-[#555] mb-2">Signed in as <span className="text-[#aaa]">{userName}</span></div>
          <Button data-testid="user-logout-btn" onClick={logout} variant="ghost" className="w-full justify-start text-[#666] hover:text-white rounded-none text-[11px] uppercase tracking-[0.1em] h-8 px-2">
            <LogOut className="h-3.5 w-3.5 mr-2" /> Sign Out
          </Button>
        </div>
      </aside>

      {/* MOBILE HEADER */}
      <div className="lg:hidden fixed top-0 left-0 right-0 z-30 bg-[#0B0B0B] border-b border-#2A2A2A px-4 py-3 flex items-center justify-between">
        <button onClick={() => setSidebarOpen(!sidebarOpen)} className="text-white p-1">
          {sidebarOpen ? <X className="h-5 w-5" /> : <LayoutGrid className="h-5 w-5" />}
        </button>
        <span className="font-semibold text-sm uppercase tracking-[0.1em] font-['Inter'] text-white">Dashboard</span>
        <Button onClick={logout} variant="ghost" className="text-[#666] h-8 w-8 p-0"><LogOut className="h-4 w-4" /></Button>
      </div>

      {/* Overlay for mobile sidebar */}
      {sidebarOpen && <div className="lg:hidden fixed inset-0 z-30 bg-black/50" onClick={() => setSidebarOpen(false)} />}

      {/* MAIN CONTENT */}
      <main className="flex-1 min-h-screen lg:ml-0 pt-14 lg:pt-0">
        <div className="p-6 lg:p-8 max-w-6xl">
          {/* TOP BAR */}
          <div className="flex items-center justify-between mb-8">
            <div>
              <h1 data-testid="dashboard-title" className="text-2xl lg:text-3xl font-bold uppercase tracking-tight font-['Inter'] text-white">
                {NAV_ITEMS.find(n => n.key === activeTab)?.label || "Dashboard"}
              </h1>
              <p className="text-[12px] text-[#555] mt-1 uppercase tracking-[0.1em]">Welcome back, {userName}</p>
            </div>
            <div className="flex gap-2">
              {activeTab === "vehicles" && (
                <Button data-testid="add-vehicle-btn" onClick={() => { setEditingVehicle(null); setVehicleForm({ year: "", make: "", model: "", vin: "", engine: "", trim: "", nickname: "" }); setVehicleDialogOpen(true); }} className="bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.1em] hover:bg-[#2563EB] rounded-none text-[11px] h-9 px-5">
                  <Plus className="h-3.5 w-3.5 mr-1.5" /> Add Vehicle
                </Button>
              )}
              {(activeTab === "overview" || activeTab === "requests") && (
                <Button data-testid="new-request-btn" onClick={() => { setForm({ ...form, name: userName, email: localStorage.getItem("user_email") || "" }); setNewRequestOpen(true); }} className="bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.1em] hover:bg-[#2563EB] rounded-none text-[11px] h-9 px-5">
                  <Plus className="h-3.5 w-3.5 mr-1.5" /> New Request
                </Button>
              )}
            </div>
          </div>

          {/* ============ OVERVIEW ============ */}
          {activeTab === "overview" && overview && (
            <div className="space-y-6">
              {/* Stat Cards */}
              <div data-testid="overview-stats" className="grid grid-cols-2 lg:grid-cols-4 gap-3">
                {[
                  { label: "Active Orders", value: overview.active_orders, icon: Package, accent: "text-cyan-400" },
                  { label: "Pending Quotes", value: overview.pending_quotes, icon: DollarSign, accent: "text-amber-400" },
                  { label: "Unpaid Invoices", value: overview.unpaid_invoices_count, icon: Receipt, accent: "text-[#3B82F6]" },
                  { label: "Saved Vehicles", value: overview.vehicles_count, icon: Car, accent: "text-emerald-400" },
                ].map(s => (
                  <div key={s.label} className="bg-[#121212] border border-#2A2A2A p-5">
                    <s.icon className={`h-4 w-4 ${s.accent} mb-3`} />
                    <p className="text-3xl font-semibold font-['Inter'] text-white leading-none">{s.value}</p>
                    <p className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mt-1">{s.label}</p>
                  </div>
                ))}
              </div>

              {/* Outstanding balance */}
              {overview.unpaid_total > 0 && (
                <div data-testid="outstanding-balance" className="bg-gradient-to-r from-[#3B82F6]/10 to-transparent border border-[#3B82F6]/20 p-6 flex items-center justify-between">
                  <div>
                    <p className="text-[11px] uppercase tracking-[0.12em] text-[#3B82F6] font-semibold mb-1">Outstanding Balance</p>
                    <p className="text-4xl font-bold font-['Inter'] text-white">${overview.unpaid_total.toLocaleString(undefined, { minimumFractionDigits: 2 })}</p>
                  </div>
                  <Button data-testid="go-to-invoices" onClick={() => setActiveTab("invoices")} className="bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.1em] hover:bg-[#2563EB] rounded-none text-[11px] h-9 px-5">
                    Pay Now <ArrowRight className="ml-1.5 h-3.5 w-3.5" />
                  </Button>
                </div>
              )}

              {/* Recent activity */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Recent Requests */}
                <div className="bg-[#121212] border border-#2A2A2A">
                  <div className="px-5 py-4 border-b border-#2A2A2A flex items-center justify-between">
                    <h3 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888]">Recent Requests</h3>
                    <button onClick={() => setActiveTab("requests")} className="text-[10px] text-[#3B82F6] uppercase tracking-[0.1em] hover:underline">View All</button>
                  </div>
                  <div className="divide-y divide-#2A2A2A">
                    {overview.recent_requests.slice(0, 4).map(r => {
                      const s = STATUS_MAP[r.status] || STATUS_MAP.new;
                      return (
                        <div key={r.id} className="px-5 py-3 flex items-center justify-between">
                          <div>
                            <p className="text-sm text-white">{r.part_needed}</p>
                            <p className="text-[11px] text-[#555]">{r.vehicle_year} {r.make} {r.model}</p>
                          </div>
                          <Badge className={`rounded-none text-[9px] uppercase border ${s.color}`}>{s.label}</Badge>
                        </div>
                      );
                    })}
                    {overview.recent_requests.length === 0 && <p className="px-5 py-8 text-center text-[#555] text-sm">No requests yet</p>}
                  </div>
                </div>

                {/* Recent Shipments */}
                <div className="bg-[#121212] border border-#2A2A2A">
                  <div className="px-5 py-4 border-b border-#2A2A2A flex items-center justify-between">
                    <h3 className="text-[12px] font-semibold uppercase tracking-[0.12em] text-[#888]">Active Shipments</h3>
                    <button onClick={() => setActiveTab("shipments")} className="text-[10px] text-[#3B82F6] uppercase tracking-[0.1em] hover:underline">View All</button>
                  </div>
                  <div className="divide-y divide-#2A2A2A">
                    {overview.recent_shipments.map(sh => (
                      <div key={sh.id} className="px-5 py-3">
                        <div className="flex items-center justify-between mb-1">
                          <p className="text-sm text-white">{sh.part_needed}</p>
                          <Badge className={`rounded-none text-[9px] uppercase border ${sh.status === "delivered" ? "bg-emerald-900/40 text-emerald-300 border-emerald-800/50" : "bg-cyan-900/40 text-cyan-300 border-cyan-800/50"}`}>
                            {sh.status === "in_transit" ? "In Transit" : "Delivered"}
                          </Badge>
                        </div>
                        <p className="text-[11px] text-[#555]"><Truck className="h-3 w-3 inline mr-1" />{sh.carrier} — {sh.tracking_number}</p>
                      </div>
                    ))}
                    {overview.recent_shipments.length === 0 && <p className="px-5 py-8 text-center text-[#555] text-sm">No active shipments</p>}
                  </div>
                </div>
              </div>

              {/* Quick Actions */}
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
                {[
                  { label: "New Request", icon: Plus, action: () => { setForm({ ...form, name: userName, email: localStorage.getItem("user_email") || "" }); setNewRequestOpen(true); } },
                  { label: "My Garage", icon: Car, action: () => setActiveTab("vehicles") },
                  { label: "View Quotes", icon: DollarSign, action: () => setActiveTab("quotes") },
                  { label: "Find a Part", icon: Search, action: () => navigate("/find-part") },
                ].map(a => (
                  <button key={a.label} onClick={a.action} className="bg-[#121212] border border-#2A2A2A p-4 text-left hover:border-[#3B82F6]/30 transition-colors group">
                    <a.icon className="h-4 w-4 text-[#666] group-hover:text-[#3B82F6] mb-2 transition-colors" />
                    <p className="text-[11px] uppercase tracking-[0.1em] text-[#888] group-hover:text-white transition-colors font-medium">{a.label}</p>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* ============ MY VEHICLES (GARAGE) ============ */}
          {activeTab === "vehicles" && (
            <div data-testid="vehicles-section">
              {vehicles.length === 0 ? (
                <div className="bg-[#121212] border border-#2A2A2A p-16 text-center">
                  <Car className="h-10 w-10 text-[#333] mx-auto mb-4" />
                  <p className="text-[#666] mb-4">No vehicles in your garage yet.</p>
                  <Button onClick={() => { setEditingVehicle(null); setVehicleForm({ year: "", make: "", model: "", vin: "", engine: "", trim: "", nickname: "" }); setVehicleDialogOpen(true); }} className="bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.1em] hover:bg-[#2563EB] rounded-none text-[11px] h-9 px-5">
                    <Plus className="h-3.5 w-3.5 mr-1.5" /> Add Your First Vehicle
                  </Button>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {vehicles.map(v => (
                    <div key={v.id} data-testid={`vehicle-${v.id}`} className="bg-[#121212] border border-#2A2A2A p-5 hover:border-[#3B82F6]/20 transition-colors">
                      <div className="flex items-start justify-between mb-3">
                        <div>
                          {v.nickname && <p className="text-[10px] text-[#3B82F6] uppercase tracking-[0.12em] font-semibold mb-1">{v.nickname}</p>}
                          <h3 className="text-lg font-bold font-['Inter'] text-white uppercase leading-tight">
                            {v.year} {v.make} {v.model}
                          </h3>
                        </div>
                        <div className="flex gap-1">
                          <button data-testid={`edit-vehicle-${v.id}`} onClick={() => { setEditingVehicle(v); setVehicleForm({ year: v.year, make: v.make, model: v.model, vin: v.vin || "", engine: v.engine || "", trim: v.trim || "", nickname: v.nickname || "" }); setVehicleDialogOpen(true); }} className="text-[#555] hover:text-white p-1.5 transition-colors">
                            <Edit3 className="h-3.5 w-3.5" />
                          </button>
                          <button data-testid={`delete-vehicle-${v.id}`} onClick={() => handleDeleteVehicle(v.id)} className="text-[#555] hover:text-[#3B82F6] p-1.5 transition-colors">
                            <Trash2 className="h-3.5 w-3.5" />
                          </button>
                        </div>
                      </div>
                      <div className="grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm">
                        {v.vin && <div><span className="text-[10px] uppercase tracking-[0.12em] text-[#555]">VIN</span><p className="text-[#aaa] font-mono text-xs">{v.vin}</p></div>}
                        {v.engine && <div><span className="text-[10px] uppercase tracking-[0.12em] text-[#555]">Engine</span><p className="text-[#aaa] text-xs">{v.engine}</p></div>}
                        {v.trim && <div><span className="text-[10px] uppercase tracking-[0.12em] text-[#555]">Trim</span><p className="text-[#aaa] text-xs">{v.trim}</p></div>}
                      </div>
                      <div className="mt-4 pt-3 border-t border-#2A2A2A">
                        <Button onClick={() => { setForm(f => ({ ...f, vehicle_year: v.year, make: v.make, model: v.model, engine: v.engine || "", vin: v.vin || "", name: userName, email: localStorage.getItem("user_email") || "" })); setNewRequestOpen(true); }} variant="ghost" className="text-[#3B82F6] text-[10px] uppercase tracking-[0.1em] h-7 px-2 hover:bg-[#3B82F6]/10 rounded-none">
                          Request Part for This Vehicle <ArrowRight className="ml-1 h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* ============ REQUESTS ============ */}
          {activeTab === "requests" && (
            <div className="bg-[#121212] border border-#2A2A2A overflow-x-auto">
              <Table>
                <TableHeader><TableRow className="border-#2A2A2A hover:bg-transparent">
                  <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Part</TableHead>
                  <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Vehicle</TableHead>
                  <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Status</TableHead>
                  <TableHead className="text-[10px] uppercase tracking-[0.15em] text-[#555]">Date</TableHead>
                </TableRow></TableHeader>
                <TableBody>
                  {requests.map(r => { const s = STATUS_MAP[r.status] || STATUS_MAP.new; return (
                    <TableRow key={r.id} data-testid={`user-request-${r.id}`} className="border-#2A2A2A hover:bg-white/[0.02]">
                      <TableCell className="text-sm text-white font-medium">{r.part_needed}</TableCell>
                      <TableCell className="text-sm text-[#888]">{r.vehicle_year} {r.make} {r.model}</TableCell>
                      <TableCell><Badge className={`rounded-none text-[10px] uppercase border ${s.color}`}>{s.label}</Badge></TableCell>
                      <TableCell className="text-[11px] text-[#555]">{new Date(r.created_at).toLocaleDateString()}</TableCell>
                    </TableRow>
                  ); })}
                  {requests.length === 0 && <TableRow><TableCell colSpan={4} className="text-center py-12 text-[#555]">No part requests yet. Click "New Request" to get started.</TableCell></TableRow>}
                </TableBody>
              </Table>
            </div>
          )}

          {/* ============ QUOTES ============ */}
          {activeTab === "quotes" && (
            <div className="space-y-3">
              {quotes.map(q => (
                <div key={q.id} data-testid={`user-quote-${q.id}`} className="bg-[#121212] border border-#2A2A2A p-6">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-4">
                    <div>
                      <p className="text-[11px] text-[#3B82F6] uppercase tracking-[0.12em] font-semibold mb-1">{q.vehicle_info}</p>
                      <p className="text-white font-medium">{q.part_needed}</p>
                    </div>
                    <div className="flex items-center gap-3">
                      <Badge className={`rounded-none text-[10px] uppercase border ${QUOTE_STATUS[q.status] || ""}`}>{q.status}</Badge>
                      <span className="text-2xl font-semibold font-['Inter'] text-white">${q.total?.toLocaleString()}</span>
                    </div>
                  </div>
                  {q.items?.length > 0 && (
                    <div className="border-t border-#2A2A2A pt-3 mb-3">
                      {q.items.map((item, i) => (
                        <div key={i} className="flex justify-between text-sm py-1">
                          <span className="text-[#999]">{item.description || `Item ${i + 1}`}</span>
                          <span className="text-white">${(item.unit_price * (item.quantity || 1)).toLocaleString()}</span>
                        </div>
                      ))}
                    </div>
                  )}
                  {q.notes && <p className="text-sm text-[#777] mb-3">{q.notes}</p>}
                  {q.estimated_shipping && <p className="text-[11px] text-[#555]"><Truck className="h-3 w-3 inline mr-1" /> Est. shipping: {q.estimated_shipping}</p>}
                  {q.status === "pending" && (
                    <div className="flex gap-3 mt-4 border-t border-#2A2A2A pt-4">
                      <Button data-testid={`approve-quote-${q.id}`} onClick={() => handleQuoteAction(q.id, "approve")} className="bg-emerald-800/80 text-white hover:bg-emerald-700 rounded-none text-[11px] uppercase tracking-[0.1em] h-9 px-5">
                        <ThumbsUp className="h-3.5 w-3.5 mr-1.5" /> Approve
                      </Button>
                      <Button data-testid={`reject-quote-${q.id}`} onClick={() => handleQuoteAction(q.id, "reject")} variant="outline" className="border-red-800/50 text-red-400 hover:bg-red-900/30 rounded-none text-[11px] uppercase tracking-[0.1em] h-9 px-5">
                        <ThumbsDown className="h-3.5 w-3.5 mr-1.5" /> Reject
                      </Button>
                    </div>
                  )}
                </div>
              ))}
              {quotes.length === 0 && <div className="bg-[#121212] border border-#2A2A2A p-12 text-center text-[#555]">No quotes yet. They'll appear here when we price your requests.</div>}
            </div>
          )}

          {/* ============ ORDERS ============ */}
          {activeTab === "orders" && (
            <div className="space-y-3">
              {orders.map(o => { const os = ORDER_STATUS[o.status] || ORDER_STATUS.processing; return (
                <div key={o.id} data-testid={`user-order-${o.id}`} className="bg-[#121212] border border-#2A2A2A p-6">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-4">
                    <div>
                      <p className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1">{o.order_number}</p>
                      <p className="text-[11px] text-[#3B82F6] uppercase tracking-[0.12em] font-semibold">{o.vehicle_info}</p>
                      <p className="text-white font-medium">{o.part_needed}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-2xl font-semibold font-['Inter'] text-white">${o.total?.toLocaleString()}</p>
                      <p className="text-[11px] text-[#555]">{new Date(o.created_at).toLocaleDateString()}</p>
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center justify-between text-[11px] text-[#888] mb-2">
                      <span className="uppercase tracking-[0.1em]">{os.label}</span>
                      <span>{os.progress}%</span>
                    </div>
                    <Progress value={os.progress} className="h-1.5 rounded-none bg-[#1a1a1a]" />
                  </div>
                </div>
              ); })}
              {orders.length === 0 && <div className="bg-[#121212] border border-#2A2A2A p-12 text-center text-[#555]">No orders yet. Approve a quote to create an order.</div>}
            </div>
          )}

          {/* ============ INVOICES ============ */}
          {activeTab === "invoices" && (
            <div className="space-y-3">
              {invoices.map(inv => (
                <div key={inv.id} data-testid={`user-invoice-${inv.id}`} className="bg-[#121212] border border-#2A2A2A p-6">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                      <p className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1">{inv.invoice_number}</p>
                      <p className="text-[11px] text-[#3B82F6] uppercase tracking-[0.12em] font-semibold">{inv.vehicle_info}</p>
                      <p className="text-white font-medium">{inv.part_needed}</p>
                      {inv.due_date && <p className="text-[11px] text-[#555] mt-1">Due: {inv.due_date}</p>}
                    </div>
                    <div className="flex items-center gap-4">
                      <div className="text-right">
                        <p className="text-2xl font-semibold font-['Inter'] text-white">${inv.amount?.toLocaleString(undefined, { minimumFractionDigits: 2 })}</p>
                        <Badge className={`rounded-none text-[10px] uppercase border mt-1 ${inv.status === "paid" ? "bg-emerald-900/40 text-emerald-300 border-emerald-800/50" : "bg-amber-900/40 text-amber-300 border-amber-800/50"}`}>{inv.status}</Badge>
                      </div>
                      {inv.status === "unpaid" && (
                        <Button
                          data-testid={`pay-invoice-${inv.id}`}
                          onClick={() => handlePayInvoice(inv)}
                          disabled={payLoading}
                          className="bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.1em] hover:bg-[#2563EB] rounded-none text-[11px] h-10 px-6"
                        >
                          {payLoading ? <Loader2 className="h-3.5 w-3.5 animate-spin mr-1.5" /> : <CreditCard className="h-3.5 w-3.5 mr-1.5" />}
                          Pay Now
                        </Button>
                      )}
                      {inv.status === "paid" && (
                        <div className="flex items-center gap-1.5 text-emerald-400">
                          <CheckCircle2 className="h-5 w-5" />
                          <span className="text-[11px] uppercase tracking-[0.1em] font-semibold">Paid</span>
                        </div>
                      )}
                    </div>
                  </div>
                  {inv.notes && <p className="text-sm text-[#666] mt-3 border-t border-#2A2A2A pt-3">{inv.notes}</p>}
                </div>
              ))}
              {invoices.length === 0 && <div className="bg-[#121212] border border-#2A2A2A p-12 text-center text-[#555]">No invoices yet.</div>}
            </div>
          )}

          {/* ============ SHIPMENTS ============ */}
          {activeTab === "shipments" && (
            <div className="space-y-3">
              {shipments.map(sh => (
                <div key={sh.id} data-testid={`user-shipment-${sh.id}`} className="bg-[#121212] border border-#2A2A2A p-6">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                      <p className="text-[11px] text-[#3B82F6] uppercase tracking-[0.12em] font-semibold mb-1">{sh.vehicle_info}</p>
                      <p className="text-white font-medium mb-2">{sh.part_needed}</p>
                      <div className="flex flex-wrap gap-4 text-sm">
                        <span className="text-[#888]"><Truck className="h-3.5 w-3.5 inline mr-1" /> {sh.carrier}</span>
                        <span className="text-white font-mono text-[13px]">{sh.tracking_number}</span>
                      </div>
                    </div>
                    <div className="text-right">
                      <Badge className={`rounded-none text-[10px] uppercase border ${sh.status === "delivered" ? "bg-emerald-900/40 text-emerald-300 border-emerald-800/50" : "bg-cyan-900/40 text-cyan-300 border-cyan-800/50"}`}>
                        {sh.status === "in_transit" ? "In Transit" : "Delivered"}
                      </Badge>
                      {sh.estimated_delivery && <p className="text-[11px] text-[#555] mt-2"><MapPin className="h-3 w-3 inline mr-1" /> Est. {sh.estimated_delivery}</p>}
                    </div>
                  </div>
                </div>
              ))}
              {shipments.length === 0 && <div className="bg-[#121212] border border-#2A2A2A p-12 text-center text-[#555]">No shipments yet. Tracking info appears here once your order ships.</div>}
            </div>
          )}
        </div>
      </main>

      {/* ============ NEW REQUEST DIALOG ============ */}
      <Dialog open={newRequestOpen} onOpenChange={setNewRequestOpen}>
        <DialogContent className="bg-[#121212] border-#2A2A2A text-white max-w-2xl rounded-none max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-2xl font-semibold uppercase tracking-tight font-['Inter']">New Part Request</DialogTitle>
            <DialogDescription className="text-[#777]">Submit a new part request. We'll get back to you within 24-48 hours.</DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmitRequest} className="space-y-5 mt-2">
            <div className="flex gap-2">
              <Input data-testid="dash-vin-input" placeholder="VIN (17 chars, optional)" value={form.vin} onChange={update("vin")} maxLength={17} className={`${inputCls} flex-1 uppercase`} />
              <Button type="button" data-testid="dash-vin-decode" onClick={() => handleVinDecode(form, setForm, setVinLoading)} disabled={vinLoading} className="bg-[#3B82F6] text-white hover:bg-[#2563EB] rounded-none px-4 text-[11px] uppercase">
                {vinLoading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <><Search className="h-3.5 w-3.5 mr-1" /> Decode</>}
              </Button>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Year</Label><Input data-testid="dash-year" placeholder="2019" value={form.vehicle_year} onChange={update("vehicle_year")} className={inputCls} /></div>
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Make</Label><Input data-testid="dash-make" placeholder="Toyota" value={form.make} onChange={update("make")} className={inputCls} /></div>
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Model</Label><Input data-testid="dash-model" placeholder="Camry" value={form.model} onChange={update("model")} className={inputCls} /></div>
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Engine</Label><Input data-testid="dash-engine" placeholder="2.5L 4cyl" value={form.engine} onChange={update("engine")} className={inputCls} /></div>
            </div>
            <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Part Needed *</Label><Input data-testid="dash-part" placeholder="e.g. Driver side headlight assembly" value={form.part_needed} onChange={update("part_needed")} className={inputCls} required /></div>
            <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Budget</Label><Input data-testid="dash-budget" placeholder="e.g. $200-300" value={form.budget} onChange={update("budget")} className={inputCls} /></div>
            <div className="grid grid-cols-2 gap-3">
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Name *</Label><Input data-testid="dash-name" value={form.name} onChange={update("name")} className={inputCls} required /></div>
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Email *</Label><Input data-testid="dash-email" type="email" value={form.email} onChange={update("email")} className={inputCls} required /></div>
            </div>
            <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Notes</Label><textarea data-testid="dash-notes" placeholder="Additional details" value={form.notes} onChange={update("notes")} rows={2} className={`${inputCls} w-full p-3 h-auto resize-none`} /></div>
            <Button data-testid="dash-submit-request" type="submit" disabled={submitLoading} className="w-full bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.12em] hover:bg-[#2563EB] rounded-none py-5 text-[13px]">
              {submitLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null} Submit Request
            </Button>
          </form>
        </DialogContent>
      </Dialog>

      {/* ============ VEHICLE DIALOG ============ */}
      <Dialog open={vehicleDialogOpen} onOpenChange={setVehicleDialogOpen}>
        <DialogContent className="bg-[#121212] border-#2A2A2A text-white max-w-lg rounded-none">
          <DialogHeader>
            <DialogTitle className="text-2xl font-semibold uppercase tracking-tight font-['Inter']">
              {editingVehicle ? "Edit Vehicle" : "Add Vehicle"}
            </DialogTitle>
            <DialogDescription className="text-[#777]">
              {editingVehicle ? "Update your vehicle details." : "Add a vehicle to your garage for quick part requests."}
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSaveVehicle} className="space-y-4 mt-2">
            <div className="flex gap-2">
              <Input data-testid="veh-vin" placeholder="VIN (auto-fills details)" value={vehicleForm.vin} onChange={updateVeh("vin")} maxLength={17} className={`${inputCls} flex-1 uppercase`} />
              <Button type="button" data-testid="veh-vin-decode" onClick={() => handleVinDecode(vehicleForm, setVehicleForm, setVehVinLoading)} disabled={vehVinLoading} className="bg-[#3B82F6] text-white hover:bg-[#2563EB] rounded-none px-4 text-[11px] uppercase">
                {vehVinLoading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Decode"}
              </Button>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Year *</Label><Input data-testid="veh-year" placeholder="2020" value={vehicleForm.year} onChange={updateVeh("year")} className={inputCls} required /></div>
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Make *</Label><Input data-testid="veh-make" placeholder="Toyota" value={vehicleForm.make} onChange={updateVeh("make")} className={inputCls} required /></div>
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Model *</Label><Input data-testid="veh-model" placeholder="Camry" value={vehicleForm.model} onChange={updateVeh("model")} className={inputCls} required /></div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Engine</Label><Input data-testid="veh-engine" placeholder="2.5L 4cyl" value={vehicleForm.engine} onChange={updateVeh("engine")} className={inputCls} /></div>
              <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Trim</Label><Input data-testid="veh-trim" placeholder="SE, XLE, etc." value={vehicleForm.trim} onChange={updateVeh("trim")} className={inputCls} /></div>
            </div>
            <div><Label className="text-[10px] font-semibold uppercase tracking-[0.15em] text-[#555] mb-1.5 block">Nickname</Label><Input data-testid="veh-nickname" placeholder='e.g. "Daily Driver", "Work Truck"' value={vehicleForm.nickname} onChange={updateVeh("nickname")} className={inputCls} /></div>
            <Button data-testid="veh-save" type="submit" disabled={submitLoading} className="w-full bg-[#3B82F6] text-white uppercase font-semibold tracking-[0.12em] hover:bg-[#2563EB] rounded-none py-5 text-[13px]">
              {submitLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
              {editingVehicle ? "Update Vehicle" : "Add to Garage"}
            </Button>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
