"use client";
import { useEffect, useState, Suspense, lazy } from "react";
import {
  FormInput,
  FormButton,
  FormMobileNuber,
} from "@/app/components/form/forms";

import MobileNumber from "@/app/components/form/country/MobileNumber";
import { RadioChip } from "@/app/components/chips";
import { GeoLocation } from "@/app/components/locations/geonames";

const ZipCodeLookup = lazy(
  () => import("@/app/components/locations/ZipCodeLookup"),
);

export default function AddAddress({
  onClose,
  editMode = false,
  addressData = null,
}: {
  onClose: () => void;
  editMode?: boolean;
  addressData?: any;
}) {
  const [fullName, setFullName] = useState(addressData?.full_name || "");
  const [mobileCode, setMobileCode] = useState(
    addressData?.mobile_code || "+91",
  );
  const [mobileNumber, setMobileNumber] = useState(addressData?.mobile || "");
  const [addressType, setAddressType] = useState(
    addressData?.delivery_mode || "",
  );
  const [addressLine1, setAddressLine1] = useState(
    addressData?.full_address || "",
  );
  const [locObject, setLocObject] = useState<GeoLocation | null>(() => {
    if (addressData?.loc_object) {
      return {
        ...addressData.loc_object,
        postalCode: addressData.postal_code || "",
        adminName1: addressData.loc_object.adminName1 || "",
        adminName3: addressData.loc_object.adminName3 || "",
        countryCode: addressData.loc_object.countryCode || addressData.loc_object["ISO3166-2"] || "",
      };
    }
    return null;
  });
  const [postalCode, setPostalCode] = useState<string | null>(
    addressData?.postal_code || null,
  );

  useEffect(() => {
    if (addressData) {
      setFullName(addressData.full_name || "");
      setMobileNumber(addressData.mobile || "");
      setMobileCode(addressData.mobile_code || "+91");
      setAddressType(addressData.delivery_mode || "");
      setAddressLine1(addressData.full_address || "");
      if (addressData.loc_object) {
        setLocObject({
          ...addressData.loc_object,
          postalCode: addressData.postal_code || "",
          adminName1: addressData.loc_object.adminName1 || "",
          adminName3: addressData.loc_object.adminName3 || "",
          countryCode: addressData.loc_object.countryCode || addressData.loc_object["ISO3166-2"] || "",
        });
      } else {
        setLocObject(null);
      }
      setPostalCode(addressData.postal_code || null);
    }
  }, [addressData]);

  const handleLocationSelect = (loc: GeoLocation | null) => {
    if (loc) {
      setLocObject(loc);
      setPostalCode(loc.postalCode || null);
    } else {
      setLocObject(null);
      setPostalCode(null);
    }
  };

  const resetForm = () => {
    setFullName("");
    setMobileNumber("");
    setAddressType("");
    setAddressLine1("");
    setLocObject(null);
    setPostalCode(null);
  };

  const handleSubmit = async () => {
    if (!locObject || !postalCode) {
      alert("Please select a location.");
      return;
    }

    const payload = {
      loc_object: {
        lat: locObject.lat,
        lng: locObject.lng,
        ["ISO3166-2"]: locObject["ISO3166-2"],
        placeName: locObject.placeName,
        adminCode1: locObject.adminCode1 || "",
      },
      delivery_mode: addressType,
      postal_code: postalCode,
      full_name: fullName,
      full_address: addressLine1,
      mobile_code: mobileCode,
      mobile: mobileNumber,
    };

    try {
      const endpoint = editMode
        ? `/api/address/update/${addressData?.address_id}`
        : `/api/address/save`;

      const res = await fetch(endpoint, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });

      if (res.ok) {
        console.log(
          editMode
            ? "Address updated successfully!"
            : "Address saved successfully!",
        );
        resetForm();
        onClose();
      } else {
        console.error(await res.text());
        console.log("Failed to save or update address.");
      }
    } catch (error) {
      console.error(error);
      console.log("Error saving or updating address.");
    }
  };

  return (
    <div className="flex flex-col gap-4">
      <div>
        <div className="mt-6 grid grid-cols-1 gap-2">
          <div className="text-sm font-medium">Delivery Mode</div>
          <div className="flex flex-wrap gap-2">
            <RadioChip
              id="address_type_home"
              name="address_type"
              label="Home"
              checked={addressType === "home"}
              onChange={() => setAddressType("home")}
            />
            <RadioChip
              id="address_type_office"
              name="address_type"
              label="Office"
              checked={addressType === "Office"}
              onChange={() => setAddressType("Office")}
            />
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1">
        <Suspense fallback={<p>Loading location finder...</p>}>
          <ZipCodeLookup
            onSelect={handleLocationSelect}
            defaultValue={locObject}
          />
        </Suspense>
      </div>

      <div>
        <FormInput
          type="text"
          id="full_address"
          label="Full Address"
          require={false}
          value={addressLine1}
          onChange={(e: any) => setAddressLine1(e.target.value)}
        />
      </div>

      <div className="grid grid-cols-1 gap-2 gap-x-10 md:grid-cols-2">
        <div>
          <FormInput
            type="text"
            id="full_name"
            label="Full name"
            require={false}
            value={fullName}
            onChange={(e: any) => setFullName(e.target.value)}
          />
        </div>
        <div className="">
          <MobileNumber
            mobileCode={mobileCode}
            setMobileCode={setMobileCode}
            mobileNumber={mobileNumber}
            setMobileNumber={setMobileNumber}
          />
        </div>
      </div>

      <div className="mb-5 flex w-full items-center justify-center align-middle md:w-[50%]">
        <div className="flex w-full">
          <FormButton
            id="btn_save_new_address"
            label="Save Address"
            type="button"
            color="gray"
            hairline="amber"
            onClick={handleSubmit}
            disabled={false}
          />
        </div>
      </div>
    </div>
  );
}
