import React, { useEffect, useRef, useState } from "react";
import {
  KeyboardAvoidingView,
  Modal,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import * as Haptics from "expo-haptics";
import {
  type CanvasTextLayer,
  CANVAS_FONT_OPTIONS,
  CANVAS_COLOR_PALETTE,
  getCanvasFontFamily,
} from "./types";

interface InstagramTextEditorModalProps {
  visible: boolean;
  layer: CanvasTextLayer | null;
  onSave: (updated: Partial<CanvasTextLayer>) => void;
  onClose: () => void;
  onDelete?: (id: string) => void;
}

export const InstagramTextEditorModal: React.FC<InstagramTextEditorModalProps> = ({
  visible,
  layer,
  onSave,
  onClose,
  onDelete,
}) => {
  const insets = useSafeAreaInsets();
  const inputRef = useRef<TextInput>(null);

  const [text, setText] = useState("");
  const [fontId, setFontId] = useState("sans");
  const [color, setColor] = useState("#FFFFFF");
  const [fontSize, setFontSize] = useState(16);
  const [textAlign, setTextAlign] = useState<"left" | "center" | "right">("center");
  const [bgStyle, setBgStyle] = useState<"none" | "solid" | "soft" | "outline">("none");
  const [bgBoxColor, setBgBoxColor] = useState<string | undefined>(undefined);
  const [curveDegree, setCurveDegree] = useState<number>(0);

  // Modal açıldığında layer verilerini yükle
  useEffect(() => {
    if (layer && visible) {
      setText(layer.text || "");
      setFontId(layer.fontId || "sans");
      setColor(layer.color || "#FFFFFF");
      setFontSize(layer.fontSize || 16);
      setTextAlign(layer.textAlign || "center");
      setCurveDegree(layer.curveDegree || 0);
      if (layer.bgBoxColor) {
        if (layer.bgBoxColor.includes("0.2") || layer.bgBoxColor.includes("0.3")) {
          setBgStyle("soft");
        } else {
          setBgStyle("solid");
        }
        setBgBoxColor(layer.bgBoxColor);
      } else {
        setBgStyle("none");
        setBgBoxColor(undefined);
      }

      // Auto focus text input
      setTimeout(() => {
        inputRef.current?.focus();
      }, 150);
    }
  }, [layer, visible]);

  // Kavis Modunu Değiştir (Düz (0) -> Yukarı Kavis (40) -> Ters Kavis (-40) -> Düz)
  const handleToggleCurveDegree = () => {
    try {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    } catch {}
    setCurveDegree((prev) => {
      if (prev === 0) return 40;
      if (prev === 40) return 60;
      if (prev === 60) return -40;
      return 0;
    });
  };

  // Arka plan pill stilini sırayla değiştir (Instagram "A" butonu mantığı)
  const handleToggleBgStyle = () => {
    try {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    } catch {}

    if (bgStyle === "none") {
      setBgStyle("solid");
      // Solid: seçili rengi kutu yap, metin rengini zıt yap
      if (color === "#FFFFFF" || color === "#F6EFE3") {
        setBgBoxColor("rgba(18, 18, 21, 0.92)");
      } else {
        setBgBoxColor("rgba(212, 175, 55, 0.92)");
      }
    } else if (bgStyle === "solid") {
      setBgStyle("soft");
      setBgBoxColor("rgba(255, 255, 255, 0.22)");
    } else if (bgStyle === "soft") {
      setBgStyle("outline");
      setBgBoxColor(undefined);
    } else {
      setBgStyle("none");
      setBgBoxColor(undefined);
    }
  };

  // Metin Hizalama Değiştir (Sol -> Orta -> Sağ)
  const handleToggleAlign = () => {
    try {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    } catch {}
    setTextAlign((prev) => {
      if (prev === "center") return "left";
      if (prev === "left") return "right";
      return "center";
    });
  };

  // Renk Değiştir
  const handleSelectColor = (selectedColor: string) => {
    try {
      Haptics.selectionAsync();
    } catch {}
    setColor(selectedColor);
    if (bgStyle === "solid") {
      if (selectedColor === "#FFFFFF" || selectedColor === "#F6EFE3") {
        setBgBoxColor("rgba(18, 18, 21, 0.92)");
      } else if (selectedColor === "#121215") {
        setBgBoxColor("rgba(255, 255, 255, 0.92)");
      } else {
        setBgBoxColor(selectedColor);
      }
    }
  };

  // Font Değiştir
  const handleSelectFont = (fId: string) => {
    try {
      Haptics.selectionAsync();
    } catch {}
    setFontId(fId);
  };

  // Bitti / Kaydet
  const handleDone = () => {
    try {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
    } catch {}

    let finalBg = bgBoxColor;
    if (bgStyle === "none" || bgStyle === "outline") {
      finalBg = undefined;
    }

    onSave({
      text: text.trim() ? text : "Metin",
      fontId,
      color,
      fontSize,
      textAlign,
      bgBoxColor: finalBg,
      bgStyle,
      curveDegree,
      hasShadow: bgStyle === "outline" || (!finalBg && color !== "#121215"),
    });
    onClose();
  };

  const fontFamily = getCanvasFontFamily(fontId);

  if (!visible || !layer) return null;

  return (
    <Modal
      visible={visible}
      transparent
      animationType="fade"
      statusBarTranslucent
      onRequestClose={onClose}
    >
      <View style={styles.overlayBackdrop}>
        <KeyboardAvoidingView
          behavior={Platform.OS === "ios" ? "padding" : "height"}
          style={[styles.container, { paddingTop: insets.top + 8, paddingBottom: insets.bottom + 12 }]}
        >
          {/* ÜST BAR - INSTAGRAM STORY KONTROLLERİ */}
          <View style={styles.topBar}>
            {/* Sol: İptal / Kapat */}
            <Pressable
              onPress={onClose}
              hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
              style={styles.iconButton}
            >
              <Ionicons name="close" size={24} color="#FFFFFF" />
            </Pressable>

            {/* Orta Araçlar: Hizalama & Arka Plan Rozeti */}
            <View style={styles.centerTools}>
              {/* Hizalama Butonu */}
              <Pressable
                onPress={handleToggleAlign}
                hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                style={styles.toolPill}
              >
                <Ionicons
                  name={
                    textAlign === "left"
                      ? "reorder-three-outline"
                      : textAlign === "right"
                      ? "reorder-three-outline"
                      : "reorder-two-outline"
                  }
                  size={20}
                  color="#FFFFFF"
                />
              </Pressable>

              {/* Instagram "A" Arka Plan Butonu */}
              <Pressable
                onPress={handleToggleBgStyle}
                hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                style={[
                  styles.toolPill,
                  bgStyle !== "none" && { backgroundColor: "#FFFFFF" },
                ]}
              >
                <Text
                  style={[
                    styles.bgPillText,
                    bgStyle !== "none" && { color: "#0C0C0E", fontWeight: "900" },
                  ]}
                >
                  A
                </Text>
                {bgStyle === "soft" && (
                  <View style={styles.softIndicator} />
                )}
                {bgStyle === "outline" && (
                  <View style={styles.outlineIndicator} />
                )}
              </Pressable>

              {/* Kavis (Yay / Eğri Yazı) Toggle Butonu */}
              <Pressable
                onPress={handleToggleCurveDegree}
                hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                style={[
                  styles.toolPill,
                  curveDegree !== 0 && { backgroundColor: "#D4AF37" },
                ]}
              >
                <Text
                  style={[
                    styles.bgPillText,
                    { fontSize: 14 },
                    curveDegree !== 0 ? { color: "#0C0C0E", fontWeight: "900" } : { color: "#FFFFFF" },
                  ]}
                >
                  {curveDegree > 0 ? "◠" : curveDegree < 0 ? "◡" : "⌒"}
                </Text>
              </Pressable>

              {/* Katmanı Sil (Varsa) */}
              {onDelete && (
                <Pressable
                  onPress={() => {
                    try {
                      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning);
                    } catch {}
                    onDelete(layer.id);
                    onClose();
                  }}
                  hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                  style={[styles.toolPill, { backgroundColor: "rgba(239, 68, 68, 0.2)" }]}
                >
                  <Ionicons name="trash-outline" size={17} color="#EF4444" />
                </Pressable>
              )}
            </View>

            {/* Sağ: BİTTİ (Done) Butonu */}
            <Pressable
              onPress={handleDone}
              hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
              style={styles.doneButton}
            >
              <Text style={styles.doneButtonText}>Bitti</Text>
            </Pressable>
          </View>

          {/* ORTA BÖLÜM: SOL BOYUT SLIDER & CANLI METİN ALANI */}
          <View style={styles.editorBody}>
            {/* Sol: Dikey Boyut Stepper / Gösterge */}
            <View style={styles.sizeControlCol}>
              <Pressable
                onPress={() => {
                  try { Haptics.selectionAsync(); } catch {}
                  setFontSize((s) => Math.min(48, s + 2));
                }}
                hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                style={styles.sizeStepBtn}
              >
                <Ionicons name="add" size={16} color="#FFFFFF" />
              </Pressable>

              <View style={styles.sizeTrack}>
                <View
                  style={[
                    styles.sizeTrackFill,
                    { height: `${Math.min(100, Math.max(10, ((fontSize - 8) / 40) * 100))}%` },
                  ]}
                />
              </View>

              <Pressable
                onPress={() => {
                  try { Haptics.selectionAsync(); } catch {}
                  setFontSize((s) => Math.max(8, s - 2));
                }}
                hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                style={styles.sizeStepBtn}
              >
                <Ionicons name="remove" size={16} color="#FFFFFF" />
              </Pressable>

              <Text style={styles.sizeLabel}>{fontSize}pt</Text>
            </View>

            {/* Orta: Canlı İnstagram Yazı Alanı */}
            <View style={styles.textInputArea}>
              <View
                style={[
                  styles.textPillWrapper,
                  bgStyle === "solid" && {
                    backgroundColor: bgBoxColor || "#D4AF37",
                    borderRadius: 14,
                    paddingHorizontal: 16,
                    paddingVertical: 8,
                  },
                  bgStyle === "soft" && {
                    backgroundColor: "rgba(255, 255, 255, 0.22)",
                    borderRadius: 14,
                    paddingHorizontal: 16,
                    paddingVertical: 8,
                    borderWidth: 1,
                    borderColor: "rgba(255, 255, 255, 0.3)",
                  },
                  bgStyle === "outline" && {
                    borderWidth: 1.5,
                    borderColor: color,
                    borderRadius: 14,
                    paddingHorizontal: 14,
                    paddingVertical: 6,
                  },
                ]}
              >
                <TextInput
                  ref={inputRef}
                  value={text}
                  onChangeText={setText}
                  multiline
                  placeholder="Yazmaya başla..."
                  placeholderTextColor="rgba(255,255,255,0.4)"
                  textAlign={textAlign}
                  autoCapitalize="sentences"
                  style={[
                    styles.textInput,
                    {
                      fontFamily,
                      fontSize,
                      color:
                        bgStyle === "solid" && (bgBoxColor === "#FFFFFF" || bgBoxColor === "#F6EFE3")
                          ? "#0C0C0E"
                          : color,
                      textAlign,
                      letterSpacing: fontId === "serif" ? 1.5 : 0.5,
                      textShadowColor: bgStyle === "outline" ? color : "rgba(0,0,0,0.7)",
                      textShadowOffset: { width: 0, height: 1 },
                      textShadowRadius: bgStyle === "outline" ? 8 : 4,
                    },
                  ]}
                />
              </View>
            </View>
          </View>

          {/* ALT BÖLÜM 0: KAVİS HASSAS AYAR BARI */}
          <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "center", paddingHorizontal: 16, paddingVertical: 4, gap: 10 }}>
            <Text style={{ color: "#A1A1AA", fontSize: 11, fontWeight: "700" }}>KAVİS:</Text>
            <View style={{ flexDirection: "row", alignItems: "center", backgroundColor: "rgba(255,255,255,0.1)", borderRadius: 14, paddingHorizontal: 6, paddingVertical: 3, gap: 8 }}>
              <Pressable
                onPress={() => {
                  try { Haptics.selectionAsync(); } catch {}
                  setCurveDegree((deg) => Math.max(-100, deg - 5));
                }}
                hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                style={{ width: 26, height: 26, borderRadius: 13, backgroundColor: "rgba(255,255,255,0.15)", alignItems: "center", justifyContent: "center" }}
              >
                <Ionicons name="remove" size={15} color="#FFFFFF" />
              </Pressable>

              <Text style={{ color: "#D4AF37", fontSize: 13, fontWeight: "900", minWidth: 36, textAlign: "center" }}>
                {curveDegree}°
              </Text>

              <Pressable
                onPress={() => {
                  try { Haptics.selectionAsync(); } catch {}
                  setCurveDegree((deg) => Math.min(100, deg + 5));
                }}
                hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                style={{ width: 26, height: 26, borderRadius: 13, backgroundColor: "rgba(255,255,255,0.15)", alignItems: "center", justifyContent: "center" }}
              >
                <Ionicons name="add" size={15} color="#FFFFFF" />
              </Pressable>
            </View>

            <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 6 }}>
              {[
                { label: "Düz (0°)", deg: 0 },
                { label: "25° ◠", deg: 25 },
                { label: "45° ◠", deg: 45 },
                { label: "65° ◠", deg: 65 },
                { label: "-35° ◡", deg: -35 },
              ].map((item) => {
                const isActive = curveDegree === item.deg;
                return (
                  <Pressable
                    key={item.deg}
                    onPress={() => {
                      try { Haptics.selectionAsync(); } catch {}
                      setCurveDegree(item.deg);
                    }}
                    style={{
                      paddingHorizontal: 10,
                      paddingVertical: 5,
                      borderRadius: 12,
                      backgroundColor: isActive ? "#D4AF37" : "rgba(255,255,255,0.1)",
                    }}
                  >
                    <Text style={{ color: isActive ? "#0C0C0E" : "#FFFFFF", fontSize: 11, fontWeight: isActive ? "800" : "600" }}>
                      {item.label}
                    </Text>
                  </Pressable>
                );
              })}
            </ScrollView>
          </View>

          {/* ALT BÖLÜM 1: RENK SEÇİCİ BALONCUKLAR */}
          <View style={styles.colorPickerBar}>
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              contentContainerStyle={styles.colorScrollContent}
            >
              {CANVAS_COLOR_PALETTE.map((c) => {
                const isSelected = color === c.color;
                return (
                  <Pressable
                    key={c.id}
                    onPress={() => handleSelectColor(c.color)}
                    style={[
                      styles.colorCircleWrapper,
                      isSelected && { borderColor: "#FFFFFF", transform: [{ scale: 1.15 }] },
                    ]}
                  >
                    <View
                      style={[
                        styles.colorCircle,
                        { backgroundColor: c.color },
                        c.color === "#121215" && { borderWidth: 1, borderColor: "rgba(255,255,255,0.4)" },
                      ]}
                    />
                  </Pressable>
                );
              })}
            </ScrollView>
          </View>

          {/* ALT BÖLÜM 2: INSTAGRAM FONT STİLLERİ CAROUSEL */}
          <View style={styles.fontPickerBar}>
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              contentContainerStyle={styles.fontScrollContent}
            >
              {CANVAS_FONT_OPTIONS.map((f) => {
                const isSelected = fontId === f.id;
                return (
                  <Pressable
                    key={f.id}
                    onPress={() => handleSelectFont(f.id)}
                    style={[
                      styles.fontPill,
                      isSelected && styles.fontPillActive,
                    ]}
                  >
                    <Text
                      style={[
                        styles.fontPillText,
                        { fontFamily: f.fontFamily },
                        isSelected && styles.fontPillTextActive,
                      ]}
                    >
                      {f.label}
                    </Text>
                  </Pressable>
                );
              })}
            </ScrollView>
          </View>
        </KeyboardAvoidingView>
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  overlayBackdrop: {
    flex: 1,
    backgroundColor: "rgba(10, 10, 14, 0.94)",
  },
  container: {
    flex: 1,
    justifyContent: "space-between",
  },
  topBar: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 16,
    height: 52,
    zIndex: 10,
  },
  iconButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: "rgba(255, 255, 255, 0.12)",
    alignItems: "center",
    justifyContent: "center",
  },
  centerTools: {
    flexDirection: "row",
    alignItems: "center",
    gap: 10,
  },
  toolPill: {
    width: 38,
    height: 38,
    borderRadius: 19,
    backgroundColor: "rgba(255, 255, 255, 0.12)",
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
  },
  bgPillText: {
    color: "#FFFFFF",
    fontSize: 16,
    fontWeight: "700",
  },
  softIndicator: {
    position: "absolute",
    bottom: 4,
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: "#60A5FA",
  },
  outlineIndicator: {
    position: "absolute",
    bottom: 4,
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: "#F59E0B",
  },
  doneButton: {
    backgroundColor: "#FFFFFF",
    paddingHorizontal: 18,
    paddingVertical: 8,
    borderRadius: 20,
    alignItems: "center",
    justifyContent: "center",
  },
  doneButtonText: {
    color: "#0C0C0E",
    fontSize: 14,
    fontWeight: "800",
  },
  editorBody: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
  },
  sizeControlCol: {
    width: 36,
    alignItems: "center",
    gap: 8,
  },
  sizeStepBtn: {
    width: 30,
    height: 30,
    borderRadius: 15,
    backgroundColor: "rgba(255, 255, 255, 0.15)",
    alignItems: "center",
    justifyContent: "center",
  },
  sizeTrack: {
    width: 4,
    height: 120,
    backgroundColor: "rgba(255, 255, 255, 0.18)",
    borderRadius: 2,
    justifyContent: "flex-end",
    overflow: "hidden",
  },
  sizeTrackFill: {
    width: "100%",
    backgroundColor: "#D4AF37",
    borderRadius: 2,
  },
  sizeLabel: {
    color: "rgba(255, 255, 255, 0.6)",
    fontSize: 10,
    fontWeight: "700",
  },
  textInputArea: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 12,
  },
  textPillWrapper: {
    maxWidth: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  textInput: {
    minWidth: 140,
    maxWidth: "100%",
    padding: 0,
    margin: 0,
    fontWeight: "800",
  },
  colorPickerBar: {
    paddingVertical: 10,
  },
  colorScrollContent: {
    paddingHorizontal: 20,
    gap: 12,
    alignItems: "center",
  },
  colorCircleWrapper: {
    width: 32,
    height: 32,
    borderRadius: 16,
    borderWidth: 2,
    borderColor: "transparent",
    alignItems: "center",
    justifyContent: "center",
  },
  colorCircle: {
    width: 24,
    height: 24,
    borderRadius: 12,
  },
  fontPickerBar: {
    paddingVertical: 8,
  },
  fontScrollContent: {
    paddingHorizontal: 16,
    gap: 8,
    alignItems: "center",
  },
  fontPill: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 18,
    backgroundColor: "rgba(255, 255, 255, 0.08)",
    borderWidth: 1,
    borderColor: "rgba(255, 255, 255, 0.12)",
  },
  fontPillActive: {
    backgroundColor: "#FFFFFF",
    borderColor: "#FFFFFF",
  },
  fontPillText: {
    color: "rgba(255, 255, 255, 0.8)",
    fontSize: 12,
    fontWeight: "700",
    letterSpacing: 0.5,
  },
  fontPillTextActive: {
    color: "#0C0C0E",
    fontWeight: "900",
  },
});
