import { Button } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { ProBottomSheet } from "../ProBottomSheet/ProBottomSheet";
import { GoogleMap } from "./GoogleMap";
import styles from "./MapBottomSheet.module.css";
import { MapFallback } from "./MapFallback";

interface MapBottomSheetProps {
  isOpen: boolean;
  onClose: () => void;
  initialValue: string;
  onSave: (value: string) => void;
}

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

export function MapBottomSheet({
  isOpen,
  onClose,
  initialValue,
  onSave,
}: MapBottomSheetProps) {
  const { t } = useTranslation();
  const [value, setValue] = useState(initialValue);
  const [selectedLocation, setSelectedLocation] = useState<LocationData | null>(
    null
  );
  const [useMapFallback, setUseMapFallback] = useState(false);

  useEffect(() => {
    setValue(initialValue);
    
    // Try to parse initialValue as JSON to set selectedLocation
    if (initialValue) {
      try {
        const parsed = JSON.parse(initialValue);
        if (parsed.lat && parsed.lng && parsed.address) {
          setSelectedLocation(parsed);
        }
      } catch {
        // If parsing fails, it's just a string value, not a location object
        setSelectedLocation(null);
      }
    }
  }, [initialValue]);

  const handleLocationSelect = (lat: number, lng: number, address: string) => {
    console.log('Location selected:', { lat, lng, address });
    setSelectedLocation({ lat, lng, address });
    setValue(address);
  };

  const handleSave = () => {
    console.log('Save clicked, selectedLocation:', selectedLocation);
    if (selectedLocation) {
      onSave(JSON.stringify(selectedLocation));
    } else {
      onSave(value);
    }
    onClose();
  };

  const handleCancel = () => {
    setValue(initialValue);
    setSelectedLocation(null);
    onClose();
  };

  return (
    <ProBottomSheet
      isOpen={isOpen}
      onClose={handleCancel}
      title={t("cart.selectLocation")}
      showCloseButton={true}
      initialSnap={1}
      height={"100vh"}
      snapPoints={["100vh"]}
    >
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          height: "100%",
          padding: 0, // Override ProBottomSheet padding
          margin: 0, // Remove any margins
        }}
      >
        <div className={styles.mapContainer}>
          <div className={styles.mapWrapper}>
            {useMapFallback ? (
              <MapFallback 
                onLocationSelect={handleLocationSelect} 
                height="100%" 
                initialAddress={selectedLocation?.address || ""}
              />
            ) : (
              <GoogleMap onLocationSelect={handleLocationSelect} height="100%" />
            )}
          </div>  
        </div>

        {!useMapFallback && (
          <div className={styles.fallbackButton}>
            <Button 
              type="link" 
              size="small"
              onClick={() => setUseMapFallback(true)}
            >
              {t("cart.mapFallbackText")}
            </Button>
          </div>
        )}

        <div className={styles.actionButtons}>
          <Button className={styles.actionButton} onClick={handleCancel}>
            {t("cart.cancel")}
          </Button>
          <Button
            type="primary"
            className={styles.actionButton}
            onClick={handleSave}
            disabled={!selectedLocation}
          >
            {t("cart.save")}
          </Button>
        </div>
      </div>
    </ProBottomSheet>
  );
}
