import React, { useState, useEffect, Fragment } from "react";
import { Formik, Field, Form, ErrorMessage } from "formik";
import * as Yup from "yup";
import { useDispatch, useSelector } from "react-redux";
import {
  allAddress,
  address,
  addressUpdate,
  stateLocation,
} from "../../../../api/api";
import { toast, ToastContainer } from "react-toastify";
import { RootState } from "../../../../store";
import Modal from "./modal";
import { Menu, Transition } from "@headlessui/react";

interface AddressFormProps {
  onClose: () => void;
  initialValues: AddressFormValues;
}

interface AddressFormValues {
  id?: number;
  house_number: string;
  city: string;
  postal_code: string;
  province?: string;
  country: string;
  state?: string;
  is_default: boolean;
}

const getValidationSchema = () => {
  return Yup.object({
    house_number: Yup.string().required("Building/Flat is required"),
    city: Yup.string().required("City is required"),
    postal_code: Yup.string()
      .matches(/^[A-Za-z0-9\-]+$/, "Postal Code must be alphanumeric")
      .required("Postal Code is required"),
    country: Yup.string()
      .required("Country is required")
      .oneOf(["USA", "Canada"], "Please select a valid country"),
    is_default: Yup.boolean(),
    state_province: Yup.string().required("State/Province is required"),
  });
};

