"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function CustomerLoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      // Check if customer exists in orders
      const response = await fetch("/api/orders");
      if (response.ok) {
        const data = await response.json();
        const orders = data.orders || [];
        const customer = orders.find((order: any) => order.customer.email === email);

        if (customer) {
          // Create a temporary user session for customer
          const customerUser = {
            _id: customer.customer.email,
            name: customer.customer.name,
            email: customer.customer.email,
            role: "customer",
            status: "active",
          };

          localStorage.setItem("user", JSON.stringify(customerUser));
          alert("Logged in successfully as customer!");
          router.push("/account");
        } else {
          alert("Customer not found. Please check your email or place an order first.");
        }
      }
    } catch (error) {
      console.error("Login error:", error);
      alert("Error logging in. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Customer Login</h1>
        <p className="text-gray-600 mt-2">Allow customers to login using their email address</p>
      </div>

      <div className="bg-white rounded-lg shadow p-6 max-w-md">
        <form onSubmit={handleLogin} className="space-y-4">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-1">
              Customer Email *
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              placeholder="Enter customer email"
            />
            <p className="text-xs text-gray-500 mt-1">
              Customer must have placed at least one order to login
            </p>
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? "Logging in..." : "Login as Customer"}
          </button>
        </form>

        <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <h3 className="font-semibold text-blue-900 mb-2">How it works:</h3>
          <ul className="list-disc list-inside space-y-1 text-blue-800 text-sm">
            <li>Enter the customer's email address</li>
            <li>System will check if customer has placed any orders</li>
            <li>If found, customer will be logged in and redirected to their account</li>
            <li>Customer can view their orders and account information</li>
          </ul>
        </div>
      </div>
    </div>
  );
}

