"use client";

import { useRef, useState } from "react";
import AddressLabelPicker from "@/components/AddressLabelPicker";
import StateDistrictPicker from "@/components/StateDistrictPicker";

type AddressFormValues = {
  label?: string | null;
  name?: string;
  phone?: string;
  addressLine1?: string;
  addressLine2?: string | null;
  landmark?: string | null;
  pincode?: string;
  city?: string;
  state?: string | null;
  district?: string | null;
};

export default function AddressForm({
  action,
  defaultValues,
  submitLabel,
  cancelHref,
}: {
  action: (formData: FormData) => void;
  defaultValues?: AddressFormValues;
  submitLabel: string;
  cancelHref?: string;
}) {
  const addressLine1Ref = useRef<HTMLInputElement>(null);
  const landmarkRef = useRef<HTMLInputElement>(null);
  const pincodeRef = useRef<HTMLInputElement>(null);
  const cityRef = useRef<HTMLInputElement>(null);

  const [geoDefaults, setGeoDefaults] = useState({
    state: defaultValues?.state ?? null,
    district: defaultValues?.district ?? null,
  });
  const [pickerKey, setPickerKey] = useState(0);
  const [locating, setLocating] = useState(false);
  const [locationError, setLocationError] = useState<string | null>(null);

  function handleUseMyLocation() {
    setLocationError(null);
    if (!("geolocation" in navigator)) {
      setLocationError("Location isn't supported on this device/browser.");
      return;
    }
    setLocating(true);
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        try {
          const { latitude, longitude } = position.coords;
          const res = await fetch(`/api/geocode/reverse?lat=${latitude}&lon=${longitude}`);
          if (!res.ok) throw new Error("lookup_failed");
          const data = await res.json();

          if (addressLine1Ref.current && data.addressLine1) addressLine1Ref.current.value = data.addressLine1;
          if (cityRef.current && data.city) cityRef.current.value = data.city;
          if (pincodeRef.current && data.pincode) pincodeRef.current.value = data.pincode;
          if (data.state) {
            setGeoDefaults({ state: data.state, district: data.district ?? null });
            setPickerKey((k) => k + 1);
          }
          if (!data.addressLine1 && !data.city && !data.state) {
            setLocationError("Couldn't determine your address. Please fill it in manually.");
          }
        } catch {
          setLocationError("Couldn't detect your address. Please fill it in manually.");
        } finally {
          setLocating(false);
        }
      },
      (err) => {
        setLocating(false);
        setLocationError(
          err.code === err.PERMISSION_DENIED
            ? "Location access was denied. Please fill in your address manually."
            : "Couldn't get your location. Please fill it in manually."
        );
      },
      { enableHighAccuracy: false, timeout: 10000, maximumAge: 300000 }
    );
  }

  return (
    <form action={action} className="grid grid-cols-1 gap-2 sm:grid-cols-2">
      <div className="sm:col-span-2">
        <button
          type="button"
          onClick={handleUseMyLocation}
          disabled={locating}
          className="inline-flex items-center gap-1.5 rounded-md border border-rose-200 bg-rose-50 px-3 py-1.5 text-xs font-medium text-rose-700 hover:bg-rose-100 disabled:opacity-60"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className="h-3.5 w-3.5">
            <path
              fillRule="evenodd"
              d="M9.69 18.933l.003.001C9.89 19.02 10 19 10 19s.11.02.308-.066l.002-.001.006-.003.018-.008a5.741 5.741 0 00.281-.14c.186-.096.446-.24.757-.433.62-.384 1.445-.966 2.274-1.765C15.302 14.988 17 12.493 17 9A7 7 0 103 9c0 3.492 1.698 5.988 3.355 7.584a13.731 13.731 0 002.273 1.765 11.842 11.842 0 00.976.544l.062.029.018.008.006.003zM10 11.25a2.25 2.25 0 100-4.5 2.25 2.25 0 000 4.5z"
              clipRule="evenodd"
            />
          </svg>
          {locating ? "Detecting location…" : "Use my location"}
        </button>
        {locationError && <p className="mt-1 text-xs text-red-600">{locationError}</p>}
      </div>

      <AddressLabelPicker defaultValue={defaultValues?.label} />
      <input
        name="name"
        defaultValue={defaultValues?.name}
        required
        maxLength={100}
        placeholder="Full name"
        className="rounded-md border border-stone-300 px-2 py-1.5 text-sm"
      />
      <input
        name="phone"
        type="tel"
        defaultValue={defaultValues?.phone}
        required
        inputMode="numeric"
        pattern="\d{10}"
        maxLength={10}
        title="Enter a 10-digit mobile number"
        placeholder="Phone"
        className="rounded-md border border-stone-300 px-2 py-1.5 text-sm"
      />
      <input
        ref={addressLine1Ref}
        name="addressLine1"
        defaultValue={defaultValues?.addressLine1}
        required
        maxLength={200}
        placeholder="Address line 1"
        className="rounded-md border border-stone-300 px-2 py-1.5 text-sm sm:col-span-2"
      />
      <input
        name="addressLine2"
        defaultValue={defaultValues?.addressLine2 ?? ""}
        maxLength={200}
        placeholder="Address line 2 (optional)"
        className="rounded-md border border-stone-300 px-2 py-1.5 text-sm sm:col-span-2"
      />
      <input
        ref={landmarkRef}
        name="landmark"
        defaultValue={defaultValues?.landmark ?? ""}
        maxLength={100}
        placeholder="Landmark (optional)"
        className="rounded-md border border-stone-300 px-2 py-1.5 text-sm sm:col-span-2"
      />
      <input
        ref={pincodeRef}
        name="pincode"
        type="text"
        inputMode="numeric"
        pattern="\d{6}"
        maxLength={6}
        title="Enter a 6-digit pincode"
        defaultValue={defaultValues?.pincode}
        required
        placeholder="Pincode"
        className="rounded-md border border-stone-300 px-2 py-1.5 text-sm"
      />
      <input
        ref={cityRef}
        name="city"
        defaultValue={defaultValues?.city}
        required
        maxLength={100}
        placeholder="City"
        className="rounded-md border border-stone-300 px-2 py-1.5 text-sm"
      />
      <StateDistrictPicker key={pickerKey} defaultState={geoDefaults.state} defaultDistrict={geoDefaults.district} />

      <div className="flex gap-2 sm:col-span-2">
        <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
          {submitLabel}
        </button>
        {cancelHref && (
          <a href={cancelHref} className="rounded-md border border-stone-300 px-3 py-1.5 text-xs font-medium text-stone-600 hover:bg-stone-50">
            Cancel
          </a>
        )}
      </div>
    </form>
  );
}
