import React, { useRef } from "react";
import {
  Image,
  PanResponder,
  View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { type CanvasQrConfig } from "./types";

interface CanvasQrItemProps {
  qrConfig: CanvasQrConfig;
  qrBase64?: string;
  isSelected: boolean;
  onSelect: () => void;
  onUpdatePosition: (x: number, y: number) => void;
  onDragStart?: () => void;
  onDragMove?: (rawX: number, rawY: number, itemWidth: number, itemHeight: number) => { snappedX: number; snappedY: number };
  onDragEnd?: (finalX: number, finalY: number, itemWidth: number, itemHeight: number) => void;
  canvasWidth: number;
  canvasHeight: number;
}

export const CanvasQrItem: React.FC<CanvasQrItemProps> = ({
  qrConfig,
  qrBase64,
  isSelected,
  onSelect,
  onUpdatePosition,
  onDragStart,
  onDragMove,
  onDragEnd,
  canvasWidth,
  canvasHeight,
}) => {
  // Stale closure önlemi için ref'ler
  const qrConfigRef = useRef(qrConfig);
  qrConfigRef.current = qrConfig;

  const canvasWidthRef = useRef(canvasWidth);
  canvasWidthRef.current = canvasWidth;

  const canvasHeightRef = useRef(canvasHeight);
  canvasHeightRef.current = canvasHeight;

  const panStartRef = useRef({ x: qrConfig.x, y: qrConfig.y });
  const currentPosRef = useRef({ x: qrConfig.x, y: qrConfig.y });

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onStartShouldSetPanResponderCapture: () => true,
      onMoveShouldSetPanResponder: (_evt, gestureState) =>
        Math.abs(gestureState.dx) > 1 || Math.abs(gestureState.dy) > 1,
      onMoveShouldSetPanResponderCapture: (_evt, gestureState) =>
        Math.abs(gestureState.dx) > 1 || Math.abs(gestureState.dy) > 1,
      onPanResponderTerminationRequest: () => false,

      onPanResponderGrant: () => {
        onSelect();
        const cur = qrConfigRef.current;
        panStartRef.current = { x: cur.x, y: cur.y };
        currentPosRef.current = { x: cur.x, y: cur.y };
        onDragStart?.();
      },

      onPanResponderMove: (_evt, gestureState) => {
        const cur = qrConfigRef.current;
        const cWidth = canvasWidthRef.current;
        const cHeight = canvasHeightRef.current;

        const maxX = Math.max(0, cWidth - cur.size);
        const maxY = Math.max(0, cHeight - cur.size);

        const rawX = Math.max(0, Math.min(maxX, panStartRef.current.x + gestureState.dx));
        const rawY = Math.max(0, Math.min(maxY, panStartRef.current.y + gestureState.dy));

        if (onDragMove) {
          const { snappedX, snappedY } = onDragMove(rawX, rawY, cur.size, cur.size);
          currentPosRef.current = { x: snappedX, y: snappedY };
          onUpdatePosition(snappedX, snappedY);
        } else {
          const sx = Math.round(rawX);
          const sy = Math.round(rawY);
          currentPosRef.current = { x: sx, y: sy };
          onUpdatePosition(sx, sy);
        }
      },

      onPanResponderRelease: () => {
        const cur = qrConfigRef.current;
        onDragEnd?.(currentPosRef.current.x, currentPosRef.current.y, cur.size, cur.size);
      },

      onPanResponderTerminate: () => {
        const cur = qrConfigRef.current;
        onDragEnd?.(currentPosRef.current.x, currentPosRef.current.y, cur.size, cur.size);
      },
    })
  ).current;

  return (
    <View
      {...panResponder.panHandlers}
      accessible={true}
      accessibilityRole="button"
      accessibilityLabel="QR Kod Alanı"
      accessibilityHint="QR kodunu seçmek, boyutunu ayarlamak veya stant üzerinde taşımak için dokunun"
      accessibilityState={{ selected: isSelected }}
      style={{
        position: "absolute",
        left: qrConfig.x,
        top: qrConfig.y,
        width: qrConfig.size,
        height: qrConfig.size,
        zIndex: isSelected ? 80 : 15,
      }}
    >
      <View
        style={{
          width: "100%",
          height: "100%",
          backgroundColor: qrConfig.bgBoxColor || "#FFFFFF",
          borderRadius: qrConfig.borderRadius,
          borderWidth: isSelected ? 2 : qrConfig.borderWidth,
          borderColor: isSelected ? "#D4AF37" : qrConfig.borderColor,
          borderStyle: isSelected ? "dashed" : "solid",
          padding: qrConfig.padding,
          alignItems: "center",
          justifyContent: "center",
          shadowColor: "#000",
          shadowOffset: { width: 0, height: 4 },
          shadowOpacity: 0.25,
          shadowRadius: 6,
          elevation: 4,
        }}
      >
        {qrBase64 ? (
          <Image
            source={{ uri: `data:image/png;base64,${qrBase64}` }}
            style={{
              width: "100%",
              height: "100%",
              borderRadius: Math.max(0, qrConfig.borderRadius - 4),
            }}
            resizeMode="contain"
          />
        ) : (
          <View style={{ alignItems: "center", justifyContent: "center", width: "100%", height: "100%" }}>
            <Ionicons name="qr-code" size={Math.round(qrConfig.size * 0.7)} color="#0C0C0E" />
          </View>
        )}

        {/* Seçili İken Taşıma Rozeti */}
        {isSelected && (
          <View
            style={{
              position: "absolute",
              top: -8,
              right: -8,
              backgroundColor: "#D4AF37",
              width: 22,
              height: 22,
              borderRadius: 11,
              alignItems: "center",
              justifyContent: "center",
              borderWidth: 1.5,
              borderColor: "#0C0C0E",
            }}
          >
            <Ionicons name="move" size={12} color="#0C0C0E" />
          </View>
        )}
      </View>
    </View>
  );
};
