import { useEffect, useState } from "react";
import {
  Alert,
  KeyboardAvoidingView,
  Modal,
  Platform,
  Pressable,
  Text,
  TextInput,
  View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import * as Haptics from "expo-haptics";

interface AddCategoryModalProps {
  visible: boolean;
  initialName?: string;
  isEditing?: boolean;
  onClose: () => void;
  onSubmit: (name: string) => Promise<void>;
}

export function AddCategoryModal({
  visible,
  initialName = "",
  isEditing = false,
  onClose,
  onSubmit,
}: AddCategoryModalProps) {
  const [name, setName] = useState(initialName);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    setName(initialName);
  }, [initialName, visible]);

  async function handleSubmit() {
    if (!name.trim()) {
      Alert.alert("Eksik Bilgi", "Lütfen kategori adını giriniz.");
      return;
    }

    setSubmitting(true);
    try {
      await onSubmit(name.trim());
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      setName("");
      onClose();
    } catch (err) {
      Alert.alert("Hata", err instanceof Error ? err.message : "İşlem başarısız oldu.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Modal
      visible={visible}
      animationType="fade"
      transparent
      onRequestClose={onClose}
    >
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : undefined}
        style={{
          flex: 1,
          backgroundColor: "rgba(0,0,0,0.5)",
          justifyContent: "center",
          padding: 24,
        }}
      >
        <View
          style={{
            backgroundColor: "#FFFFFF",
            borderRadius: 20,
            padding: 20,
            shadowColor: "#000",
            shadowOffset: { width: 0, height: 4 },
            shadowOpacity: 0.15,
            shadowRadius: 12,
            elevation: 5,
          }}
        >
          <View
            style={{
              flexDirection: "row",
              justifyContent: "space-between",
              alignItems: "center",
              marginBottom: 16,
            }}
          >
            <Text style={{ fontSize: 18, fontWeight: "700", color: "#1C1917" }}>
              {isEditing ? "Kategoriyi Yeniden Adlandır" : "Yeni Kategori Ekle"}
            </Text>
            <Pressable onPress={onClose} style={{ padding: 4 }}>
              <Ionicons name="close" size={22} color="#78716C" />
            </Pressable>
          </View>

          <TextInput
            value={name}
            onChangeText={setName}
            placeholder="Örn: Tatlılar, Başlangıçlar, Sıcak İçecekler"
            placeholderTextColor="#57534E"
            autoFocus
            style={{
              backgroundColor: "#FAFAFA",
              borderWidth: 1.5,
              borderColor: "#D6D3D1",
              borderRadius: 12,
              padding: 14,
              fontSize: 15,
              fontWeight: "600",
              color: "#1C1917",
              marginBottom: 18,
            }}
          />

          <View style={{ flexDirection: "row", gap: 10, justifyContent: "flex-end" }}>
            <Pressable
              onPress={onClose}
              style={{
                paddingVertical: 12,
                paddingHorizontal: 16,
                borderRadius: 10,
                backgroundColor: "#F5F5F4",
              }}
            >
              <Text style={{ color: "#78716C", fontWeight: "600", fontSize: 14 }}>Vazgeç</Text>
            </Pressable>

            <Pressable
              onPress={handleSubmit}
              disabled={submitting || !name.trim()}
              style={({ pressed }) => ({
                backgroundColor: !name.trim() ? "#D6D3D1" : "#1C1917",
                paddingVertical: 12,
                paddingHorizontal: 20,
                borderRadius: 10,
                opacity: pressed ? 0.85 : 1,
              })}
            >
              <Text style={{ color: "#FFFFFF", fontWeight: "700", fontSize: 14 }}>
                {submitting ? "Kaydediliyor..." : isEditing ? "Güncelle" : "Ekle"}
              </Text>
            </Pressable>
          </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
