"use client";

import { useState } from "react";
import { checkPincodeServiceability } from "@/lib/actions/delivery-check";

export default function PincodeCheck() {
  const [pincode, setPincode] = useState("");
  const [checking, setChecking] = useState(false);
  const [result, setResult] = useState<{ serviceable: boolean; message: string } | null>(null);

  async function handleCheck() {
    if (!pincode.trim()) return;
    setChecking(true);
    const r = await checkPincodeServiceability(pincode);
    setResult(r);
    setChecking(false);
  }

  return (
    <div className="rounded-lg border border-rose-100 bg-white p-4">
      <div className="flex items-center gap-1.5 text-sm font-semibold text-stone-700">
        <svg xmlns="http://www.w3.org/2000/svg" className="h-4.5 w-4.5 text-rose-700" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" />
          <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z" />
        </svg>
        Delivery
      </div>
      <div className="mt-2 flex gap-2">
        <input
          type="text"
          inputMode="numeric"
          value={pincode}
          onChange={(e) => {
            setPincode(e.target.value.replace(/\D/g, "").slice(0, 6));
            setResult(null);
          }}
          onKeyDown={(e) => e.key === "Enter" && handleCheck()}
          placeholder="Enter pincode"
          className="w-32 rounded-md border border-stone-300 px-3 py-1.5 text-sm"
        />
        <button
          onClick={handleCheck}
          disabled={checking || !pincode.trim()}
          className="rounded-md border border-rose-700 px-3 py-1.5 text-sm font-semibold text-rose-700 hover:bg-rose-50 disabled:cursor-not-allowed disabled:border-stone-300 disabled:text-stone-400"
        >
          {checking ? "Checking…" : "Check"}
        </button>
      </div>
      {result && (
        <p className={`mt-2 text-sm font-medium ${result.serviceable ? "text-emerald-600" : "text-red-600"}`}>
          {result.serviceable ? "✓ " : ""}
          {result.message}
        </p>
      )}
    </div>
  );
}
