"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { apiCall } from "@/utils/callApi";
import {
  FileText, Send, Truck, CheckCircle,
  X, HelpCircle, CreditCard, ShoppingBag
} from "lucide-react";
import StatCard from "./StatCard";
import { useAuthContext } from "@/contexts/AuthProvider";

const getInitials = (name?: string) => {
  if (!name) return "U";

  return name
    .split(" ")
    .map((n) => n[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();
};

export default function DashboardPage() {
  const [orders, setOrders]   = useState<any[]>(  []);
  const [customer, setCustomer] = useState<{ name: string, mobile: string, avatar: string } | null>(null)
  const [loading, setLoading] = useState(false);
  const { user,clienttoken } = useAuthContext();
 

  // console.log("USER IN DASHBOARD:", clienttoken,user);
  const fetchOrders = async () => {
    try {
        setLoading(true)
        await apiCall<any>(`/clientapi/users/orders`, {
            headers: {
                Authorization: `Bearer ${clienttoken}`
            }
        }).then(res => {
            // console.log('Res ^^^^^^', res)
            setOrders(res.data?.data)
        })
       
    } catch(error) {
        console.error('Error fetching', error)
    } finally {
        setLoading(false)
    }
  }
useEffect(() => {
  if (clienttoken) {    
    fetchOrders();

    const raw_customer = localStorage.getItem('customer')
    const customer = raw_customer ? JSON.parse(raw_customer) : null
    setCustomer(customer)
  }
}, [clienttoken]);

  const count = (key: string, val: string) =>
    orders.filter((o: any) => o[key] === val).length;

  const statusStyle = (status: string) => {
    const map: any = {
      delivered:  { bg: "#dcfce7", color: "#16a34a" },
      cancelled:  { bg: "#fee2e2", color: "#dc2626" },
      shipped:    { bg: "#dbeafe", color: "#1d4ed8" },
      processing: { bg: "#fef9c3", color: "#92400e" },
      pending:    { bg: "#f3f4f6", color: "#6b7280" },
    };
    return map[status] ?? { bg: "#f3f4f6", color: "#6b7280" };
  };

  return (
    <>
   {/* Recent Orders Section */}
<div>
    {/* navbar */}
          <div className="pb-4 flex justify-between items-center">
            <h1 className="text-xl sm:text-2xl 2xl:text-3xl font-semibold">Welcome Back 👋</h1>
            <div className="flex items-center gap-4">
              <button className="md:hidden bg-[rgba(var(--secondary),1)] text-white w-8 h-8 rounded-full inline-flex justify-center items-center">
                <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" className="w-6 h-6" viewBox="0 0 16 16">
                  <path d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5m0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5"/>
                </svg>
              </button>
            </div>
          </div>
           <div className="flex gap-3 items-center mb-5">
            <div className="group p-0 border-4 border-white shadow-xl relative rounded-full min-w-16 xl:min-w-20 2xl:min-w-20 h-16 xl:h-20 2xl:h-20 overflow-hidden">
              {customer?.avatar ? (
                <img src={customer?.avatar} alt={customer?.name} className="w-full h-full object-cover" />
              ) : (
                    <div className="bg-primary w-full h-full flex items-center justify-center text-white">
                      {getInitials(customer?.name)}
                    </div>
                  )} 
              <label  className="opacity-0 group-hover:opacity-100 absolute left-0 top-0 right-0 bottom-0 inline-flex justify-center items-center bg-[rgba(var(--primary),0.55)] text-white cursor-pointer transition duration-300">
                <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" className="w-5 h-5" viewBox="0 0 16 16">
                  <path d="M15 12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h1.172a3 3 0 0 0 2.12-.879l.83-.828A1 1 0 0 1 6.827 3h2.344a1 1 0 0 1 .707.293l.828.828A3 3 0 0 0 12.828 5H14a1 1 0 0 1 1 1zM2 4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-1.172a2 2 0 0 1-1.414-.586l-.828-.828A2 2 0 0 0 9.172 2H6.828a2 2 0 0 0-1.414.586l-.828.828A2 2 0 0 1 3.172 4z"/>
                  <path d="M8 11a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5m0 1a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7M3 6.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0"/>
                </svg>
                <input type="file" id="ProfileImage" className="absolute right-0 bottom-0 opacity-0 invisible" name=""/>
              </label>
            </div>
            <div className="flex flex-col min-w-[0px]">
              <h3 className="text-lg xl:text-xl 2xl:text-2xl font-bold truncate sm:mb-1">{customer?.name}</h3>
              <p className="text-base 2xl:text-xl text-gray-500">9942427247</p>
            </div>
          </div>
        <h3 className="text-lg sm:text-xl 2xl:text-2xl font-semibold mb-3">Recent Orders</h3>
        <div className="rounded-lg border overflow-hidden">
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
            <thead>
              <tr style={{ background: "#f8fafc", borderBottom: "1px solid #e2e8f0" }}>
                {["Order ID", "Date", "Items", "Total", "Payment", "Status"].map(h => (
                  <th key={h} style={{ padding: "12px 16px", textAlign: "left", fontWeight: 600, color: "#64748b", fontSize: 12, textTransform: "uppercase" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {orders.length > 0 ? (
                orders.slice(0, 5).map((order: any) => {
                  const ss = statusStyle(order.order_status);
                  return (
                    <tr key={order._id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                      <td style={{ padding: "14px 16px", fontWeight: 500, color: "#6366f1" }}>#{order.order_id}</td>
                      <td style={{ padding: "14px 16px", color: "#64748b" }}>{new Date(order.order_placed_at).toLocaleDateString("en-IN")}</td>
                      <td style={{ padding: "14px 16px" }}>{order.items?.length} item{order.items?.length !== 1 ? "s" : ""}</td>
                      <td style={{ padding: "14px 16px", fontWeight: 600 }}>₹{order.total_amount?.toLocaleString("en-IN")}</td>
                      <td style={{ padding: "14px 16px" }}>
                        <span style={{ 
                          padding: "3px 10px", 
                          borderRadius: 20, 
                          fontSize: 12, 
                          fontWeight: 500, 
                          background: order.payment_status === "paid" ? "#dcfce7" : "#fef9c3", 
                          color: order.payment_status === "paid" ? "#16a34a" : "#92400e" 
                        }}>
                          {order.payment_status}
                        </span>
                      </td>
                      <td style={{ padding: "14px 16px" }}>
                        <span style={{ 
                          padding: "3px 10px", 
                          borderRadius: 20, 
                          fontSize: 12, 
                          fontWeight: 500, 
                          background: ss.bg, 
                          color: ss.color 
                        }}>
                          {order.order_status}
                        </span>
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan={6} style={{ padding: "40px 16px", textAlign: "center" }}>
                  {loading ? "Loading orders..." : "No orders found."}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}