"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { API_BASE_URL } from "@/utils/apiHelper";
import { 
  FaUser, 
  FaMapMarkerAlt, 
  FaBox, 
  FaWallet, 
  FaChevronRight, 
  FaClock, 
  FaCheckCircle, 
  FaTruck,
  FaSearch,
  FaHome
} from "react-icons/fa";
import { formatPrice } from "@/utils/currencyHelper";

type Order = {
  order_id: string;
  status: string;
  total_amount?: number;
  total_price?: number;
  created_at?: string;
  order_date?: string;
  coins_earned?: number;
  coins_redeemed?: number;
  coupon_code?: string | null;
  discount_applied?: number;
  coin_discount?: number;
  payment_status?: string;
  items?: { currency?: string }[];
};

type UserProfile = {
  first_name: string;
  last_name: string;
  email: string;
};

export default function ProfileOrdersPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  
  // Filters
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [dateFilter, setDateFilter] = useState("all");
  const [customStartDate, setCustomStartDate] = useState("");
  const [customEndDate, setCustomEndDate] = useState("");
  
  const router = useRouter();

  useEffect(() => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      router.push("/login");
      return;
    }

    const fetchData = async () => {
      try {
        // Fetch Profile
        const profileRes = await fetch(`${API_BASE_URL}/users/me`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (profileRes.status === 401) {
          localStorage.removeItem("access_token");
          router.push("/login");
          return;
        }
        if (profileRes.ok) {
          setProfile(await profileRes.json());
        }

        // Fetch Orders
        const ordersRes = await fetch(`${API_BASE_URL}/api/v1/b2b-orders/my-orders`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (ordersRes.ok) {
          const data = await ordersRes.json();
          const list = Array.isArray(data) ? data : data.orders || data.items || [];
          setOrders(list);
        }
      } catch (err) {
        console.error("Failed to fetch orders data:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [router]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  const initials = profile ? `${profile.first_name?.[0] || ""}${profile.last_name?.[0] || ""}`.toUpperCase() : "U";

  // Filter Logic
  const filteredOrders = orders.filter(order => {
    const matchesSearch = order.order_id.toLowerCase().includes(searchQuery.toLowerCase().trim());
    
    // Status Filter
    let matchesStatus = true;
    if (statusFilter !== "all") {
      const status = (order.status || "").toLowerCase();
      if (statusFilter === "pending") matchesStatus = !status.includes("shipped") && !status.includes("delivered") && !status.includes("completed");
      else if (statusFilter === "shipped") matchesStatus = status.includes("shipped") || status.includes("dispatch");
      else if (statusFilter === "delivered") matchesStatus = status.includes("delivered") || status.includes("completed");
    }

    // Date Filter
    let matchesDate = true;
    const dateStr = order.created_at ?? order.order_date ?? null;
    if (dateStr && dateFilter !== "all") {
      const orderDate = new Date(dateStr);
      const now = new Date();
      
      if (dateFilter === "30days") {
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(now.getDate() - 30);
        matchesDate = orderDate >= thirtyDaysAgo;
      } else if (dateFilter === "6months") {
        const sixMonthsAgo = new Date();
        sixMonthsAgo.setMonth(now.getMonth() - 6);
        matchesDate = orderDate >= sixMonthsAgo;
      } else if (dateFilter === "2026") {
        matchesDate = orderDate.getFullYear() === 2026;
      } else if (dateFilter === "custom") {
        if (customStartDate) {
          const start = new Date(customStartDate);
          start.setHours(0, 0, 0, 0);
          matchesDate = matchesDate && orderDate >= start;
        }
        if (customEndDate) {
          const end = new Date(customEndDate);
          end.setHours(23, 59, 59, 999);
          matchesDate = matchesDate && orderDate <= end;
        }
      }
    }
    
    return matchesSearch && matchesStatus && matchesDate;
  });

  const getStatusIcon = (status: string) => {
    const s = (status || "").toLowerCase();
    if (s.includes("delivered") || s.includes("completed")) return <FaCheckCircle className="text-emerald-500 text-sm" />;
    if (s.includes("shipped") || s.includes("dispatch")) return <FaTruck className="text-blue-500 text-sm" />;
    return <FaClock className="text-[#FF9900] text-sm" />;
  };

  const getStatusColor = (status: string) => {
    const s = (status || "").toLowerCase();
    if (s.includes("delivered") || s.includes("completed")) return "bg-emerald-50/70 text-emerald-800 border-emerald-300";
    if (s.includes("shipped") || s.includes("dispatch")) return "bg-blue-50/70 text-blue-850 border-blue-300";
    return "bg-amber-50/70 text-[#C26200] border-amber-300";
  };

  const formatDate = (dateString?: string | null) => {
    if (!dateString) return "N/A";
    try {
      return new Date(dateString).toLocaleDateString('en-IN', {
        year: 'numeric', month: 'short', day: 'numeric'
      });
    } catch {
      return dateString;
    }
  };

  return (
    <div className="bg-[#FAF9F6] min-h-screen py-10">
      <div className="max-w-6xl mx-auto px-4 sm:px-6">
        
        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-xs font-semibold text-gray-400 mb-8 select-none">
          <Link href="/" className="hover:text-primary transition-colors flex items-center gap-1">
            <FaHome className="text-[11px] mb-0.5" /> Home
          </Link>
          <FaChevronRight className="text-[8px]" />
          <Link href="/profile" className="hover:text-primary transition-colors">My Account</Link>
          <FaChevronRight className="text-[8px]" />
          <span className="text-gray-600">My Orders</span>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">
          
          {/* Shared Sidebar */}
          <div className="col-span-1 flex flex-col gap-6 lg:sticky lg:top-28">
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-8 flex flex-col items-center text-center">
              <div 
                style={{ backgroundColor: "#1e293b", color: "#ffffff" }}
                className="w-20 h-20 rounded-full flex items-center justify-center text-2xl font-black mb-4 shadow-md relative shrink-0"
              >
                {initials}
                <div className="absolute bottom-0 right-0 w-5 h-5 rounded-full bg-emerald-500 border-2 border-white flex items-center justify-center text-[10px] text-white">✓</div>
              </div>
              <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1 select-none">Welcome Back,</div>
              <h2 className="text-xl font-extrabold text-gray-800 leading-tight">{profile?.first_name || "Dealer"}</h2>
            </div>

            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 flex flex-col gap-6">
              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">My Account</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/order" className="flex items-center justify-between px-3 py-2.5 rounded-xl bg-primary-light text-primary text-xs font-bold transition-colors">
                    <span className="flex items-center gap-2.5"><FaBox /> MY ORDERS</span>
                    <FaChevronRight className="text-[8px]" />
                  </Link>
                  <Link href="/profile" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5"><FaUser className="text-gray-400" /> MY PROFILE</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                </nav>
              </div>

              <div className="border-t border-gray-100"></div>

              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">Reward Coins</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/wallet" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5">🪙 MY COINS</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                </nav>
              </div>
            </div>
          </div>

          {/* Right Column: Order List & Filters */}
          <div className="col-span-1 lg:col-span-3 flex flex-col gap-6">
            
            {/* Header Area */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 select-none">
              <div>
                <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-0.5">Dealer Orders</div>
                <h2 className="text-xl font-black text-gray-900 uppercase tracking-tight">Order History</h2>
              </div>

              {/* Status Filters */}
              <div className="flex items-center gap-1.5 bg-white border border-gray-200 p-1 rounded-xl shadow-[0_2px_10px_rgba(0,0,0,0.01)] text-[10px] font-bold">
                {["all", "pending", "shipped", "delivered"].map(status => (
                  <button
                    key={status}
                    onClick={() => setStatusFilter(status)}
                    className={`px-3 py-1.5 rounded-lg uppercase tracking-wider transition-all ${
                      statusFilter === status 
                        ? 'bg-primary text-white shadow-sm' 
                        : 'text-gray-500 hover:text-gray-800'
                    }`}
                  >
                    {status}
                  </button>
                ))}
              </div>
            </div>

            {/* Search & Date Filter Row */}
            <div className="flex flex-col sm:flex-row gap-4 items-stretch sm:items-center">
              <div className="relative flex-1">
                <input
                  type="text"
                  placeholder="Search by Order ID..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-3 bg-white border border-gray-200 rounded-2xl text-xs font-bold text-gray-805 placeholder-gray-400 focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/10 transition-all shadow-[0_2px_10px_rgba(0,0,0,0.01)]"
                />
                <FaSearch className="absolute left-3.5 top-3.5 text-gray-400 text-sm" />
                {searchQuery && (
                  <button
                    onClick={() => setSearchQuery("")}
                    className="absolute right-3.5 top-3.5 text-xs text-gray-400 hover:text-gray-600 transition-colors font-bold uppercase"
                  >
                    Clear
                  </button>
                )}
              </div>

              {/* Date Filter */}
              <div className="flex items-center gap-2">
                <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider select-none shrink-0">Date:</span>
                <select
                  value={dateFilter}
                  onChange={(e) => setDateFilter(e.target.value)}
                  className="bg-white border border-gray-200 text-xs font-bold text-gray-700 px-4 py-3 rounded-2xl focus:outline-none focus:border-primary transition-all cursor-pointer shadow-[0_2px_10px_rgba(0,0,0,0.01)] min-w-[150px] hover:bg-gray-50"
                >
                  <option value="all">All Time</option>
                  <option value="30days">Last 30 Days</option>
                  <option value="6months">Last 6 Months</option>
                  <option value="2026">Year 2026</option>
                  <option value="custom">Custom Range...</option>
                </select>
              </div>
            </div>

            {/* Custom Date Picker Inputs */}
            {dateFilter === "custom" && (
              <div className="flex flex-wrap items-center gap-3 bg-white border border-gray-200 p-4 rounded-2xl shadow-[0_2px_10px_rgba(0,0,0,0.01)]">
                <div className="flex items-center gap-2">
                  <span className="text-[10px] font-bold text-gray-400 uppercase">From:</span>
                  <input
                    type="date"
                    value={customStartDate}
                    onChange={(e) => setCustomStartDate(e.target.value)}
                    className="bg-gray-50 border border-gray-200 text-xs font-bold text-gray-700 px-3 py-1.5 rounded-xl focus:outline-none focus:border-primary transition-all"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[10px] font-bold text-gray-400 uppercase">To:</span>
                  <input
                    type="date"
                    value={customEndDate}
                    onChange={(e) => setCustomEndDate(e.target.value)}
                    className="bg-gray-50 border border-gray-200 text-xs font-bold text-gray-700 px-3 py-1.5 rounded-xl focus:outline-none focus:border-primary transition-all"
                  />
                </div>
                {(customStartDate || customEndDate) && (
                  <button
                    onClick={() => {
                      setCustomStartDate("");
                      setCustomEndDate("");
                    }}
                    className="ml-auto text-[10px] font-black uppercase text-gray-400 hover:text-red-500 transition-colors"
                  >
                    Reset Dates
                  </button>
                )}
              </div>
            )}

            {/* Orders Feed */}
            {filteredOrders.length === 0 ? (
              <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-16 flex flex-col items-center justify-center text-center">
                <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center text-gray-300 mb-4">
                  <FaBox className="text-3xl" />
                </div>
                <h3 className="text-base font-bold text-gray-900 mb-2">No Orders Found</h3>
                <p className="text-xs text-gray-500 font-semibold max-w-xs leading-relaxed">
                  We couldn't find any orders matching the selected status or search filter.
                </p>
              </div>
            ) : (
              <div className="flex flex-col gap-4.5">
                {filteredOrders.map((order, idx) => {
                  const price = order.total_amount ?? order.total_price ?? 0;
                  const date = order.created_at ?? order.order_date ?? null;
                  const status = order.status || "Pending";

                  return (
                    <Link
                      href={`/profile/order/${order.order_id}`}
                      key={order.order_id || idx}
                      className="bg-white p-5 sm:px-6 rounded-2xl border border-gray-250/60 shadow-[0_2px_15px_rgba(0,0,0,0.015)] hover:border-primary/20 hover:shadow-[0_4px_25px_rgba(0,0,0,0.03)] transition-all flex flex-col sm:grid sm:grid-cols-12 sm:gap-4 sm:items-center group w-full"
                    >
                      {/* Left Block (Icon, ID, Date) - col-span-5 */}
                      <div className="sm:col-span-5 flex items-center gap-4 min-w-0 w-full">
                        <div className="w-11 h-11 rounded-xl bg-gray-50 border border-gray-150 flex items-center justify-center text-gray-400 group-hover:text-primary group-hover:bg-primary-light transition-all duration-300 shrink-0">
                          <FaBox size={14} />
                        </div>
                        <div className="flex flex-col gap-0.5 min-w-0 flex-1">
                          <span className="text-xs font-black text-gray-900 uppercase tracking-tight group-hover:text-primary transition-colors whitespace-nowrap truncate">{order.order_id}</span>
                          <div className="text-[10px] font-bold text-gray-455 uppercase tracking-wider whitespace-nowrap truncate">
                            Placed: <span className="text-gray-600 font-extrabold ml-0.5">{formatDate(date)}</span>
                          </div>
                          {/* Coupon badge */}
                          {order.coupon_code && (
                            <span className="text-[9px] font-extrabold text-primary bg-primary-light border border-primary/20 px-1.5 py-0.5 rounded w-fit mt-0.5 uppercase tracking-wider">
                              {order.coupon_code}
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Total Amount - col-span-3 */}
                      <div className="sm:col-span-3 flex sm:flex-col justify-between sm:justify-center items-center sm:items-start select-none">
                        <span className="text-[9px] font-black text-gray-400 uppercase tracking-widest leading-none mb-1">Total Amount</span>
                        <span className="text-[15px] font-black text-gray-900">
                          {formatPrice(price, order.items?.[0]?.currency)}
                        </span>
                        {/* Coins earned */}
                        {(order.coins_earned ?? 0) > 0 && (
                          <span className="text-[9px] font-extrabold text-amber-600 mt-0.5">🪙 +{order.coins_earned} coins</span>
                        )}
                      </div>

                      {/* Status Pill - col-span-3 */}
                      <div className="sm:col-span-3 flex sm:justify-start justify-between items-center w-full gap-2 flex-wrap">
                        <span className="sm:hidden text-[9px] font-black text-gray-400 uppercase tracking-widest">Status</span>
                        <div className={`px-4 py-2 border rounded-full text-xs font-black uppercase tracking-wider flex items-center gap-2 select-none ${getStatusColor(status)}`}>
                          {getStatusIcon(status)}
                          {status}
                        </div>
                        {order.payment_status && (
                          <div className={`px-3 py-1.5 border rounded-full text-[10px] font-black uppercase tracking-wider select-none ${
                            order.payment_status === "Paid"
                              ? "bg-emerald-50/70 text-emerald-800 border-emerald-300"
                              : "bg-amber-50/70 text-amber-800 border-amber-300"
                          }`}>
                            {order.payment_status}
                          </div>
                        )}
                      </div>

                      {/* Chevron Button - col-span-1 */}
                      <div className="sm:col-span-1 flex justify-end">
                        <div className="w-9 h-9 rounded-full bg-gray-50 group-hover:bg-primary group-hover:text-white text-gray-400 transition-all flex items-center justify-center active:scale-90 border border-gray-150 shadow-sm shrink-0">
                          <FaChevronRight className="text-[11px]" />
                        </div>
                      </div>
                    </Link>
                  );
                })}
              </div>
            )}

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