/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState, useEffect } from "react";
import SelectField from "../TextField/ReactSelect";
import { getMasterList } from "../../Api/MastersApi";
import {
  createCustomerAddress,
  getCustomerAddresses,
  updateCustomerAddress,
} from "../../Api/CustomerApi";
import Swal from "sweetalert2";
import HourGlassLoader from "../Loader/Loader";
import { validateForm } from "./AddEditAddress/Validation";
import InputFieldCustom from "../TextField/InputFieldCustom";
import PhoneInputFieldAddAddressModal from "../TextField/PhoneInputFieldAddAddressModal";

interface FormData {
  isPrimary: string;
  name: string;
  blockNo: any;
  roadNo: any;
  buildingNo: any;
  flatNo: string;
  latitude: string;
  longitude: string;
  phone: string;
}

interface MasterList {
  id: string;
  name: string;
  code: string | number;
}

interface Option {
  id: string;
  name: string;
}

const AddAddressModal: React.FC<any> = ({ onHide, data, setData }) => {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isPrimaryAvailable, setIsPrimaryAvailable] = useState<boolean>(false);
  const [formData, setFormData] = useState<FormData>({
    isPrimary: !isPrimaryAvailable ? "no" : "yes",
    name: "",
    blockNo: "",
    roadNo: "",
    buildingNo: "",
    flatNo: "",
    latitude: "",
    longitude: "",
    phone: "",
  });
  const [filteredRoads, setFilteredRoads] = useState<MasterList[]>([]);
  const [filteredBuildings, setFilteredBuildings] = useState<MasterList[]>([]);
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [blocks, setBlocks] = useState<MasterList[]>([]);
  const fetchDefaultValuesForEdit = async () => {
    if (data?.id) {
      if (data?.block?.id) {
        try {
          setIsLoading(true);
          const roadRes = await getMasterList("road", {
            block_id: data.block.id,
          });
          setFilteredRoads(roadRes?.data || []);
          let selectedRoad = null;
          let selectedBuilding = null;
          if (data?.road?.id) {
            selectedRoad =
              (roadRes?.data || []).find((r: any) => r.id === data.road.id) ||
              data.road.id;
            const buildingRes = await getMasterList("building", {
              block_id: data.block.id,
              road_id: data.road.id,
            });
            setFilteredBuildings(buildingRes?.data || []);
            if (data?.building?.id) {
              selectedBuilding =
                (buildingRes?.data || []).find(
                  (b: any) => b.id === data.building.id
                ) || data.building.id;
            }
          } else {
            setFilteredBuildings([]);
          }
          setFormData({
            isPrimary: data?.isPrimary ? "yes" : "no",
            name: data?.addressTitle || "",
            blockNo: data?.block?.id || "",
            roadNo: selectedRoad?.id || (data?.road?.id ?? null),
            buildingNo: selectedBuilding?.id || (data?.building?.id ?? null),
            flatNo: data?.addressLineOne || "",
            latitude: data?.latitude || "",
            longitude: data?.longitude || "",
            phone: data?.phone || "",
          });
        } catch {
          setFilteredRoads([]);
          setFilteredBuildings([]);
          setFormData({
            isPrimary: data?.isPrimary ? "yes" : "no",
            name: data?.addressTitle || "",
            blockNo: data?.block?.id || "",
            roadNo: data?.road?.id || "",
            buildingNo: data?.building?.id || "",
            flatNo: data?.addressLineOne || "",
            latitude: data?.latitude || "",
            longitude: data?.longitude || "",
            phone: data?.phone || "",
          });
        } finally {
          setIsLoading(false);
        }
      } else {
        setFilteredRoads([]);
        setFilteredBuildings([]);
        setFormData({
          isPrimary: data?.isPrimary ? "yes" : "no",
          name: data?.addressTitle || "",
          blockNo: data?.block?.id || "",
          roadNo: data?.road?.id || "",
          buildingNo: data?.building?.id || "",
          flatNo: data?.addressLineOne || "",
          latitude: data?.latitude || "",
          longitude: data?.longitude || "",
          phone: data?.phone || "",
        });
      }
    }
  };
  useEffect(() => {
    const fetchMasterLists = async () => {
      try {
        setIsLoading(true);
        const [, block] = await Promise.all([
          getMasterList("road"),
          getMasterList("block"),
          getMasterList("building"),
        ]);
        setBlocks(block?.data || []);
        setFilteredRoads([]);
        setFilteredBuildings([]);
        if (data?.id) await fetchDefaultValuesForEdit();
        else {
          const primaryAddress: any = await getCustomerAddresses({
            is_primary: true,
          });
          if (primaryAddress?.data?.length > 0) setIsPrimaryAvailable(true);
          else setIsPrimaryAvailable(false);
          setFormData({
            ...formData,
            isPrimary: !isPrimaryAvailable ? "no" : "yes",
          });
        }
      } catch (err) {
        console.error("Error loading masterlists", err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchMasterLists();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Fetch roads when block changes
  useEffect(() => {
    const fetchRoads = async () => {
      if (formData.blockNo) {
        setIsLoading(true);
        try {
          const response = await getMasterList("road", {
            block_id: formData.blockNo,
          });
          setFilteredRoads(response?.data || []);
        } catch {
          setFilteredRoads([]);
        } finally {
          setIsLoading(false);
        }
      } else {
        setFilteredRoads([]);
      }
      // Only clear roadNo/buildingNo if blockNo actually changed
      setFormData((prev) => {
        if (prev.roadNo || prev.buildingNo) {
          return {
            ...prev,
            roadNo: data?.road?.id ?? "",
            buildingNo: data?.building?.id ?? "",
          };
        }
        return prev;
      });
      setFilteredBuildings([]);
    };
    fetchRoads();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formData.blockNo]);

  // Fetch buildings when road or block changes
  useEffect(() => {
    const fetchBuildings = async () => {
      if (formData.blockNo && formData.roadNo) {
        setIsLoading(true);
        try {
          const response = await getMasterList("building", {
            block_id: formData.blockNo,
            road_id: formData.roadNo,
          });
          setFilteredBuildings(response?.data || []);
        } catch {
          setFilteredBuildings([]);
        } finally {
          setIsLoading(false);
        }
      } else {
        setFilteredBuildings([]);
      }
      // Only clear buildingNo if roadNo actually changed
      setFormData((prev) => {
        if (prev.buildingNo) {
          return { ...prev, buildingNo: data?.building?.id ?? "" };
        }
        return prev;
      });
    };
    fetchBuildings();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formData.roadNo, formData.blockNo]);

  const handleChange =
    (field: keyof FormData) =>
    (e: React.ChangeEvent<HTMLInputElement> | { value: string }) => {
      const value =
        (e as React.ChangeEvent<HTMLInputElement>).target?.value ??
        (e as { value: string }).value ??
        "";
      setFormData((prev) => {
        const newFormData = { ...prev, [field]: value };
        // Validate the specific field that changed
        const validationErrors = validateForm(newFormData);
        setErrors(validationErrors);
        return newFormData;
      });
    };

  const handleSelectChange =
    (field: keyof FormData) => (selectedOption: Option | null) => {
      const newValue = selectedOption
        ? { id: selectedOption.id, name: selectedOption.name }
        : null;
      setFormData((prev) => {
        const newFormData =
          field === "blockNo"
            ? {
                ...prev,
                [field]: newValue ? newValue.id : "",
                roadNo: "",
                buildingNo: "",
              }
            : {
                ...prev,
                [field]: newValue ? newValue.id : "",
              };
        if (field === "blockNo") {
          setData({ ...data, road: "", building: "" });
        }
        // Validate the specific field that changed
        const validationErrors = validateForm(newFormData);
        setErrors(validationErrors);
        return newFormData;
      });
    };
  const handlePrimaryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setFormData((prev) => ({
      ...prev,
      isPrimary: e.target.value,
    }));
  };
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const validationErrors = validateForm(formData);
    setErrors(validationErrors);
    if (Object.keys(validationErrors).length > 0) {
      // Swal.fire({
      //   icon: "error",
      //   title: "Form Error",
      //   text: "Please fix the errors before submitting.",
      //   confirmButtonText: "OK",
      // });
      return;
    }
    const payload = {
      ...formData,
      phone: formData.phone.startsWith('+') ? formData.phone : `+${formData.phone}`,
      address_title: formData?.name,
      address_line_one: formData?.flatNo,
      address_line_two: "",
      block_id: formData?.blockNo,
      road_id:
        filteredRoads.find((road) => road.id === formData.roadNo)?.code ||
        formData?.roadNo,
      building_id:
        filteredBuildings.find(
          (building) => building.id === formData.buildingNo
        )?.code || formData.buildingNo,
      is_primary: formData.isPrimary === "yes" ? true : false, // Convert "yes"/"no" to boolean
    };

    try {
      let response: any = {};
      if (data?.id) response = await updateCustomerAddress(data?.id, payload);
      else response = await createCustomerAddress(payload);
      if (response?.status) onHide();
      else {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: response.message || "Something went wrong. Please try again.",
          confirmButtonText: "OK",
          customClass: {
            confirmButton: "delybell-primary px-4",
            cancelButton: "delybell-dark",
          },
        });
      }
    } catch (error) {
      console.error("Failed to create address", error);
      onHide();
    }
  };
  return (
    <>
      <style>
        {`
          @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
            .modal-dialog {
              display: flex;
              align-items: center;
              min-height: calc(100% - var(--bs-modal-margin) * 2);
              position: relative;
              margin: var(--bs-modal-margin);
              width: 960px;
              max-width: 960px;
              margin-right: auto;
              margin-left: auto;
            }
            .bottom-sheet-modal .modal-content {
              border-radius: 1.5rem;
            }
          }
          .react-select__control, .css-2ubb82-control { 
            border-radius: 10px; 
            position: unset;
          }
          .css-b62m3t-container { position: unset; }
          .input-style input, .input-style select, .input-style textarea {
            border-top-width: 1px;
            border-right-width: 1px;
            border-left-width: 1px;            
            border-radius: 10px;            
          }
          .modal-body { padding: 0px; }
          .input-style.mb-0 {
            margin-bottom: 0!important;
          }
        `}
      </style>
      {isLoading && <HourGlassLoader />}
      <div
        id="add-address"
        data-menu-effect="menu-over"
        // style={{ maxHeight: 555 }}
      >
        <form onSubmit={handleSubmit}>
          <div className="menu-title">
            <h1 className="font-24">{data?.id ? "Edit" : "Add New"} Address</h1>
          </div>

          <div className="content mb-0 mt-0">
            <div className="row mb-0 add-address-box">
              <div className="col-lg-4">
                <div className="input-outer-box mb-3">
                  <div className="input-style input-style-always-active has-borders has-icon validate-field mb-0">
                    <i
                      className="ri ri-id-card-line color-blue-dark"
                      aria-hidden="true"
                    ></i>
                    <label className="color-red2">
                      This address has to be primary
                    </label>
                    <select
                      value={formData.isPrimary}
                      onChange={handlePrimaryChange}
                    >
                      {/* <option value="">- Select -</option> */}
                      <option
                        value="yes"
                        disabled={isPrimaryAvailable ? true : false}
                      >
                        Yes
                      </option>
                      <option value="no">No</option>
                    </select>
                  </div>
                </div>
              </div>
              <InputFieldCustom
                icon="ri-user-3-line"
                label="Name"
                placeholder="Enter the name"
                value={formData.name}
                onChange={handleChange("name")}
                name="name"
                errors={errors}
                page="my-profile"
              />
              <SelectField
                options={blocks.map((block: MasterList) => ({
                  id: block.id,
                  name: block.name,
                  code: block?.code,
                }))}
                title="Block"
                value={
                  blocks.find((block) => block.id === formData.blockNo) || null
                }
                onChange={handleSelectChange("blockNo")}
                placeholder="Select Block"
                isCreatable={false}
                width="100%"
                errors={errors.blockNo}
                usageType={1}
                icon={"ri ri-layout-grid-line"}
                page="my-profile"
                label="block no."
                name="blockNo"
              />
              {/* {errors?.blockNo && (
                <div className="text-danger px-2 error-box select-error  mb-3">
                  {errors?.blockNo}
                </div>
              )} */}
              <SelectField
                options={filteredRoads.map((road) => ({
                  id: road.id,
                  name: road.name,
                  code: road?.code,
                }))}
                value={
                  data?.road
                    ? data?.road
                    : filteredRoads.find(
                        (road) => road.id === formData.roadNo
                      ) || null
                }
                onChange={handleSelectChange("roadNo")}
                placeholder="Select Road"
                stringAdd={true}
                width="100%"
                errors={errors.roadNo}
                usageType={1}
                icon={"ri ri-road-map-line"}
                title="Road"
                page="my-profile"
                label="road no."
                name="roadNo"
              />
              {/* {errors?.roadNo && (
                <div className="text-danger px-2 error-box select-error">
                  {errors?.roadNo}
                </div>
              )} */}
              <SelectField
                options={filteredBuildings.map((building) => ({
                  id: building.id,
                  name: building.name,
                  code: building?.code,
                }))}
                value={
                  data?.building
                    ? data?.building
                    : filteredBuildings.find(
                        (building) => building.id === formData.buildingNo
                      ) || null
                }
                onChange={handleSelectChange("buildingNo")}
                placeholder="Select Building"
                stringAdd={true}
                width="100%"
                errors={errors.buildingNo}
                usageType={1}
                icon={"ri ri-building-line"}
                title="Building"
                page="my-profile"
                label="building no."
                name="buildingNo"
              />
              {/* {errors?.blockNo && (
                <div className="text-danger col-lg-4 px-2 error-box select-error">
                  {errors?.blockNo}
                </div>
              )} */}
              <InputFieldCustom
                icon="ri ri-home-4-line"
                label="Flat/Office No:"
                placeholder="Enter the Flat/Office no:"
                value={formData.flatNo}
                onChange={handleChange("flatNo")}
                name="flatNo"
                errors={errors}
                page="my-profile"
              />
            {/* <div className="row mb-0">
               */}
              <div className="col-lg-4">
              <PhoneInputFieldAddAddressModal
                fieldName="phone"
                value={formData.phone}
                onChange={(val) => {
                  setFormData((prev) => {
                    const updated = { ...prev, phone: val };
                    const validationErrors = validateForm(updated);
                    setErrors(validationErrors);
                    return updated;
                  });
                }}
                placeholder="Enter phone number"
                error={errors.phone}
              />
            </div>
            {/* 
            <div className="col-lg-4"> */}
              <InputFieldCustom
                icon="ri-map-pin-2-line"
                label="Latitude"
                placeholder="Enter the Latitude"
                value={formData.latitude}
                onChange={handleChange("latitude")}
                type="number"
                step="any"
                name="latitude"
                errors={errors}
                page="my-profile"
              />
            {/* </div>
            <div className="col-lg-4"> */}
              <InputFieldCustom
                icon="ri-map-pin-2-line"
                label="Longitude"
                placeholder="Enter the Longitude"
                value={formData.longitude}
                onChange={handleChange("longitude")}
                type="number"
                name="longitude"
                errors={errors}
                page="my-profile"
              />
            {/* </div>
            </div> */}
            </div>

            <div className="col-12">
              <button
                type="submit"
                className="btn btn-full w-100 btn-l font-600 font-13 bg-blue-dark mt-0 mb-4 rounded-s"
              >
                Submit
              </button>
            </div>
          </div>
        </form>
      </div>
    </>
  );
};

export default AddAddressModal;
