"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Search } from "lucide-react";
import { addressLookupApi } from "@/lib/api/addressLookup";
import { MESSAGES, isPincode } from "@/lib/validation";
import { formatCity } from "@/lib/utils";

type Destination = { city: string; state: string; label?: string };

/**
 * "Enter your pincode" for the delivery city (B10). Resolves the pincode
 * through the address master and, when transporters cover that city, re-prices
 * the offers to it. An uncovered city is said plainly rather than priced with a
 * zero freight leg that would pass ex-works off as a doorstep price.
 */
export default function PincodeCitySearch({ basePath, destinations }: { basePath: string; destinations: Destination[] }) {
  const router = useRouter();
  const [pincode, setPincode] = useState("");
  const [message, setMessage] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!isPincode(pincode)) {
      setMessage(MESSAGES.pincode);
      return;
    }
    setBusy(true);
    setMessage(null);
    const place = await addressLookupApi.byPincode(pincode);
    setBusy(false);
    if (!place) {
      setMessage("Pincode not found");
      return;
    }
    const match = destinations.find(
      (d) => d.city.trim().toLowerCase() === place.city.trim().toLowerCase()
        && (!d.state || d.state.trim().toLowerCase() === place.state.trim().toLowerCase())
    );
    if (!match) {
      setMessage(`No freight rate to ${formatCity(place.city)} yet — prices shown Ex-Works. Raise an RFQ for a doorstep quote.`);
      return;
    }
    router.push(`${basePath}?city=${encodeURIComponent(match.city)}&state=${encodeURIComponent(match.state)}`);
  }

  return (
    <form onSubmit={onSubmit} noValidate className="flex flex-col items-end gap-1">
      <div className="flex items-center gap-2">
        <input
          value={pincode}
          onChange={(e) => {
            setPincode(e.target.value.replace(/\D/g, "").slice(0, 6));
            setMessage(null);
          }}
          inputMode="numeric"
          placeholder="Delivery pincode"
          aria-label="Delivery pincode"
          className="w-36 rounded-lg border border-gray-200 px-3 py-1.5 text-xs focus:border-[#CC1414] focus:outline-none"
        />
        <button
          type="submit"
          disabled={busy}
          className="inline-flex items-center gap-1 rounded-lg bg-gray-900 px-3 py-1.5 text-xs font-semibold text-white hover:bg-[#CC1414] disabled:opacity-60"
        >
          <Search size={12} aria-hidden /> {busy ? "Checking…" : "Find"}
        </button>
      </div>
      {message && <p role="alert" className="max-w-xs text-right text-[11px] text-[#CC1414]">{message}</p>}
    </form>
  );
}
