import React, { useState, useRef, useEffect } from "react";
import {
  View,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  Image,
  ScrollView,
  FlatList,
  KeyboardAvoidingView,
  Platform,
} from "react-native";
import { router } from "expo-router";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import { FLEX, COLOR_SCALES } from "@/theme";
import { title, paragraph } from "@/theme/typography";
import Text from "@/components/common/Text";
import Loading from "@/components/common/Loading";
import { OPENAI_API_KEY } from "@/constants/api";
import { getProfile, checkUserPackage } from "@/services/user";
import useAuth from "@/hooks/useAuth";
import { useUserProfile } from "@/hooks/useUserProfile";

// ✅ API key centralized in constants

export default function LokmaChatScreen() {
  const insets = useSafeAreaInsets();
  const { user: authUser } = useAuth();
  const { userData: profileData, getAvatarSource } = useUserProfile();
  const [inputText, setInputText] = useState("");
  const [isChatStarted, setIsChatStarted] = useState(false);
  const [messages, setMessages] = useState([]);
  const scrollViewRef = useRef();
  const [isLoading, setIsLoading] = useState(false);
  const [userName, setUserName] = useState("Kullanıcı");
  const [hasPackage, setHasPackage] = useState(false);
  const [inputHeight, setInputHeight] = useState(72);

  useEffect(() => {
    let isMounted = true;
    const load = async () => {
      try {
        // Kullanıcı adını belirle
        let displayName = "Kullanıcı";
        
        // Önce profileData'dan al
        if (profileData) {
          const candidate = profileData?.name
            ?? profileData?.fullName
            ?? profileData?.username
            ?? `${profileData?.firstName ?? ''} ${profileData?.lastName ?? ''}`.trim();
          if (candidate && candidate.length > 0) {
            displayName = candidate;
          }
        }
        // Yoksa authUser'dan al
        else if (authUser) {
          const fromAuth = authUser?.name
            ?? authUser?.fullName
            ?? authUser?.username
            ?? `${authUser?.firstName ?? ''} ${authUser?.lastName ?? ''}`.trim();
          if (fromAuth && fromAuth.length > 0) {
            displayName = fromAuth;
          }
        }
        
        if (isMounted) {
          setUserName(displayName);
        }

        // Paket kontrolü
        const packageRes = await checkUserPackage();
        if (isMounted) {
          const raw = packageRes;
          const d = raw?.data ?? raw;
          let owned = false;
          if (d && typeof d === 'object' && Object.prototype.hasOwnProperty.call(d, 'hasPackage')) {
            owned = Boolean(d.hasPackage);
          } else if (typeof d === 'boolean') {
            owned = d;
          } else if (Array.isArray(d)) {
            owned = d.length > 0;
          } else if (d && typeof d === 'object') {
            owned = Object.values(d)?.some?.((v) => v === true || v === 1) ?? false;
          }
          setHasPackage(Boolean(owned));
        }
      } catch (_) {
        if (isMounted) setHasPackage(false);
      }
    };
    load();
    return () => { isMounted = false; };
  }, [authUser, profileData]);

  const handleBackPress = () => {
    router.back();
  };

  // 🔥 Lokma’dan cevap al
  const getLokmaResponse = async (userMessage) => {
    if (!hasPackage) return;
    if (!OPENAI_API_KEY) {
      const errorResponse = {
        id: Date.now() + 2,
        type: "lokma",
        text: "API anahtarı bulunamadı. Lütfen yapılandırmayı kontrol edin.",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, errorResponse]);
      return;
    }
    if (isLoading) return;

    try {
      setIsLoading(true);
      const response = await fetch("https://api.openai.com/v1/chat/completions", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          Authorization: `Bearer ${OPENAI_API_KEY}`,
        },
        body: JSON.stringify({
          model: "gpt-4o-mini",
          messages: [
            { role: "system", content: "Sen Lokma adında sevimli bir yardımcı botsun. Gıda israfı, saklama yöntemleri, alışveriş ipuçları ve eğitimlerde kullanıcılara eğlenceli ve samimi bir dille yardımcı ol." },
            { role: "user", content: userMessage },
          ],
          max_tokens: 250,
        }),
      });

      if (!response.ok) {
        let errJson = null;
        try { errJson = await response.json(); } catch (_) {}
        const message = errJson?.error?.message ?? `API hata durum kodu: ${response.status}`;
        throw new Error(message);
      }

      const data = await response.json();
      const reply = data?.choices?.[0]?.message?.content ?? "Üzgünüm, şu an cevap veremiyorum 😔";

      const lokmaResponse = {
        id: Date.now() + 1,
        type: "lokma",
        text: reply,
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };

      setMessages((prev) => [...prev, lokmaResponse]);
    } catch (error) {
      console.error("OpenAI API Error:", error);
      const errorResponse = {
        id: Date.now() + 2,
        type: "lokma",
        text: error?.message ?? "Bir hata oluştu, lütfen tekrar deneyin ⚠️",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, errorResponse]);
    } finally {
      setIsLoading(false);
    }
  };
  // Paket yoksa chat başlatılamaz; aktif sohbeti kapat
  useEffect(() => {
    if (!hasPackage) {
      setIsChatStarted(false);
    }
  }, [hasPackage]);

  const handleSendMessage = () => {
    if (!hasPackage) {
      router.push('/(tabs)/packages');
      return;
    }
    if (inputText.trim()) {
      const newMessage = {
        id: Date.now(),
        type: "user",
        text: inputText.trim(),
        userName: userName ?? "Kullanıcı",
        userAvatar: getAvatarSource(),
      };

      setMessages((prev) => [...prev, newMessage]);
      setInputText("");

      if (!isChatStarted) setIsChatStarted(true);

      // AI cevabı al
      getLokmaResponse(newMessage.text);
    }
  };

  const handleQuickButtonPress = (buttonText) => {
    if (!hasPackage) {
      router.push('/(tabs)/packages');
      return;
    }
    const userMessage = {
      id: Date.now(),
      type: "user",
      text: buttonText,
      userName: userName ?? "Kullanıcı",
      userAvatar: getAvatarSource(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setIsChatStarted(true);

    // AI cevabı al
    getLokmaResponse(buttonText);
  };

  const quickButtons = [
    "Gıda İsrafı Eğitimi",
    "Gıda Saklama Eğitimi",
    "Gıda İsrafı ve Bilinç Eğitimi",
    "Soru Cevap",
    "Gıda Alışverişi Eğitimi",
    "Günlük egzersizler",
  ];

  const renderMessage = ({ item }) => {
    if (item.type === "user") {
      return (
        <View style={styles.userMessageContainer}>
          <View style={styles.userMessageHeader}>
            <Image source={item.userAvatar} style={styles.userAvatar} />
            <Text style={styles.userName}>{item.userName}</Text>
          </View>
          <View style={styles.userBubble}>
            <Text style={styles.userText}>{item.text}</Text>
          </View>
        </View>
      );
    }

    if (item.type === "lokma") {
      return (
        <View style={styles.lokmaMessageContainer}>
          <View style={styles.lokmaMessageHeader}>
            <Image source={item.lokmaAvatar} style={styles.lokmaAvatar} />
            <Text style={styles.lokmaName}>{item.lokmaName}</Text>
          </View>
          <View style={styles.lokmaBubble}>
            <Text style={styles.lokmaText}>{item.text}</Text>
          </View>
        </View>
      );
    }

    return null;
  };

  return (
    <SafeAreaView style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
            <Image
              source={require("@/assets/images/icons/back-button.png")}
              style={styles.backButtonIcon}
              resizeMode="contain"
            />
          </TouchableOpacity>

          <TouchableOpacity style={styles.bugunButton}>
            <Text style={styles.bugunText}>Bugün</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.bugunYapButton}>
            <Image
              source={require("@/assets/images/logo/logo-small.png")}
              style={styles.logo}
            />
          </TouchableOpacity>
        </View>
      </View>

      {/* Main Content */}
      {(!isChatStarted || !hasPackage) ? (
        <ScrollView style={styles.mainContent} showsVerticalScrollIndicator={false}>
          {/* Greeting Section */}
          <View style={styles.greetingSection}>
            <Text style={styles.greetingText}>
              Merhaba!{" "}
              <Text
                style={{
                  fontSize: 24,
                  fontWeight: "700",
                  color: COLOR_SCALES.primary[80],
                }}
              >
                {userName ?? 'Kullanıcı'}
              </Text>
            </Text>
            <Text style={styles.helpText}>Sana nasıl yardımcı olabilirim?</Text>
          </View>

          {/* Lokma Character */}
          <View style={styles.characterSection}>
            <Image
              source={require("@/assets/images/lokma-right.png")}
              style={styles.lokmaCharacter}
              resizeMode="contain"
            />
          </View>

          {/* Quick Buttons */}
          <View style={styles.quickButtonsSection}>
            <View style={styles.quickButtonsGrid}>
              {quickButtons.map((buttonText, index) => (
                <TouchableOpacity
                  key={index}
                  style={[styles.quickButton, !hasPackage && { opacity: 0.6 }]}
                  onPress={() => handleQuickButtonPress(buttonText)}
                  disabled={!hasPackage}
                >
                  <Text style={styles.quickButtonText}>{buttonText}</Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
          {!hasPackage && (
            <View style={styles.lockBanner}>
              <Text style={styles.lockBannerTitle}>Lokma sohbeti için aktif paket gerekli</Text>
              <Text style={styles.lockBannerDesc}>Paket satın alarak Lokma ile sohbet etmeye başlayabilirsin.</Text>
              <TouchableOpacity style={styles.lockBannerButton} onPress={() => router.push("/(tabs)/packages")}>
                <Text style={styles.lockBannerButtonText}>Paketleri Gör</Text>
              </TouchableOpacity>
            </View>
          )}
        </ScrollView>
      ) : (
        <>
          <View style={[styles.chatContainer, { paddingBottom: 20 + Math.max(insets?.bottom ?? 0, 8) }]}>
            {/* Date Separator */}
            <View style={styles.dateSeparator}>
              <Text style={styles.dateText}>Bugün</Text>
            </View>

            {/* Messages */}
            <FlatList
              data={messages}
              renderItem={renderMessage}
              keyExtractor={(item) => item.id.toString()}
              style={styles.messagesList}
              showsVerticalScrollIndicator={false}
              ref={scrollViewRef}
              onLayout={() => scrollViewRef.current?.scrollToEnd({ animated: false })}
              onContentSizeChange={() => scrollViewRef.current?.scrollToEnd({ animated: true })}
              contentContainerStyle={{ paddingBottom: inputHeight + 24, paddingTop: 8, flexGrow: 1 }}
              keyboardShouldPersistTaps="always"
              keyboardDismissMode="on-drag"
            />
            {isLoading && (
              <Loading size="small" message="Lokma yazıyor..." />
            )}
          </View>

          {/* Input Section (Keyboard aware) */}
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : 'padding'}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
          >
            <View style={styles.inputSection} onLayout={(e) => setInputHeight(e?.nativeEvent?.layout?.height ?? 72)}>
              <View style={styles.inputContainer}>
              <TextInput
                  style={styles.textInput}
                  placeholder="Mesajınızı yazın..."
                  placeholderTextColor={COLOR_SCALES.gray[40]}
                  value={inputText}
                  onChangeText={setInputText}
                  multiline
                  editable={hasPackage && !isLoading}
                />
                <TouchableOpacity
                  style={[
                    styles.sendButton,
                  (isLoading || !inputText.trim() || !hasPackage) && { opacity: 0.6 },
                  ]}
                  onPress={handleSendMessage}
                  disabled={isLoading || !inputText.trim() || !hasPackage}
                >
                  <Image
                    source={require("@/assets/images/send.png")}
                    style={styles.sendButtonIcon}
                    resizeMode="contain"
                  />
                </TouchableOpacity>
              </View>
            </View>
          </KeyboardAvoidingView>
        </>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: "#FFFFFF",
  },
  header: {
    backgroundColor: "#FFFFFF",
    paddingTop: 10,
    paddingBottom: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#F0F0F0",
  },
  headerContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    marginTop: 40,
  },
  backButton: {
    width: 40,
    height: 40,
    alignItems: "center",
    justifyContent: "center",
  },
  backButtonIcon: {
    width: 40,
    height: 40,
  },
  headerCenter: {
    flex: 1,
    alignItems: "center",
  },
  bugunButton: {
    backgroundColor: "#F0F0F0",
    paddingHorizontal: 20,
    paddingVertical: 8,
    borderRadius: 20,
  },
  bugunText: {
    ...title["S/Medium"],
    color: "#666666",
  },
  bugunYapButton: {
    flexDirection: "row",
    alignItems: "center",
  },
  logo: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: "#FF0026",
    borderWidth: 1,
    borderColor: "#fff",
  },
  logoContainer: {
    backgroundColor: "#FF0026",
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 20,
    alignItems: "center",
  },
  logoText: {
    color: "#FFFFFF",
    fontSize: 12,
    fontWeight: "600",
    marginBottom: 2,
  },
  mainContent: {
    flex: 1,
    paddingHorizontal: 20,
  },
  greetingSection: {
    alignItems: "center",
    marginTop: 40,
    marginBottom: 30,
  },
  greetingText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.secondary[100],
    textAlign: "center",
    marginBottom: 8,
  },
  userName: {
    color: COLOR_SCALES.primary[60],
    fontSize: 24,
    fontWeight: "700",
  },
  helpText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.secondary[100],
    textAlign: "center",
  },
  characterSection: {
    alignItems: "center",
    marginBottom: 40,
  },
  lokmaCharacter: {
    width: 100,
    height: 100,
  },
  quickButtonsSection: {
    marginBottom: 40,
  },
  quickButtonsGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-between",
    gap: 12,
  },
  quickButton: {
    backgroundColor: COLOR_SCALES.white[20],
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 20,
    minWidth: "48%",
    alignItems: "center",
    borderWidth: 1,
    borderColor: COLOR_SCALES.gray[20],
  },
  quickButtonText: {
    ...paragraph["S/Medium"],
    color: COLOR_SCALES.gray[100],
    textAlign: "center",
    lineHeight: 18,
  },
  lockBanner: {
    marginHorizontal: 20,
    marginTop: 12,
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[60],
    backgroundColor: COLOR_SCALES.primary[10],
    alignItems: "center",
  },
  lockBannerTitle: {
    ...title["S/Bold"],
    color: COLOR_SCALES.primary[80],
    marginBottom: 6,
  },
  lockBannerDesc: {
    ...paragraph["S/Regular"],
    color: COLOR_SCALES.colorGray[80],
    textAlign: "center",
    marginBottom: 10,
  },
  lockBannerButton: {
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderRadius: 20,
    borderWidth: 2,
    borderColor: COLOR_SCALES.primary[80],
    backgroundColor: COLOR_SCALES.white.white,
  },
  lockBannerButtonText: {
    ...title["S/Medium"],
    color: COLOR_SCALES.primary[80],
  },
  inputSection: {
    paddingHorizontal: 20,
    paddingVertical: 16,
    backgroundColor: "#FFFFFF",
    borderTopWidth: 1,
    borderTopColor: COLOR_SCALES.gray[20],
  },
  inputContainer: {
    flexDirection: "row",
    alignItems: "flex-end",
    backgroundColor: "#FFFFFF",
    borderRadius: 32,
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[100],
    paddingHorizontal: 16,
    paddingBottom: 6,
    paddingTop: 2,
  },
  textInput: {
    flex: 1,
    paddingVertical: 12,
    paddingHorizontal: 8,
    maxHeight: 100,
    fontSize: 14,
    color: COLOR_SCALES.gray[90],
  },
  sendButton: {
    backgroundColor: "#B4001A",
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: "center",
    justifyContent: "center",
    marginLeft: 8,
  },
  sendButtonIcon: {
    width: 40,
    height: 40,
  },
  // Chat Styles
  chatContainer: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  dateSeparator: {
    alignItems: "center",
    marginVertical: 16,
  },
  dateText: {
    backgroundColor: COLOR_SCALES.gray[20],
    paddingHorizontal: 16,
    paddingVertical: 6,
    borderRadius: 16,
    fontSize: 12,
    color: COLOR_SCALES.gray[60],
  },
  messagesList: {
    flex: 1,
    paddingHorizontal: 16,
  },
  userMessageContainer: {
    alignItems: "flex-end",
    marginBottom: 16,
  },
  userMessageHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 4,
  },
  userAvatar: {
    width: 24,
    height: 24,
    borderRadius: 12,
    marginRight: 8,
  },
  userName: {
    fontSize: 12,
    color: COLOR_SCALES.secondary[100],
    fontWeight: "700",
  },
  userBubble: {
    backgroundColor: COLOR_SCALES.gray[20],
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 12,
    maxWidth: "90%",
  },
  userText: {
    color: COLOR_SCALES.gray[90],
    fontSize: 15,
    lineHeight: 22,
    flexShrink: 1,
    flexWrap: "wrap",
  },
  lokmaMessageContainer: {
    alignItems: "flex-start",
    marginBottom: 16,
  },
  lokmaMessageHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 4,
  },
  lokmaAvatar: {
    width: 24,
    height: 24,
    borderRadius: 12,
    marginRight: 8,
  },
  lokmaName: {
    fontSize: 14,
    color: COLOR_SCALES.secondary[100],
    fontWeight: "700",
  },
  lokmaBubble: {
    backgroundColor: COLOR_SCALES.primary[80],
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 12,
    maxWidth: "90%",
  },
  lokmaText: {
    color: "#FFFFFF",
    fontSize: 16,
    lineHeight: 24,
    includeFontPadding: false,
    textAlignVertical: "center",
    flexShrink: 1,
    flexWrap: "wrap",
  },
}); 