import { Button, Card } from "antd";
import { GoogleMap } from "components/CustomBottomSheet/GoogleMap";
import { MapBottomSheet } from "components/CustomBottomSheet/MapBottomSheet";
import ProText from "components/ProText";
import { selectCart, updateLocation } from "features/order/orderSlice";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAppDispatch, useAppSelector } from "redux/hooks";
import styles from "../../address/address.module.css";

interface LocationData {
  lat: number;
  lng: number;
  address: string;
}

export const AddressSummary = () => {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  const { location } = useAppSelector(selectCart);
  const [isMapBottomSheetOpen, setIsMapBottomSheetOpen] = useState(false);
  const orderType = useMemo(() => localStorage.getItem("orderType"), []); // Default to delivery for now

  const handleLocationSave = useCallback(
    (locationString: string) => {
      try {
        const locationData = JSON.parse(locationString) as LocationData;
        dispatch(updateLocation(locationData));
        console.log("Location saved to Redux store:", locationData);
      } catch (error) {
        console.error("Failed to parse location data:", error);
      }
    },
    [dispatch]
  );

  const handleMapBottomSheetOpen = useCallback(() => {
    setIsMapBottomSheetOpen(true);
  }, []);

  const handleMapBottomSheetClose = useCallback(() => {
    setIsMapBottomSheetOpen(false);
  }, []);

  const initialValue = useMemo(
    () => (location ? JSON.stringify(location) : ""),
    [location]
  );

  const shouldRender = useMemo(() => orderType === "delivery", [orderType]);

  if (!shouldRender) {
    return null;
  }

  return (
    <>
      <Card
        title={t("locationDetails")}
        extra={
          <Button
            type="primary"
            size="small"
            onClick={handleMapBottomSheetOpen}
          >
            {location ? t("changeLocation") : t("selectLocation")}
          </Button>
        }
        className={styles.addressCard}
      >
        {!location ? (
          <div className={styles.noLocationContainer}>
            <ProText type="secondary">{t("noLocationSelected")}</ProText>
            <br />
            <ProText type="secondary" className={styles.smallTextStyle}>
              {t("clickEditToSelect")}
            </ProText>
          </div>
        ) : (
          <div className={styles.mapContainer}>
            <GoogleMap
              readOnly={true}
              initialLocation={location}
              height="160px"
            />
          </div>
        )}
      </Card>

      <MapBottomSheet
        isOpen={isMapBottomSheetOpen}
        onClose={handleMapBottomSheetClose}
        initialValue={initialValue}
        onSave={handleLocationSave}
      />
    </>
  );
};
