"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { whatsappLink } from "@/lib/siteConfig";

export default function TrackOrderPage() {
  const [orderId, setOrderId] = useState("");
  const [checking, setChecking] = useState(false);
  const [error, setError] = useState("");
  const router = useRouter();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const id = orderId.trim();
    if (!id) return;
    setChecking(true);
    setError("");
    try {
      const res = await fetch(`/api/track-order/${encodeURIComponent(id)}`);
      if (res.ok) {
        router.push(`/order/${id}`);
        return;
      }
      setError(`We couldn't find an order with that number. Double-check and try again.`);
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setChecking(false);
    }
  }

  return (
    <div className="mx-auto max-w-md px-4 py-16 sm:px-6">
      <h1 className="font-display text-2xl font-bold text-brand-ink">Track your order</h1>
      <p className="mt-1.5 text-sm text-black/55">
        Enter the order number from your confirmation to see its status.
      </p>

      <form onSubmit={handleSubmit} className="mt-7 flex flex-col gap-3">
        <label htmlFor="order-id" className="text-sm font-medium text-brand-ink">
          Order number
        </label>
        <input
          id="order-id"
          value={orderId}
          onChange={(e) => setOrderId(e.target.value)}
          placeholder="e.g. SG-10004"
          className="rounded-lg border border-black/10 px-3.5 py-2.5 text-sm focus:border-brand-orange focus:outline-none focus:ring-1 focus:ring-brand-orange"
        />
        {error && <p className="text-sm text-danger">{error}</p>}
        <button
          type="submit"
          disabled={checking || !orderId.trim()}
          className="mt-1 rounded-lg bg-brand-ink py-3 text-sm font-semibold text-white transition hover:bg-black disabled:cursor-not-allowed disabled:bg-black/15"
        >
          {checking ? "Checking..." : "Track order"}
        </button>
      </form>

      <p className="mt-8 text-center text-sm text-black/50">
        Can&rsquo;t find your order number?{" "}
        <a
          href={whatsappLink("Hi, I need help finding my order number.")}
          target="_blank"
          rel="noopener noreferrer"
          className="font-medium text-brand-orange-dark hover:underline"
        >
          Chat with us on WhatsApp
        </a>
      </p>
    </div>
  );
}
