"use client";

import { Form, FormProps, Modal, Spin } from "antd";
import AddressCard from "@/components/pagesComponents/addresses/AddressCard";
import EmptyAddresses from "@/components/sharedComponents/empty/EmptyAddresses";
import { addOrUpdateItemToAddresses, closeAddressModal, getAllAddressesItems } from "@/store/address";
import { AppDispatch, RootState } from "@/store/store";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useTranslations } from "next-intl";
import { GoPlus } from "react-icons/go";
import MapInput from "../addresses/MapInput";
import useWindowWidth from "@/utils/hooks/useWindowWidth";
import AppForm from "@/components/UiComponents/forms/AppForm";
import { ArrowLeftIcon, EditIcon } from "@/assets/svgs/Icons";
import MapImage from '@/assets/images/map-image.png';
import ImageWithFallback from "@/components/UiComponents/ImageWithFallback";
import Cookies from "js-cookie";
import { getCities } from "@/services/GeneralApis";


const SelectAddressesModal = () => {
  const { allAddressesItems, mainLoader , startStep ,openModal,singleItem } = useSelector((state: RootState) => state.AddressConfig);
  const { token} = useSelector((state: RootState) => state.ProfileConfig);
  const location = useSelector((state:RootState)=> state.locationConfig);
  const t = useTranslations();
  const dispatch = useDispatch<AppDispatch>();
  const [current, setCurrent] = useState(startStep);
  const [mapData, setMapData] = useState<any>({});
  const windowWidth = useWindowWidth();
  const [form] = Form.useForm();
  const [cities, setCities] = useState<any>([]);

  
  const fetchCities = async ()=>{
  const {data} = await getCities();
    if(data){
      const customCities = data?.map((item:any)=>({
        value:item?.id,
        label:item?.name
      }))
      setCities(customCities)
    }
  }
  useEffect(()=>{
    fetchCities();
  },[]);
  
  useEffect(()=>{
    if(token){
      dispatch(getAllAddressesItems());
    }
  },[token, dispatch]);

    
  useEffect(() => {
    if (singleItem) {
      const updatedValues = {
        ...singleItem,
        city_id: singleItem?.city?.id,
        is_default: singleItem?.is_default
      };
      form.setFieldsValue(updatedValues);
    } else {
      form.resetFields();
    }
  }, [singleItem, openModal]);
  

  useEffect(()=>{
    setCurrent(startStep)
  },[startStep])

  const next = () => setCurrent(current + 1);

  const prev = () => setCurrent(current - 1);

  const closeModal = ()=> dispatch(closeAddressModal())

  const infoFields = [
    {
      type: "select",
      name: "city_id",
      label: t("form.city"),
      placeholder: t("form.cityPlaceholder"),
      rules: [{ required: true, message: t("validation.cityRequired") }],
      options: cities,
    },
    {
      type: "text",
      name: "address",
      label: t("form.addressTitle"),
      placeholder: t("form.addressTitlePlaceholder"),
      rules: [{ required: true, message: t("validation.addressTitleRequired") }],
      span: 12,
    },
    {
      type: "text",
      name: "property_number",
      label: t("form.propertyNumber"),
      placeholder: t("form.propertyNumberPlaceholder"),
      rules: [{ required: true, message: t("validation.propertyNumberRequired") }],
      span: 12,
    },
    {
      type: "textarea",
      name: "details",
      label: t("form.detailedAddress"),
      placeholder: t("form.detailedAddressPlaceholder"),
    },
    ...(!singleItem?.is_default?[{
      type: "checkbox",
      name: "is_default",
      itemProps : {
        valuePropName:"checked"
      },
      placeholder: t("form.setAsDefault"),
      span: 12,
    }]:[]),
  ];

  const onFinish: FormProps["onFinish"] = async (values:any) => {
    values.lat = mapData.lat;
    values.lng = mapData.lng;
    values.location = mapData.location_description;
    values.is_default = singleItem?.is_default ? 1 : +values.is_default || 0;
    dispatch(addOrUpdateItemToAddresses({id:singleItem?.id, values }));
  };


  const steps = [
    {
      title: t("NAV.addresses"),
      content: (
        <>
        {allAddressesItems?.length === 0 ? (
            <EmptyAddresses className="!h-[400px]"  withOutBtn/>
          ) : (
            <>
                <h2 className=" text-2xl font-bold">{t("LABELS.address")}</h2>
                <div className="space-y-4 h-[400px] overflow-y-auto">
                    {allAddressesItems?.map((item: any) => (
                    <AddressCard key={item.id} item={item} />
                    ))}
                </div>
            </>
        )}
        <div className="flex items-center justify-between">
            <button onClick={next} className="inline-flex items-center gap-2 text-primary text-sm font-semibold">
                <GoPlus className="size-5"/>
                {t("buttons.addAddresses")}
            </button>
            {allAddressesItems?.length > 0 && (
                <div className="flex-center-content gap-2">
                    <button className="app-btn" onClick={closeModal}>
                      {t("buttons.confirm")}
                    </button>
                    <button className="app-btn outline-btn" onClick={closeModal}>
                      {t("buttons.cancel")}
                    </button>
                </div>
            )}
        </div>
        </>
      ),
      width: 668
    },
    {
      title: t("Text.select_position"),
      content: (
        <>
        <MapInput
            defaultMarkerPosition={{
                lat:singleItem?.lat || location?.lat || 30.9585477,
                lng:singleItem?.lng || location?.lng || 31.1613696,
              }}
              onLocationChange={(locationData) => {
              setMapData((prev:any) => ({ 
                  ...prev, 
                  location_description: locationData.address,
                  lat: locationData.lat,
                  lng: locationData.lng
              }))
          }}
        />
        <div className="flex items-center justify-end mt-4">
            <button className="app-btn lg:min-w-[184px]" onClick={next}>
                {t("Text.CONFIRM_LOCATION")}
            </button>
        </div>
        </>
      ),
      width: 998
    },
    {
      title: (
        <div className="flex items-center gap-2  cursor-pointer" onClick={prev}>
          <ArrowLeftIcon className="size-5 rotate-180"/> 
            {t("Text.GO_BACK_TO_MAP")}         
        </div>
      ),
      content: (
        <AppForm
          form={form}
          fields={infoFields} 
          onFinish={onFinish}
          btnClass="justify-end"
          fromBtn="buttons.save_address"
        >
          <div className="address-card">
            <div className="min-w-[120px] inline-flex items-center ">
              <ImageWithFallback 
                src={MapImage} 
                alt='address-image' 
                width={100} 
                height={100} 
                className='size-[100px] object-contain rounded-xl' 
              />
            </div>
            <div className="flex-1 flex flex-col justify-between">
              <p className="text-gray-500 text-xs sm:text-sm font-medium ">{mapData?.location_description}</p>
              <div className="flex  items-start gap-2 mt-5">
                <button type="button" onClick={prev} className="border border-solid border-platinum rounded-md p-1.5"><EditIcon/></button>
              </div>
            </div>
          </div>
        </AppForm>
      ),
      width: 668
    },
  ];


  return (
    <Modal
      title={steps[current].title}
      open={openModal}
      onCancel={closeModal}
      destroyOnHidden
      // loading={mainLoader}
      getContainer={false}
      footer={false}
      width={windowWidth > 1024 ?steps[current].width : "" }
    >
      <Spin spinning={mainLoader}>
        {steps[current].content}
      </Spin>
    </Modal>
  );
};



export default SelectAddressesModal;
