'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '@/store';
import { logout, updateUser } from '@/store/authSlice';
import {
  User,
  ShoppingBag,
  Heart,
  MapPin,
  Wallet,
  Award,
  Download,
  FileText,
  Star,
  Bell,
  Lock,
  Moon,
  Sun,
  LogOut,
  Plus,
  Trash2,
  CheckCircle2,
  AlertCircle,
  Clock,
  ArrowRight,
  ShieldCheck,
  CreditCard,
  Smartphone,
  Eye,
} from 'lucide-react';
import { addToCart } from '@/store/cartSlice';
import api from '@/lib/api';

export default function CustomerDashboard() {
  const dispatch = useDispatch();
  const router = useRouter();
  const { user, isAuthenticated } = useSelector((state: RootState) => state.auth);

  React.useEffect(() => {
    if (!isAuthenticated && !user) {
      router.push('/login?redirect=/user/dashboard');
    }
  }, [isAuthenticated, user, router]);

  // Profile settings form state
  const [profileForm, setProfileForm] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
  });
  const [profileSaving, setProfileSaving] = useState(false);
  const [profileSuccess, setProfileSuccess] = useState('');
  const [profileError, setProfileError] = useState('');

  React.useEffect(() => {
    if (user) {
      setProfileForm({
        firstName: user.firstName || '',
        lastName: user.lastName || '',
        email: user.email || '',
        phone: user.phone || '',
      });
    }
  }, [user]);

  const handleProfileSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setProfileSaving(true);
    setProfileSuccess('');
    setProfileError('');
    try {
      const response = await api.put('/auth/profile', profileForm);
      if (response.data?.success) {
        setProfileSuccess('Profile updated successfully!');
        dispatch(updateUser(response.data.data.user));
      } else {
        setProfileError(response.data?.message || 'Failed to update profile');
      }
    } catch (err: any) {
      setProfileError(err.response?.data?.message || 'An error occurred while updating profile');
    } finally {
      setProfileSaving(false);
    }
  };

  const [activeTab, setActiveTab] = useState<
    | 'dashboard'
    | 'orders'
    | 'wishlist'
    | 'addresses'
    | 'wallet'
    | 'rewards'
    | 'downloads'
    | 'invoices'
    | 'reviews'
    | 'notifications'
    | 'profile'
    | 'security'
  >('dashboard');

  const [darkMode, setDarkMode] = useState(false);

  if (!isAuthenticated && !user) {
    return (
      <div className="max-w-md mx-auto px-4 py-24 text-center space-y-4">
        <div className="w-16 h-16 rounded-full bg-rose-50 dark:bg-rose-950/50 text-[#701a08] flex items-center justify-center mx-auto shadow-inner">
          <Lock className="w-8 h-8" />
        </div>
        <h2 className="text-2xl font-extrabold text-zinc-900 dark:text-zinc-100">Authentication Required</h2>
        <p className="text-xs text-zinc-500 leading-relaxed">
          Please sign in to your Indian Books Worldwide customer account to view your order history, wallet credit, and saved addresses.
        </p>
        <Link
          href="/login?redirect=/user/dashboard"
          className="inline-block px-7 py-3.5 rounded-2xl bg-[#701a08] hover:bg-[#581406] text-white font-extrabold text-xs shadow-xl transition-all"
        >
          Sign In To Customer Portal
        </Link>
      </div>
    );
  }

  // Address state
  const [addresses, setAddresses] = useState([
    { id: '1', name: 'Home Address', street: '42 Heritage Lane, Connaught Place', city: 'New Delhi', state: 'Delhi', zip: '110001', country: 'India', isDefault: true },
    { id: '2', name: 'Office Address', street: 'Cyber City, Tower B, 5th Floor', city: 'Gurugram', state: 'Haryana', zip: '122002', country: 'India', isDefault: false },
  ]);

  // Wishlist State
  const [wishlistItems, setWishlistItems] = useState<Array<{
    id: string;
    bookId: string;
    book: {
      id: string;
      title: string;
      slug: string;
      price: number;
      discountPrice?: number | null;
      stock: number;
      coverImage?: string | null;
      authorName?: string;
      categoryName?: string;
    };
  }>>([]);
  const [wishlistLoading, setWishlistLoading] = useState(false);

  // Fetch wishlist from API
  const fetchWishlist = async () => {
    try {
      setWishlistLoading(true);
      const res = await api.get('/wishlist');
      if (res.data?.data?.items) {
        setWishlistItems(res.data.data.items);
      }
    } catch (err) {
      // Fallback to empty if error
      setWishlistItems([]);
    } finally {
      setWishlistLoading(false);
    }
  };

  React.useEffect(() => {
    if (isAuthenticated) {
      fetchWishlist();
    }
  }, [isAuthenticated]);

  const handleRemoveFromWishlist = async (bookId: string) => {
    try {
      await api.delete(`/wishlist/${bookId}`);
      setWishlistItems((prev) => prev.filter((i) => i.bookId !== bookId && i.id !== bookId));
    } catch (err) {
      console.error('Failed to remove from wishlist', err);
    }
  };

  const handleMoveWishlistToCart = (item: any) => {
    const book = item.book || item;
    dispatch(
      addToCart({
        id: book.id,
        bookId: book.id,
        title: book.title,
        price: book.price,
        discountPrice: book.discountPrice ?? undefined,
        coverImage: book.coverImage ?? undefined,
        stock: book.stock ?? 10,
      })
    );
    handleRemoveFromWishlist(item.bookId || item.id);
  };

  return (
    <div className={`min-h-screen ${darkMode ? 'dark bg-zinc-950 text-zinc-100' : 'bg-zinc-50 text-zinc-900'} transition-colors py-10`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">
        {/* Top Banner */}
        <div className="bg-gradient-to-r from-saffron-600 via-saffron-700 to-amber-700 rounded-3xl p-8 text-white shadow-xl flex flex-col md:flex-row items-center justify-between gap-6 relative overflow-hidden">
          <div className="flex items-center gap-5">
            <div className="w-16 h-16 rounded-full bg-white/20 backdrop-blur-md flex items-center justify-center font-extrabold text-2xl border border-white/30 shrink-0">
              {user?.firstName ? user.firstName[0] : 'R'}
            </div>
            <div>
              <span className="text-xs uppercase font-extrabold tracking-widest text-saffron-200">Customer Portal</span>
              <h1 className="text-3xl font-extrabold mt-0.5">Namaste, {user?.firstName || 'Reader'}!</h1>
              <p className="text-xs text-white/80 mt-1">
                Manage your orders, reading lists, store credit, and shipping preferences.
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => setDarkMode(!darkMode)}
              className="p-2.5 rounded-2xl bg-white/10 backdrop-blur-md border border-white/20 hover:bg-white/20 transition-colors"
            >
              {darkMode ? <Sun className="w-4 h-4 text-amber-300" /> : <Moon className="w-4 h-4 text-white" />}
            </button>
            <div className="px-4 py-2 rounded-2xl bg-white/20 backdrop-blur-md border border-white/30 text-xs font-extrabold flex items-center gap-1.5">
              <Award className="w-4 h-4 text-amber-300" /> Gold Member (1,240 Pts)
            </div>
          </div>
        </div>

        {/* Dashboard Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* Left Navigation Sidebar */}
          <aside className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-4 space-y-2 shadow-sm h-fit">
            {[
              { id: 'dashboard', label: 'Overview Dashboard', icon: User },
              { id: 'orders', label: 'My Orders', icon: ShoppingBag, badge: '2 Active' },
              { id: 'wishlist', label: 'Saved Wishlist', icon: Heart, badge: wishlistItems.length },
              { id: 'addresses', label: 'Shipping Addresses', icon: MapPin },
              { id: 'wallet', label: 'Store Wallet Credit', icon: Wallet, badge: '₹450' },
              { id: 'rewards', label: 'Reward Points', icon: Award },
              { id: 'downloads', label: 'Digital Downloads', icon: Download },
              { id: 'invoices', label: 'Tax Invoices', icon: FileText },
              { id: 'reviews', label: 'My Reviews', icon: Star },
              { id: 'notifications', label: 'Alerts & Messages', icon: Bell, badge: '3 Unread' },
              { id: 'profile', label: 'Profile Settings', icon: User },
              { id: 'security', label: 'Account Security', icon: Lock },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                className={`w-full flex items-center justify-between px-3.5 py-2.5 rounded-2xl text-xs font-bold transition-all ${
                  activeTab === tab.id
                    ? 'gradient-saffron text-white shadow-md shadow-saffron-500/20'
                    : 'text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800'
                }`}
              >
                <div className="flex items-center gap-3">
                  <tab.icon className="w-4 h-4" />
                  {tab.label}
                </div>
                {tab.badge && (
                  <span className={`text-[10px] font-extrabold px-2 py-0.5 rounded-full ${
                    activeTab === tab.id ? 'bg-white/20 text-white' : 'bg-saffron-50 text-saffron-600 dark:bg-saffron-950 dark:text-saffron-300'
                  }`}>
                    {tab.badge}
                  </span>
                )}
              </button>
            ))}

            <button
              onClick={() => dispatch(logout())}
              className="w-full flex items-center gap-3 px-3.5 py-2.5 rounded-2xl text-xs font-bold text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30 transition-all border-t border-zinc-100 dark:border-zinc-800 mt-2"
            >
              <LogOut className="w-4 h-4" /> Sign Out Account
            </button>
          </aside>

          {/* Right Main Content Area */}
          <main className="lg:col-span-3 space-y-6">
            {/* Tab 1: Overview Dashboard */}
            {activeTab === 'dashboard' && (
              <div className="space-y-6">
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
                  <div className="bg-white dark:bg-zinc-900 p-5 rounded-3xl border border-zinc-200 dark:border-zinc-800 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-saffron-50 dark:bg-saffron-950/40 text-saffron-600 flex items-center justify-center">
                      <ShoppingBag className="w-6 h-6" />
                    </div>
                    <div>
                      <span className="text-2xl font-extrabold">4</span>
                      <p className="text-xs text-zinc-500 font-bold">Total Orders Placed</p>
                    </div>
                  </div>

                  <div className="bg-white dark:bg-zinc-900 p-5 rounded-3xl border border-zinc-200 dark:border-zinc-800 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-red-50 dark:bg-red-950/40 text-red-600 flex items-center justify-center">
                      <Heart className="w-6 h-6" />
                    </div>
                    <div>
                      <span className="text-2xl font-extrabold">{wishlistItems.length}</span>
                      <p className="text-xs text-zinc-500 font-bold">Saved Books</p>
                    </div>
                  </div>

                  <div className="bg-white dark:bg-zinc-900 p-5 rounded-3xl border border-zinc-200 dark:border-zinc-800 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-peacock-50 dark:bg-peacock-950/40 text-peacock-600 flex items-center justify-center">
                      <Wallet className="w-6 h-6" />
                    </div>
                    <div>
                      <span className="text-2xl font-extrabold">₹450</span>
                      <p className="text-xs text-zinc-500 font-bold">Store Wallet Credit</p>
                    </div>
                  </div>
                </div>

                {/* Live Recent Orders */}
                <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-4 shadow-sm">
                  <div className="flex items-center justify-between">
                    <h3 className="font-extrabold text-sm">Active Orders Telemetry</h3>
                    <button onClick={() => setActiveTab('orders')} className="text-xs font-bold text-saffron-600">
                      View All Orders →
                    </button>
                  </div>

                  <div className="space-y-3">
                    {[
                      { id: 'IBW-98201', title: 'The Mahabharata: Complete Unabridged', status: 'SHIPPED', carrier: 'DHL Express', total: 1199 },
                      { id: 'IBW-84102', title: 'Malgudi Days & Discovery of India', status: 'DELIVERED', carrier: 'BlueDart', total: 848 },
                    ].map((ord) => (
                      <div key={ord.id} className="p-4 rounded-2xl border border-zinc-100 dark:border-zinc-800 flex justify-between items-center text-xs">
                        <div>
                          <span className="font-extrabold text-saffron-600">{ord.id}</span>
                          <h4 className="font-bold text-zinc-900 dark:text-zinc-100 mt-0.5">{ord.title}</h4>
                          <p className="text-[10px] text-zinc-400 mt-0.5">Carrier: {ord.carrier}</p>
                        </div>
                        <div className="text-right">
                          <span className="font-extrabold text-base">₹{ord.total}</span>
                          <span className={`block text-[10px] font-extrabold px-2.5 py-0.5 rounded-full mt-1 ${
                            ord.status === 'DELIVERED' ? 'bg-green-50 text-green-600' : 'bg-blue-50 text-blue-600'
                          }`}>
                            {ord.status}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* Tab 2: Orders */}
            {activeTab === 'orders' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <h2 className="text-xl font-extrabold">My Order History</h2>
                <div className="space-y-4">
                  {[
                    { id: 'IBW-98201', date: '2026-08-01', title: 'The Mahabharata: Complete Unabridged', status: 'SHIPPED', total: 1199 },
                    { id: 'IBW-84102', date: '2026-07-20', title: 'Malgudi Days', status: 'DELIVERED', total: 299 },
                    { id: 'IBW-71003', date: '2026-06-15', title: 'Discovery of India', status: 'DELIVERED', total: 549 },
                  ].map((ord) => (
                    <div key={ord.id} className="p-5 rounded-2xl border border-zinc-100 dark:border-zinc-800 flex justify-between items-center text-xs">
                      <div className="space-y-1">
                        <span className="font-extrabold text-saffron-600">{ord.id}</span>
                        <h4 className="font-bold">{ord.title}</h4>
                        <span className="text-[10px] text-zinc-400 block">Ordered on {ord.date}</span>
                      </div>
                      <div className="text-right space-y-2">
                        <span className="font-extrabold text-base block">₹{ord.total}</span>
                        <button onClick={() => alert(`Downloading GST Invoice for ${ord.id}...`)} className="px-3 py-1.5 rounded-xl border border-zinc-300 dark:border-zinc-700 text-xs font-bold flex items-center gap-1">
                          <FileText className="w-3.5 h-3.5" /> Invoice
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Tab 3: Wishlist */}
            {activeTab === 'wishlist' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <div className="flex items-center justify-between">
                  <h2 className="text-xl font-extrabold flex items-center gap-2">
                    <Heart className="w-5 h-5 text-[#701a08]" /> Saved Books Wishlist ({wishlistItems.length})
                  </h2>
                  {wishlistItems.length > 0 && (
                    <button
                      onClick={async () => {
                        await api.delete('/wishlist/clear');
                        setWishlistItems([]);
                      }}
                      className="text-xs font-bold text-red-600 hover:text-red-700 flex items-center gap-1"
                    >
                      <Trash2 className="w-3.5 h-3.5" /> Clear All
                    </button>
                  )}
                </div>

                {wishlistLoading ? (
                  <div className="py-12 text-center text-xs text-zinc-400 animate-pulse">
                    Loading your saved wishlist...
                  </div>
                ) : wishlistItems.length === 0 ? (
                  <div className="py-16 text-center space-y-3">
                    <Heart className="w-12 h-12 mx-auto text-zinc-300 dark:text-zinc-700" />
                    <p className="text-sm font-bold text-zinc-700 dark:text-zinc-300">Your wishlist is currently empty.</p>
                    <p className="text-xs text-zinc-500">Save books while exploring our sacred texts and classical catalog.</p>
                    <Link
                      href="/books"
                      className="inline-block px-5 py-2.5 rounded-xl bg-[#701a08] text-white text-xs font-bold shadow-md hover:bg-[#581406]"
                    >
                      Browse Store Catalog
                    </Link>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    {wishlistItems.map((item) => {
                      const book = item.book;
                      const price = book?.discountPrice || book?.price || 0;
                      return (
                        <div key={item.id} className="p-4 rounded-2xl border border-zinc-200 dark:border-zinc-800 flex gap-4 items-center bg-zinc-50/50 dark:bg-zinc-800/30">
                          {book?.coverImage ? (
                            <img src={book.coverImage} alt={book.title} className="w-16 h-22 rounded-xl object-contain bg-white dark:bg-zinc-900 border p-1 shrink-0" />
                          ) : (
                            <div className="w-16 h-22 rounded-xl bg-zinc-200 dark:bg-zinc-800 flex items-center justify-center text-[10px] text-zinc-400 shrink-0">
                              No image
                            </div>
                          )}
                          <div className="space-y-1 flex-1 min-w-0">
                            <Link href={`/books/${book?.slug || book?.id}`} className="font-bold text-xs line-clamp-1 hover:text-[#701a08] dark:hover:text-amber-500">
                              {book?.title}
                            </Link>
                            <p className="text-[11px] text-zinc-500 line-clamp-1">{book?.authorName}</p>
                            <div className="flex items-center gap-2">
                              <span className="text-xs font-extrabold text-[#701a08] dark:text-amber-500">₹{price}</span>
                              {book?.discountPrice && (
                                <span className="text-[10px] text-zinc-400 line-through">₹{book.price}</span>
                              )}
                            </div>
                            <div className="flex items-center gap-2 pt-1">
                              <button
                                onClick={() => handleMoveWishlistToCart(item)}
                                className="px-3 py-1.5 rounded-lg bg-[#701a08] text-white text-[11px] font-bold shadow-sm hover:bg-[#581406]"
                              >
                                Move to Cart
                              </button>
                              <button
                                onClick={() => handleRemoveFromWishlist(item.bookId || item.id)}
                                className="p-1.5 rounded-lg text-zinc-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-zinc-800"
                                title="Remove from wishlist"
                              >
                                <Trash2 className="w-3.5 h-3.5" />
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            )}

            {/* Tab 4: Addresses */}
            {activeTab === 'addresses' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <div className="flex justify-between items-center">
                  <h2 className="text-xl font-extrabold">Saved Shipping Addresses</h2>
                  <button className="px-4 py-2 rounded-xl gradient-saffron text-white text-xs font-bold flex items-center gap-1">
                    <Plus className="w-4 h-4" /> Add Address
                  </button>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {addresses.map((addr) => (
                    <div key={addr.id} className="p-5 rounded-2xl border border-zinc-200 dark:border-zinc-800 space-y-2 text-xs">
                      <div className="flex justify-between">
                        <span className="font-bold text-saffron-600">{addr.name}</span>
                        {addr.isDefault && <span className="text-[10px] font-extrabold text-green-600 bg-green-50 px-2 py-0.5 rounded-full">DEFAULT</span>}
                      </div>
                      <p className="font-bold">{addr.street}</p>
                      <p className="text-zinc-500">{addr.city}, {addr.state} - {addr.zip}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Tab 5: Wallet */}
            {activeTab === 'wallet' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <h2 className="text-xl font-extrabold">Store Wallet Balance</h2>
                <div className="p-6 rounded-2xl bg-gradient-to-r from-peacock-700 to-peacock-800 text-white flex justify-between items-center shadow-lg">
                  <div>
                    <span className="text-xs uppercase font-bold opacity-80">Available Store Credit</span>
                    <span className="text-3xl font-extrabold block mt-1">₹450.00</span>
                  </div>
                  <button className="px-4 py-2 rounded-xl bg-white text-peacock-800 font-bold text-xs shadow">
                    Add Funds
                  </button>
                </div>
              </div>
            )}

            {/* Tab 6: Rewards */}
            {activeTab === 'rewards' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <h2 className="text-xl font-extrabold">Literary Club Rewards</h2>
                <p className="text-xs text-zinc-500">Earn 10 points for every ₹100 spent on Indian literature.</p>
              </div>
            )}

            {/* Tab 7: Digital Downloads */}
            {activeTab === 'downloads' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <h2 className="text-xl font-extrabold">My Digital Library & eBooks</h2>
                <p className="text-xs text-zinc-500">Download PDF & ePub versions of your purchased manuscripts.</p>
              </div>
            )}

            {/* Tab 8: Invoices */}
            {activeTab === 'invoices' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <div className="border-b border-zinc-100 dark:border-zinc-800 pb-3">
                  <h2 className="text-xl font-extrabold flex items-center gap-2">
                    <FileText className="w-5 h-5 text-[#701a08]" /> Tax Invoices & Purchase Receipts
                  </h2>
                  <p className="text-xs text-zinc-500 mt-0.5">Official GST compliance records for your library purchases. Shipped worldwide.</p>
                </div>

                <div className="overflow-x-auto text-xs">
                  <table className="w-full text-left border-collapse">
                    <thead>
                      <tr className="border-b border-zinc-200 dark:border-zinc-800 text-zinc-400 font-extrabold uppercase text-[9px] tracking-wider">
                        <th className="py-2.5">Invoice No.</th>
                        <th className="py-2.5">Date</th>
                        <th className="py-2.5">Gateway</th>
                        <th className="py-2.5">Amount</th>
                        <th className="py-2.5">Status</th>
                        <th className="py-2.5 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="font-bold divide-y divide-zinc-100 dark:divide-zinc-800">
                      {[
                        { num: 'INV-IBW-98201', date: '2026-08-08', gateway: 'RAZORPAY', amount: '₹2,499.00', status: 'PAID' },
                        { num: 'INV-IBW-98202', date: '2026-08-07', gateway: 'PHONEPE', amount: '₹1,199.00', status: 'PAID' },
                        { num: 'INV-IBW-98203', date: '2026-08-07', gateway: 'STRIPE', amount: '₹4,890.00', status: 'FAILED' },
                      ].map((inv) => (
                        <tr key={inv.num} className="hover:bg-zinc-50 dark:hover:bg-zinc-800/20">
                          <td className="py-3 font-mono">{inv.num}</td>
                          <td className="py-3 text-zinc-500">{inv.date}</td>
                          <td className="py-3 text-zinc-400">{inv.gateway}</td>
                          <td className="py-3 text-[#701a08] dark:text-amber-500">{inv.amount}</td>
                          <td className="py-3">
                            <span className={`px-2 py-0.5 rounded text-[9px] uppercase ${
                              inv.status === 'PAID'
                                ? 'bg-green-100 text-green-800 dark:bg-green-950/40 dark:text-green-400'
                                : 'bg-red-100 text-red-800 dark:bg-red-950/40 dark:text-red-400'
                            }`}>
                              {inv.status}
                            </span>
                          </td>
                          <td className="py-3 text-right">
                            {inv.status === 'PAID' ? (
                              <a
                                href={`${api.defaults.baseURL || ''}/payments/invoice/download/${inv.num}`}
                                target="_blank"
                                rel="noreferrer"
                                className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-zinc-100 hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700 text-zinc-800 dark:text-zinc-200 text-[10px] font-extrabold shadow-xs"
                              >
                                <Download className="w-3.5 h-3.5" /> Download PDF
                              </a>
                            ) : (
                              <button
                                onClick={() => {
                                  router.push('/checkout?retry=true');
                                }}
                                className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[#701a08] hover:bg-[#581406] text-white text-[10px] font-extrabold shadow-xs"
                              >
                                <CreditCard className="w-3.5 h-3.5" /> Retry Pay
                              </button>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* Tab 9: Reviews */}
            {activeTab === 'reviews' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <h2 className="text-xl font-extrabold">My Book Reviews & Ratings</h2>
                <p className="text-xs text-zinc-500">Your published feedback and star ratings on Indian books.</p>
              </div>
            )}

            {/* Tab 10: Notifications */}
            {activeTab === 'notifications' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <h2 className="text-xl font-extrabold">Notifications & Broadcasts</h2>
                <p className="text-xs text-zinc-500">Order updates, shipping tracking notices, and exclusive book releases.</p>
              </div>
            )}

            {/* Tab 11: Profile */}
            {activeTab === 'profile' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <div>
                  <h2 className="text-xl font-extrabold text-zinc-900 dark:text-zinc-100">Personal Profile Information</h2>
                  <p className="text-xs text-zinc-500 mt-1">Update your account name, email address, and phone details.</p>
                </div>

                {profileSuccess && (
                  <div className="p-3.5 rounded-2xl bg-emerald-50 dark:bg-emerald-950/40 text-emerald-800 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-900/60 text-xs font-bold flex items-center gap-2">
                    <CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
                    {profileSuccess}
                  </div>
                )}

                {profileError && (
                  <div className="p-3.5 rounded-2xl bg-rose-50 dark:bg-rose-950/40 text-rose-800 dark:text-rose-400 border border-rose-200 dark:border-rose-900/60 text-xs font-bold flex items-center gap-2">
                    <AlertCircle className="w-4 h-4 shrink-0 text-rose-600 dark:text-rose-400" />
                    {profileError}
                  </div>
                )}

                <form onSubmit={handleProfileSubmit} className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-1">
                      <label htmlFor="profile-firstName" className="text-[10px] uppercase tracking-wider font-extrabold text-zinc-500 block">First Name</label>
                      <input
                        id="profile-firstName"
                        type="text"
                        required
                        value={profileForm.firstName}
                        onChange={(e) => setProfileForm(prev => ({ ...prev, firstName: e.target.value }))}
                        className="w-full px-4 py-3 text-xs rounded-xl bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-saffron-500"
                      />
                    </div>
                    <div className="space-y-1">
                      <label htmlFor="profile-lastName" className="text-[10px] uppercase tracking-wider font-extrabold text-zinc-500 block">Last Name</label>
                      <input
                        id="profile-lastName"
                        type="text"
                        required
                        value={profileForm.lastName}
                        onChange={(e) => setProfileForm(prev => ({ ...prev, lastName: e.target.value }))}
                        className="w-full px-4 py-3 text-xs rounded-xl bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-saffron-500"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-1">
                      <label htmlFor="profile-email" className="text-[10px] uppercase tracking-wider font-extrabold text-zinc-500 block">Email Address</label>
                      <input
                        id="profile-email"
                        type="email"
                        required
                        value={profileForm.email}
                        onChange={(e) => setProfileForm(prev => ({ ...prev, email: e.target.value }))}
                        className="w-full px-4 py-3 text-xs rounded-xl bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-saffron-500"
                      />
                    </div>
                    <div className="space-y-1">
                      <label htmlFor="profile-phone" className="text-[10px] uppercase tracking-wider font-extrabold text-zinc-500 block">Phone Number</label>
                      <input
                        id="profile-phone"
                        type="tel"
                        value={profileForm.phone}
                        onChange={(e) => setProfileForm(prev => ({ ...prev, phone: e.target.value }))}
                        className="w-full px-4 py-3 text-xs rounded-xl bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-saffron-500"
                        placeholder="e.g. +91 98765 43210"
                      />
                    </div>
                  </div>

                  <div className="pt-2">
                    <button
                      id="save-profile-btn"
                      type="submit"
                      disabled={profileSaving}
                      className="px-6 py-3 rounded-xl bg-[#701a08] hover:bg-[#581406] text-white font-extrabold text-xs shadow-md transition-colors disabled:opacity-40"
                    >
                      {profileSaving ? 'Saving Changes...' : 'Save Profile Changes'}
                    </button>
                  </div>
                </form>
              </div>
            )}

            {/* Tab 12: Security */}
            {activeTab === 'security' && (
              <div className="bg-white dark:bg-zinc-900 rounded-3xl border border-zinc-200 dark:border-zinc-800 p-6 space-y-6 shadow-sm">
                <h2 className="text-xl font-extrabold">Account Security & Sessions</h2>
                <p className="text-xs text-zinc-500">Change password, manage active device logins, and enable two-factor authentication.</p>
              </div>
            )}
          </main>
        </div>
      </div>
    </div>
  );
}
