"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Navbar from "@/components/Navbar";
import WhatsAppButton from "@/components/WhatsAppButton";
import Link from "next/link";

type Order = {
  _id: string;
  customer?: {
    name?: string;
    email?: string;
    phone?: string;
    address?: string;
  };
  items?: Array<{
    productId?: string;
    name?: string;
    price?: number;
    quantity?: number;
  }>;
  total?: number;
  status?: string;
  createdAt?: string;
};

export default function OrdersPage() {
  const router = useRouter();
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState<any>(null);

  useEffect(() => {
    const userData = localStorage.getItem("user");
    if (!userData) {
      router.push("/login");
      return;
    }
    setUser(JSON.parse(userData));
    fetchOrders();
  }, [router]);

  const fetchOrders = async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/orders");
      if (response.ok) {
        const data = await response.json();
        // Filter orders for current user if not admin
        const userData = localStorage.getItem("user");
        if (userData) {
          const userObj = JSON.parse(userData);
          if (userObj.role !== "admin") {
            setOrders(data.orders?.filter((o: Order) => o.customer?.email === userObj.email) || []);
          } else {
            setOrders(data.orders || []);
          }
        }
      }
    } catch (error) {
      console.error("Error fetching orders:", error);
    } finally {
      setLoading(false);
    }
  };

  const updateOrderStatus = async (orderId: string, status: string) => {
    try {
      const response = await fetch(`/api/orders/${orderId}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ status }),
      });

      if (response.ok) {
        alert("Order status updated successfully");
        fetchOrders();
      } else {
        alert("Failed to update order status");
      }
    } catch (error) {
      console.error("Error updating order status:", error);
      alert("Error updating order status");
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Navbar />
        <div className="container mx-auto px-4 py-12">
          <p className="text-center">Loading orders...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-6">My Orders</h1>

        {orders.length === 0 ? (
          <div className="bg-white rounded-lg shadow p-12 text-center">
            <p className="text-gray-600 mb-4">No orders found</p>
            <Link
              href="/shop"
              className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition inline-block"
            >
              Start Shopping
            </Link>
          </div>
        ) : (
          <div className="space-y-6">
            {orders.map((order) => (
              <div key={order._id} className="bg-white rounded-lg shadow p-6">
                <div className="flex justify-between items-start mb-4">
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900">
                      Order #{order._id?.slice(-8) || "N/A"}
                    </h3>
                    <p className="text-sm text-gray-600">
                      {order.createdAt ? new Date(order.createdAt).toLocaleDateString() : "N/A"}
                    </p>
                  </div>
                  <div className="flex items-center gap-4">
                    <span
                      className={`px-3 py-1 rounded-full text-sm font-semibold ${
                        order.status === "completed"
                          ? "bg-green-100 text-green-800"
                          : order.status === "processing"
                          ? "bg-blue-100 text-blue-800"
                          : order.status === "cancelled"
                          ? "bg-red-100 text-red-800"
                          : "bg-yellow-100 text-yellow-800"
                      }`}
                    >
                      {order.status || "pending"}
                    </span>
                    {user?.role === "admin" && (
                      <select
                        value={order.status || "pending"}
                        onChange={(e) => updateOrderStatus(order._id, e.target.value)}
                        className="px-3 py-1 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                      >
                        <option value="pending">Pending</option>
                        <option value="processing">Processing</option>
                        <option value="completed">Completed</option>
                        <option value="cancelled">Cancelled</option>
                      </select>
                    )}
                  </div>
                </div>

                {order.customer && (
                  <div className="mb-4">
                    <h4 className="font-semibold text-gray-700 mb-2">Customer:</h4>
                    <p className="text-sm text-gray-600">{order.customer.name || "N/A"}</p>
                    <p className="text-sm text-gray-600">{order.customer.email || "N/A"}</p>
                    <p className="text-sm text-gray-600">{order.customer.phone || "N/A"}</p>
                  </div>
                )}

                <div className="mb-4">
                  <h4 className="font-semibold text-gray-700 mb-2">Items:</h4>
                  <ul className="space-y-2">
                    {order.items?.map((item, index) => {
                      const price = item.price || 0;
                      const quantity = item.quantity || 0;
                      return (
                        <li key={index} className="flex justify-between text-sm">
                          <span>
                            {item.name || "Unknown Item"} x {quantity}
                          </span>
                          <span>${(price * quantity).toFixed(2)}</span>
                        </li>
                      );
                    })}
                  </ul>
                </div>

                <div className="flex justify-between items-center pt-4 border-t">
                  <span className="text-lg font-bold text-gray-900">
                    Total: ${(order.total || 0).toFixed(2)}
                  </span>
                  <div className="flex gap-2">
                    <a
                      href={`/api/orders/${order._id}/export.pdf`}
                      target="_blank"
                      className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-semibold rounded-lg transition"
                    >
                      📄 PDF
                    </a>
                    <a
                      href={`/api/orders/${order._id}/export.xlsx`}
                      download
                      className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded-lg transition"
                    >
                      📊 Excel
                    </a>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      <WhatsAppButton />
    </div>
  );
}

