import React, { useState, useEffect, useRef } from "react";
import {
  View,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
  Platform,
  Image,
  Alert,
  TextInput,
  KeyboardAvoidingView,
  TouchableWithoutFeedback,
  Keyboard,
  SafeAreaView,
  useWindowDimensions,
} from "react-native";
import {
  ActivityIndicator,
  Divider,
  Modal,
  Portal,
  Text,
} from "react-native-paper";
import { StatusBar } from "expo-status-bar";
import Markdown from "react-native-markdown-display";
import axios from "axios";
import { AntDesign } from "@expo/vector-icons";
import logo from "../../assets/damgo-trans.png";
import { LinearGradient } from "expo-linear-gradient";
import * as Clipboard from "expo-clipboard";
import { Ionicons } from "@expo/vector-icons";
import Groq from "groq-sdk";
import { Picker } from "@react-native-picker/picker";
import { Dropdown } from "react-native-element-dropdown";
import { ScreenContext } from "../context/RotationContext";

// Move data outside component to avoid re-creation on each render
const MODEL_OPTIONS = [
  {
    label: "gpt-3.5",
    value: "gpt-3.5",
    icon: "https://img.icons8.com/ios-glyphs/30/chatgpt.png",
  },
  {
    label: "groq", 
    value: "groq",
    icon: "https://groq.com/wp-content/uploads/2024/02/android-icon-192x192-1.png",
  },
];

// Add rate limiting
const RATE_LIMIT_MS = 1000; // 1 request per second
let lastRequestTime = 0;

const ChatGPTButton = ({ apiKey, initialQuery, bottomInset }) => {
  // Add input validation
  if (!apiKey) {
    throw new Error("API key is required");
  }

  const [visible, setVisible] = useState(false);
  const [scrollOffset, setScrollOffset] = useState(0);
  const [conversation, setConversation] = useState([]);
  const [followUpQuery, setFollowUpQuery] = useState("");
  const [loading, setLoading] = useState(false);
  const [icon1, setIcon1] = useState(MODEL_OPTIONS[1].icon);
  const [iconStates, setIconStates] = useState({});
  const scrollViewRef = useRef(null);
  const [selectedModel, setSelectedModel] = useState("groq");
  const [value, setValue] = useState(null);
  const [isFocus, setIsFocus] = useState(false);
  const [error, setError] = useState(null);

  // Add error boundary
  useEffect(() => {
    if (error) {
      Alert.alert("Error", error.message);
    }
  }, [error]);

  // Add request timeout
  const TIMEOUT_MS = 30000;
  
  const groq = new Groq({
    apiKey: process.env.GROQ_API_KEY // Move to env var
  });

  const showModal = () => setVisible(true);
  const hideModal = () => setVisible(false);

  const { height: screenHeight, width: screenWidth } = useWindowDimensions();
  const { height, width, isLandscape, pixelRatio } = React.useContext(ScreenContext);

  const styles = dynamicStyles(
    height,
    width, 
    screenHeight,
    screenWidth,
    isLandscape,
    bottomInset,
    pixelRatio
  );

  const fetchResponse = async (query, initial) => {
    try {
      // Rate limiting
      const now = Date.now();
      if (now - lastRequestTime < RATE_LIMIT_MS) {
        throw new Error("Please wait before making another request");
      }
      lastRequestTime = now;

      // Input validation
      if (!query?.trim()) {
        throw new Error("Query cannot be empty");
      }

      setLoading(true);
      setError(null);

      const trimmedQuery = query.trim();
      const basePrompt = "Interpret the query as a request for specific information...";
      
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);

      try {
        if (selectedModel === "gpt-3.5") {
          const messages = [
            ...conversation,
            {
              role: "user", 
              content: initial ? basePrompt + trimmedQuery : trimmedQuery
            }
          ];

          const result = await axios.post(
            "https://api.openai.com/v1/chat/completions",
            {
              model: "gpt-3.5-turbo",
              messages,
              max_tokens: 250
            },
            {
              headers: {
                Authorization: `Bearer ${apiKey}`,
                "Content-Type": "application/json"
              },
              signal: controller.signal
            }
          );

          const aiResponse = result.data.choices[0].message.content;
          setConversation(prev => [...prev, { role: "assistant", content: aiResponse }]);

        } else if (selectedModel === "groq") {
          const chatCompletion = await groq.chat.completions.create({
            messages: [{ role: "user", content: trimmedQuery }],
            model: "llama3-8b-8192",
            signal: controller.signal
          });

          const aiResponse = chatCompletion.choices[0]?.message?.content;
          if (!aiResponse) {
            throw new Error("Empty response from Groq");
          }

          setConversation(prev => [
            ...prev,
            { role: "user", content: trimmedQuery },
            { role: "assistant", content: aiResponse }
          ]);
        }

        // Scroll with debounce
        const scrollTimeout = setTimeout(() => {
          scrollViewRef.current?.scrollToEnd({ animated: true });
        }, 100);

        return () => clearTimeout(scrollTimeout);

      } finally {
        clearTimeout(timeoutId);
      }

    } catch (error) {
      setError(error);
      console.error("Error fetching response:", error);
    } finally {
      setLoading(false);
    }
  };

  // Rest of the component code remains the same...
  // (Keeping existing UI rendering logic)

  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      <TouchableOpacity style={styles.floatingButton} onPress={showModal}>
        <Image source={logo} style={styles.logo} />
      </TouchableOpacity>
      
      {/* Rest of JSX remains the same */}
      
    </View>
  );
};

// Styles remain the same...

export default ChatGPTButton;

aduit this file find bottleneck, security threads, crash causing loops, unexcepted brakes, loopholes. give me changes