import React, { useEffect, useState } from "react";
import { Image, StyleSheet, ImageStyle, StyleProp, Pressable, Modal, View, Text, Dimensions } from "react-native";
import { getProductLocalImage } from "../db/repository";
import { API_BASE_URL } from "../api/config";

const PLACEHOLDER = require("../../assets/product-placeholder.png");

export default function ProductImage({
  productId,
  remoteUrl,
  productName,
  style,
  zoomable = true,
}: {
  productId: string;
  remoteUrl?: string | null;
  productName?: string;
  style?: StyleProp<ImageStyle>;
  zoomable?: boolean;
}) {
  const [uri, setUri] = useState<string | null>(null);
  const [viewerOpen, setViewerOpen] = useState(false);

  useEffect(() => {
    let cancelled = false;
    getProductLocalImage(productId).then((local) => {
      if (!cancelled) setUri(local);
    });
    return () => {
      cancelled = true;
    };
  }, [productId]);

  const source = uri
    ? { uri }
    : remoteUrl
    ? { uri: `${API_BASE_URL}${remoteUrl}` }
    : PLACEHOLDER;

  const image = <Image source={source} style={[styles.image, style]} resizeMode="cover" />;

  if (!zoomable) return image;

  return (
    <>
      <Pressable onPress={() => setViewerOpen(true)}>{image}</Pressable>
      <Modal visible={viewerOpen} transparent animationType="fade" onRequestClose={() => setViewerOpen(false)}>
        <Pressable style={styles.overlay} onPress={() => setViewerOpen(false)}>
          <Image source={source} style={styles.enlarged} resizeMode="contain" />
          {productName ? (
            <View style={styles.captionBar}>
              <Text style={styles.captionText}>{productName}</Text>
            </View>
          ) : null}
          <Text style={styles.hint}>Tap anywhere to close</Text>
        </Pressable>
      </Modal>
    </>
  );
}

const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");

const styles = StyleSheet.create({
  image: { width: 56, height: 56, borderRadius: 8, backgroundColor: "#f0f0f0" },
  overlay: {
    flex: 1,
    backgroundColor: "rgba(0,0,0,0.92)",
    alignItems: "center",
    justifyContent: "center",
  },
  enlarged: { width: SCREEN_WIDTH, height: SCREEN_HEIGHT * 0.75 },
  captionBar: { position: "absolute", bottom: 60, paddingHorizontal: 24 },
  captionText: { color: "#fff", fontSize: 18, fontWeight: "700", textAlign: "center" },
  hint: { position: "absolute", bottom: 24, color: "rgba(255,255,255,0.6)", fontSize: 12 },
});