const AddressForm: React.FC<AddressFormProps> = ({
  onClose,
  initialValues,
}) => {
  const dispatch = useDispatch<any>();
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedCountry, setSelectedCountry] = useState<string>(
    initialValues.country || ""
  );
  // const [showCountryDropdown, setShowCountryDropdown] = useState(false);
  const { stateLocationData, loadings } = useSelector(
    (state: RootState) => state.StateLocationReducer
  );

  useEffect(() => {
    if (selectedCountry === "USA" || selectedCountry === "Canada") {
      const selectedStateValue = selectedCountry === "USA" ? "US" : "CAN";
      dispatch(stateLocation(selectedStateValue));
    }
  }, [selectedCountry, dispatch]);

  const getDefaultValues = () => {
    return {
      id: initialValues?.id || undefined,
      house_number: initialValues?.house_number || "",
      city: initialValues?.city || "",
      postal_code: initialValues?.postal_code || "",
      province: initialValues?.province || "",
      state: initialValues?.state || "",
      country: selectedCountry,
      is_default: initialValues?.is_default || false,
      // Combined field for display purposes
      state_province: initialValues?.state || initialValues?.province || "",
    };
  };

  const handleSubmit = async (values: any) => {
    const payload: AddressFormValues = {
      id: values.id,
      house_number: values.house_number,
      city: values.city,
      postal_code: values.postal_code,
      country: values.country,
      is_default: values.is_default,
      // Set the appropriate field based on country
      ...(stateLocationData?.data?.type === "states"
        ? { state: values.state_province, province: "" }
        : { province: values.state_province, state: "" }),
    };

    try {
      if (values.id) {
        await dispatch(addressUpdate(payload)).unwrap();
        toast.success("Address updated successfully!");
      } else {
        await dispatch(address(payload)).unwrap();
        toast.success("Address added successfully!");
      }

      await dispatch(allAddress());
      onClose();
    } catch (error: any) {
      toast.error(error || "Something went wrong. Please try again later.");
    }
  };

  return (
    <div className="p-6 relative bg-white shadow-md rounded-md ">
      <ToastContainer />
      <div className="flex justify-between items-center mb-2">
        <h2 className="text-2xl text-start font-bold text-[#1E1E1E] ">
          {initialValues.id ? "Edit Address" : "Add Address"}
        </h2>
        <button
          onClick={onClose}
          className=" absolute top-0 right-3 text-black font-normal cursor-pointer hover:text-gray-800 text-4xl p-0"
        >
          &times;
        </button>
      </div>

      <Formik
        initialValues={getDefaultValues()}
        validationSchema={getValidationSchema()}
        onSubmit={handleSubmit}
      >
        {({
          isSubmitting,
          setFieldValue,
          values,
          validateForm,
          setFieldTouched,
        }) => {
          const handleStateChange = (stateName: string) => {
            setFieldValue("state_province", stateName);
            setModalOpen(false);
            setFieldTouched("state_province", false);
            validateForm();
          };

          return (
            <Form className="pt-6 gap-4 flex flex-col">
              <div>
                <label className="block text-lg font-medium mb-1 text-black text-start ">
                  Apt. No. -Street No., Street name
                </label>
                <Field
                  name="house_number"
                  type="text"
                  placeholder="Apt. No. -Street No., Street name"
                  className="w-full p-3 text-lg border border-gray-300 rounded text-black"
                />
                <ErrorMessage
                  name="house_number"
                  component="div"
                  className="text-red-500 text-lg"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                <div>
                  <label className="block text-lg font-medium mb-1 text-black text-start ">
                    City
                  </label>
                  <Field
                    name="city"
                    type="text"
                    placeholder="City"
                    className="w-full p-3 text-lg border border-gray-300 rounded text-black"
                  />
                  <ErrorMessage
                    name="city"
                    component="div"
                    className="text-red-500 text-lg"
                  />
                </div>

                {/* <div>
                  <label className="block text-lg font-medium mb-1 text-start text-black">
                    Country
                  </label>
                  <Field
                    as="select"
                    id="country"
                    name="country"
                    value={selectedCountry}
                    onChange={(e: React.ChangeEvent<HTMLSelectElement>) => {
                      const value = e.target.value;
                      setSelectedCountry(value);
                      setFieldValue("country", value);
                      setFieldValue("state_province", ""); // Reset state/province when country changes
                      setFieldTouched("country", false);
                    }}
                    validateOnChange={true}
                    className={`w-full h-[55px] text-lg border rounded  border-gray-300 focus:ring-blue-500 focus:border-blue-500 block
                       ${
                         selectedCountry === ""
                           ? "text-gray-500 font-normal"
                           : "text-black "
                       }
                       dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500`}
                  >
                    <option value="" className="text-gray-400" disabled>
                      Select a country
                    </option>
                    <option value="USA">USA</option>
                    <option value="Canada">Canada</option>
                  </Field>
                  <ErrorMessage
                    name="country"
                    component="div"
                    className="text-red-500 text-lg"
                  />
                </div> */}
                <div className="relative">
                  <label className="block text-lg font-medium mb-1 text-black text-start">
                    Country
                  </label>

                  <Menu as="div" className="relative">
                    <Menu.Button
                      className={`w-full h-[54px] text-left text-lg border border-gray-300 rounded px-4 flex items-center justify-between bg-white font-normal ${
                        selectedCountry ? "text-black font-medium " : "text-gray-500"
                      }`}
                    >
                      {selectedCountry || "Select a country"}
                      <span className="text-3xl">&#9662;</span>
                    </Menu.Button>

                    <Transition
                      as={Fragment}
                      enter="transition ease-out duration-100"
                      enterFrom="transform opacity-0 scale-95"
                      enterTo="transform opacity-100 scale-100"
                      leave="transition ease-in duration-75"
                      leaveFrom="transform opacity-100 scale-100"
                      leaveTo="transform opacity-0 scale-95"
                    >
                      <Menu.Items className="absolute z-10 mt-1 w-full divide-y bg-white border border-gray-200 rounded-md shadow-lg overflow-hidden">
                        {["USA", "Canada"].map((country) => (
                          <Menu.Item key={country}>
                            {({ active }) => (
                              <div
                                onClick={() => {
                                  setSelectedCountry(country);
                                  setFieldValue("country", country);
                                  setFieldValue("state_province", "");
                                }}
                                className={`px-4 py-2 cursor-pointer text-left ${
                                  active
                                    ? "bg-navy text-white dark:bg-gray-600"
                                    : "text-gray-900 dark:text-white"
                                }`}
                              >
                                {country}
                              </div>
                            )}
                          </Menu.Item>
                        ))}
                      </Menu.Items>
                    </Transition>
                  </Menu>

                  <ErrorMessage
                    name="country"
                    component="div"
                    className="text-red-500 text-lg"
                  />
                </div>
                <div>
                  <label className="block text-lg text-start font-medium text-black ">
                    State/Province
                  </label>
                  <Field
                    name="state_province"
                    type="text"
                    readOnly
                    placeholder="State/Province"
                    onClick={() => selectedCountry && setModalOpen(true)}
                    disabled={!selectedCountry}
                    className={`w-full p-3 border mt-1 text-lg border-gray-300 rounded text-black ${
                      !selectedCountry ? "bg-gray-100 cursor-not-allowed" : ""
                    }`}
                  />
                  <ErrorMessage
                    name="state_province"
                    component="div"
                    className="text-red-500 text-lg"
                  />

                  <Modal
                    isOpen={modalOpen}
                    onClose={() => setModalOpen(false)}
                    title={loadings ? "..." : `Select a State/Province`}
                  >
                    {loadings ? (
                      <p className="text-black">Loading...</p>
                    ) : (
                      <form>
                        <div className="grid grid-cols-2 gap-4 text-black">
                          {stateLocationData?.data?.list.map((state: any) => (
                            <label
                              key={state.code}
                              className="flex items-center gap-4 cursor-pointer"
                            >
                              <input
                                type="radio"
                                name="state_province"
                                className="cursor-pointer"
                                onChange={() => handleStateChange(state.name)}
                                checked={state.name === values.state_province}
                              />
                              <span className="text-black text-start cursor-pointer">
                                {state.name}
                              </span>
                            </label>
                          ))}
                        </div>
                      </form>
                    )}
                    {/* <button
                      onClick={() => setModalOpen(false)}
                      className="mt-4 px-4 py-1 bg-yellow-500 cursor-pointer text-black rounded "
                    >
                      Close Modal
                    </button> */}
                  </Modal>
                </div>

                <div>
                  <label className="block text-lg font-medium mb-1 text-black text-start ">
                    Postal Code
                  </label>
                  <Field
                    name="postal_code"
                    type="text"
                    placeholder="Postal Code"
                    className="w-full p-3 border text-lg border-gray-300 rounded text-black"
                  />
                  <ErrorMessage
                    name="postal_code"
                    component="div"
                    className="text-red-500 text-lg"
                  />
                </div>
              </div>

              <div className="col-span-2 text-start">
                <label className="inline-flex items-center">
                  <Field
                    name="is_default"
                    type="checkbox"
                    className="form-checkbox"
                  />
                  <span className="ml-2 text-lg text-[#1E1E1E] ">
                    Set as default
                  </span>
                </label>
              </div>

              <div className="col-span-2">
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="animation-custom-button"
                >
                  {initialValues.id ? "Update Address" : "Add Address"}
                </button>
              </div>
            </Form>
          );
        }}
      </Formik>
    </div>
  );
};

export default AddressForm;
