import React, { useState, useRef, useEffect } from "react";
import {
  View,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  FlatList,
  Image,
} from "react-native";
import { router, useLocalSearchParams } from "expo-router";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import { FLEX, COLOR_SCALES } from "@/theme";
import { title } from "@/theme/typography";
import Text from "@/components/common/Text";
import { getLokmaNotification, saveLokmaNotification, getFoodTypes } from "../services/notifications";
import { OPENAI_API_KEY } from "@/constants/api";

export default function ChatScreen() {
  const params = useLocalSearchParams();
  const [messages, setMessages] = useState([]);
  const [currentStep, setCurrentStep] = useState("idle");
  const [foodType, setFoodType] = useState([]);
  const [selectedMealId, setSelectedMealId] = useState(null);
  const [selectedFoodTypeIds, setSelectedFoodTypeIds] = useState([]);
  const [selectedPlaceId, setSelectedPlaceId] = useState(null);
  const [inputText, setInputText] = useState("");
  const scrollViewRef = useRef();
  const [isLoading, setIsLoading] = useState(false);


  const handleBackPress = () => {
    router.back();
  };


  const foodTypes = async () => {
    try {
      console.log("foodTypes");
      const response = await getFoodTypes();
      console.log("foodTypes resp:", response);
      setFoodType(response?.data ?? []);
    } catch (e) {
      console.log("foodTypes error:", e?.message);
      setFoodType([]);
    }
  };

  const pushLokmaMessage = (partial) => ({
    id: Date.now() + Math.floor(Math.random() * 1000),
    type: "lokma",
    ...partial,
  });

  const pushUserMessage = (text) => ({
    id: Date.now() + Math.floor(Math.random() * 1000),
    type: "user",
    text,
  });

  const startDailyFlow = (prefilled) => {
    if (prefilled?.answeredYes === "0") {
      // Directly show closing message
      const closing = buildClosingMessage();
      setMessages((prev) => [closing]);
      setCurrentStep("done");
      return;
    }

    if (prefilled?.meal) {
      const mealQ = pushLokmaMessage({
        text: "Hangi öğünde gıdanı israf ettin?",
        hasButtons: true,
        buttons: [
          { id: 1, text: "Sabah", selected: prefilled.meal === "Sabah" },
          { id: 2, text: "Öğlen", selected: prefilled.meal === "Öğle" },
          { id: 3, text: "Akşam", selected: prefilled.meal === "Akşam" },
        ],
      });
      const userMeal = pushUserMessage(prefilled.meal);
      const foodsQ = buildFoodsQuestion();
      setMessages([mealQ, userMeal, foodsQ]);
      setCurrentStep("foods");
      return;
    }

    // Initial question
    const q = pushLokmaMessage({
      text: "Bugün gıdanı israf ettin mis?",
      hasButtons: true,
      buttons: [
        { id: "yes", text: "Evet", selected: false },
        { id: "no", text: "Hayır", selected: false },
      ],
    });
    setMessages([q]);
    setCurrentStep("initial");
  };

  const buildFoodsQuestion = () =>
    pushLokmaMessage({
      text: "Aşağıdakilerden hangi gıdaları israf ettin? (Birden fazla seçebilirsin)",
      hasCheckboxes: true,
      checkboxes:
        (foodType?.length > 0
          ? foodType.map((ft) => ({
              id: String(ft?.id),
              text: ft?.name ?? "",
              checked: false,
            }))
          : []),
    });

  const buildLocationQuestion = () =>
    pushLokmaMessage({
      text: "Gıdanı nerede israf ettin?",
      hasButtons: true,
      buttons: [
        { id: 1, text: "Evde", selected: false },
        { id: 2, text: "İş yerindeki yemekhanede", selected: false },
        { id: 3, text: "Restoran veya Kafede", selected: false },
      ],
    });

  const buildClosingMessage = () =>
    pushLokmaMessage({
      text: buildPersonalClosingText(),
    });

  const buildPersonalClosingText = () => {
    // Try to read name from route or elsewhere in app state if available in future
    const nameParam = params?.name;
    const name = typeof nameParam === "string" && nameParam.length > 0 ? nameParam : "Misafir";
    return `Sevgili ${name},  Benimle paylaştığın bu bilgiler için çok teşekkür ederim. Seninle her gün yaptığımız bu bilgi paylaşımı sayesinde verilerini senin için 30 günün sonunda sunacağım rapora kayıt ediyorum.  Bu raporu, büyük bir değişimin küçük ama güçlü kahramanı olarak senin için hazırlıyorum. Belki bazen tabağında bir şeyler kalıyor, belki bu konuda çok dikkatli davranıyorsun... Her halükârda, bu raporda yer alan veriler, senin güçlü yanlarını gösterirken, aynı zamanda birlikte geliştirebileceğimiz alanlara da ışık tutuyor.  🌱 Ama bilmeni istediğim çok önemli bir şey var: Gıda israfı sadece bir ev alışkanlığı değil; iklim krizinin gizli bir tetikleyicisi. Her israf edilen lokma, sadece çöpe giden yemek değil... Aynı zamanda boşa harcanan su, enerji, toprak ve emek demek.  Ve bu kayıplar, gezegenimizin geleceğini ve çocuklarımızın yarınlarını sessizce tehdit ediyor.  💪 İyi haber mi? Bu döngüyü değiştirecek güce sahip birisi var: Sen`;
  };

  // OpenAI chat integration (Lokma cevapları)
  const getLokmaResponse = async (userMessage) => {
    if (!OPENAI_API_KEY) {
      const errorMsg = pushLokmaMessage({ text: "API anahtarı bulunamadı. Lütfen yapılandırmayı kontrol edin." });
      setMessages((prev) => [...prev, errorMsg]);
      return;
    }

    if (isLoading) return;

    const typing = { id: Date.now() + 1, type: "typing", text: "Lokma yazıyor..." };
    setMessages((prev) => [...prev, typing]);
    setIsLoading(true);

    try {
      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,
        }),
      });

      let reply = "Üzgünüm, şu an cevap veremiyorum 😔";
      if (response.ok) {
        const data = await response.json();
        reply = data?.choices?.[0]?.message?.content ?? reply;
      } else {
        try {
          const errJson = await response.json();
          reply = errJson?.error?.message ?? reply;
        } catch (_) {}
      }

      setMessages((prev) => prev.filter((m) => m.id !== typing.id).concat(pushLokmaMessage({ text: reply })));
    } catch (error) {
      setMessages((prev) => prev.filter((m) => m.id !== typing.id).concat(pushLokmaMessage({ text: error?.message ?? "Bir hata oluştu, lütfen tekrar deneyin ⚠️" })));
    } finally {
      setIsLoading(false);
    }
  };

  const formatDateForApi = (dateObj) => {
    const pad = (n) => String(n).padStart(2, "0");
    const yyyy = dateObj.getFullYear();
    const MM = pad(dateObj.getMonth() + 1);
    const dd = pad(dateObj.getDate());
    const HH = pad(dateObj.getHours());
    const mm = pad(dateObj.getMinutes());
    const ss = pad(dateObj.getSeconds());
    return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
  };

  const submitLokmaNotification = async ({ isWaste, meal, place, types }) => {
    try {
      const now = new Date();
      const payload = {
        isWaste,
        meal: meal ?? null,
        place: place ?? null,
        date: formatDateForApi(now),
        types: Array.isArray(types) ? types.map((n) => Number(n)) : [],
        // Backend uyumluluğu için her iki alanı da gönder
        foodTypes: Array.isArray(types) ? types.map((n) => Number(n)) : [],
      };
      const response = await saveLokmaNotification(payload);
      console.log("saveLokmaNotification resp:", response);
      return true;
    } catch (e) {
      console.log("saveLokmaNotification error:", e?.message);
      return false;
    }
  };

  useEffect(() => {
    foodTypes();
    if (messages?.length === 0 && currentStep === "idle") {
      startDailyFlow();
    }
  }, []);

  const handleButtonPress = async (messageId, buttonId) => {
    // update selection UI
    setMessages((prev) =>
      prev.map((msg) => {
        if (msg.id === messageId && msg.hasButtons) {
          // Eğer butonlar zaten kilitliyse yeniden seçim yapılmasın
          if (msg.buttonsLocked) return msg;
          return {
            ...msg,
            buttonsLocked: true,
            buttons: msg.buttons.map((btn) => ({
              ...btn,
              selected: btn.id === buttonId,
            })),
          };
        }
        return msg;
      })
    );

    const source = messages.find((m) => m.id === messageId);
    const selectedButton = source?.buttons?.find((b) => b.id === buttonId);
    if (source?.buttonsLocked) {
      return;
    }
    const selectedText = selectedButton?.text ?? "";

    if (!selectedText) return;

    // append user answer
    setMessages((prev) => [...prev, pushUserMessage(selectedText)]);

    // Decide next step
    if (currentStep === "initial") {
      if (buttonId === "yes") {
        setMessages((prev) => [...prev, pushLokmaMessage({
          text: "Hangi öğünde gıdanı israf ettin?",
          hasButtons: true,
          buttons: [
            { id: 1, text: "Sabah", selected: false },
            { id: 2, text: "Öğlen", selected: false },
            { id: 3, text: "Akşam", selected: false },
          ],
        })]);
        setCurrentStep("meal");
      } else {
        // no
        setMessages((prev) => [...prev, buildClosingMessage()]);
        setCurrentStep("done");
        await submitLokmaNotification({ isWaste: 0, meal: null, place: null, types: [] });
      }
      return;
    }

    if (currentStep === "meal") {
      setSelectedMealId(buttonId);
      setMessages((prev) => [...prev, buildFoodsQuestion()]);
      setCurrentStep("foods");
      return;
    }

    if (currentStep === "location") {
      await submitLokmaNotification({
        isWaste: 1,
        meal: selectedMealId,
        place: buttonId,
        types: selectedFoodTypeIds,
      });
      setMessages((prev) => [...prev, buildClosingMessage()]);
      setCurrentStep("done");
      return;
    }
  };

  const handleCheckboxPress = (messageId, checkboxId) => {
    setMessages((prev) =>
      prev.map((msg) => {
        if (msg.id === messageId && msg.hasCheckboxes) {
          return {
            ...msg,
            checkboxes: msg.checkboxes.map((cb) => ({
              ...cb,
              checked: cb.id === checkboxId ? !cb.checked : cb.checked,
            })),
          };
        }
        return msg;
      })
    );
  };

  const handleContinueButtonPress = (messageId) => {
    const currentMessage = messages.find((msg) => msg.id === messageId);
    const selectedCheckboxes = currentMessage?.checkboxes?.filter((cb) => cb.checked) || [];
    
    if (selectedCheckboxes.length > 0) {
      // Seçili checkbox'ların metinlerini birleştir
      const selectedTexts = selectedCheckboxes.map((cb) => cb.text).join(", ");
      const ids = selectedCheckboxes
        .map((cb) => parseInt(cb.id, 10))
        .filter((n) => Number.isFinite(n));
      setSelectedFoodTypeIds(ids);
      
      // Kullanıcı cevabını ekle
      const userMessage = {
        id: Date.now(),
        type: "user",
        text: selectedTexts,
      };
      setMessages((prev) => [...prev, userMessage, buildLocationQuestion()]);
      setCurrentStep("location");
    }
  };

  const handleSendMessage = () => {
    if (inputText.trim()) {
      const newMessage = {
        id: Date.now(),
        type: "user",
        text: inputText.trim(),
      };
      setMessages((prev) => [...prev, newMessage]);
      setInputText("");

      // Lokma (OpenAI) yanıtını al
      getLokmaResponse(newMessage.text);
    }
  };

  const renderMessage = ({ item }) => {
    if (item.type === "lokma") {
      return (
        <View style={styles.lokmaMessageContainer}>
          <View style={styles.lokmaAvatarContainer}>
            <View style={styles.lokmaAvatar}>
              <Image
                source={require("@/assets/images/package-lokma.png")}
                style={styles.lokmaCharacter}
                resizeMode="contain"
              />
            </View>
            <Text style={styles.lokmaName}>Lokma'm</Text>
          </View>

          <View style={styles.messageContent}>
            <View style={styles.lokmaBubble}>
              <Text style={styles.lokmaText}>{item.text}</Text>
            </View>

            {item.hasButtons && (
              <View style={styles.buttonContainer}>
                {item.buttons.map((button) => (
                  <TouchableOpacity
                    key={button.id}
                    style={[
                      styles.pillButton,
                      button.selected
                        ? styles.selectedButton
                        : styles.unselectedButton,
                    ]}
                    onPress={() => handleButtonPress(item.id, button.id)}
                  >
                    <Text
                      style={[
                        styles.buttonText,
                        button.selected
                          ? styles.selectedButtonText
                          : styles.unselectedButtonText,
                      ]}
                    >
                      {button.text}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>
            )}

            {item.hasCheckboxes && (
              <>
                <View style={styles.checkboxContainer}>
                  <View style={styles.checkboxList}>
                    {item.checkboxes.map((checkbox) => (
                      <TouchableOpacity
                        key={checkbox.id}
                        style={styles.checkboxItem}
                        onPress={() =>
                          handleCheckboxPress(item.id, checkbox.id)
                        }
                      >
                        <View
                          style={[
                            styles.checkbox,
                            checkbox.checked
                              ? styles.checkedCheckbox
                              : styles.uncheckedCheckbox,
                          ]}
                        >
                          {checkbox.checked && (
                            <Ionicons
                              name="checkmark"
                              size={16}
                              color="#FFFFFF"
                            />
                          )}
                        </View>
                        <Text style={styles.checkboxText}>{checkbox.text}</Text>
                      </TouchableOpacity>
                    ))}
                  </View>
                </View>

                <TouchableOpacity 
                  style={styles.continueButton}
                  onPress={() => handleContinueButtonPress(item.id)}
                >
                  <Text style={styles.continueButtonText}>
                    Devam Et (seçili{" "}
                    {item.checkboxes.filter((cb) => cb.checked).length})
                  </Text>
                </TouchableOpacity>
              </>
            )}
          </View>
        </View>
      );
    }

    if (item.type === "user") {
      return (
        <View style={styles.userMessageContainer}>
          <View style={styles.userBubble}>
            <Text style={styles.userText}>{item.text}</Text>
          </View>
        </View>
      );
    }

    if (item.type === "typing") {
      return (
        <View style={styles.typingContainer}>
          <View style={styles.lokmaAvatarContainer}>
            <View style={styles.lokmaAvatar}>
              <Image
                source={require("@/assets/images/package-lokma.png")}
                style={styles.lokmaCharacter}
                resizeMode="contain"
              />
            </View>
            <Text style={styles.lokmaName}>Lokma'm</Text>
          </View>
          <Text style={styles.typingText}>{item.text}</Text>
        </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>

      <View style={styles.chatContainer}>
        <FlatList
          data={messages}
          renderItem={renderMessage}
          keyExtractor={(item) => item.id.toString()}
          style={styles.messagesList}
          showsVerticalScrollIndicator={false}
          ref={scrollViewRef}
          onContentSizeChange={() =>
            scrollViewRef.current?.scrollToEnd({ animated: true })
          }
        />
      </View>

      <View style={styles.inputContainer}>
        <TextInput
          style={styles.textInput}
          placeholder="Mesajınızı yazın..."
          placeholderTextColor={COLOR_SCALES.gray[40]}
          value={inputText}
          onChangeText={setInputText}
          multiline
        />
        <TouchableOpacity style={styles.sendButton} onPress={handleSendMessage}>
          <Image
            source={require("@/assets/images/send.png")}
            style={styles.sendButtonIcon}
            resizeMode="contain"
          />
        </TouchableOpacity>
      </View>
    </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,
  },
  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",
  },
  chatContainer: {
    flex: 1,
    paddingHorizontal: 16,
    backgroundColor: "#FFFFFF",
    marginTop: 30,
  },
  messagesList: {
    flex: 1,
  },
  lokmaMessageContainer: {
    marginBottom: 16,
    alignItems: "flex-start",
  },
  lokmaAvatarContainer: {
    alignItems: "center",
    marginRight: 8,
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  lokmaAvatar: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: "#F0F0F0",
    alignItems: "center",
    justifyContent: "center",
    marginBottom: 4,
  },
  lokmaCharacter: {
    width: 38,
    height: 40,
  },
  lokmaName: {
    fontSize: 14,
    color: COLOR_SCALES.secondary[100],
    fontWeight: "700",
  },
  messageContent: {
    flex: 1,
    maxWidth: "80%",
  },
  lokmaBubble: {
    backgroundColor: COLOR_SCALES.primary[80],
    borderRadius: 24,
    paddingHorizontal: 16,
    paddingVertical: 12,
    marginBottom: 8,
    marginTop: 10,
  },
  lokmaText: {
    color: "#FFFFFF",
    fontSize: 14,
    lineHeight: 20,
  },
  buttonContainer: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 8,
    marginTop: 10,
  },
  pillButton: {
    backgroundColor: "#FFFF",
    paddingVertical: 4,
    paddingHorizontal: 20,
    borderRadius: 24,
    borderWidth: 2,
    borderColor: COLOR_SCALES.secondary[50],
    alignItems: "center",
    shadowColor: "#DB0020",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1,
    shadowRadius: 0,
    elevation: 4,
  },
  selectedButton: {
    backgroundColor: "#FF0025",
    paddingVertical: 6,
    paddingHorizontal: 20,
    borderRadius: 24,
    borderWidth: 2,
    borderColor: "#420F1B",
    alignItems: "center",
    shadowColor: "#DB0020",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1,
    shadowRadius: 0,
    elevation: 4,
  },
  unselectedButton: {
    backgroundColor: "#FFFFFF",
    borderColor: "#B4001A",
  },
  buttonText: {
    fontSize: 14,
    fontWeight: "500",
  },
  selectedButtonText: {
    color: "#FFFFFF",
  },
  unselectedButtonText: {
    color: "#B4001A",
  },
  checkboxContainer: {
    backgroundColor: "#FFFFFF",
    borderWidth: 1,
    borderColor: "#B4001A",
    borderRadius: 8,
    padding: 12,
  },
  checkboxList: {
    marginBottom: 12,
  },
  checkboxItem: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 8,
  },
  checkbox: {
    width: 20,
    height: 20,
    borderRadius: 4,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
  },
  checkedCheckbox: {
    backgroundColor: "#B4001A",
  },
  uncheckedCheckbox: {
    backgroundColor: "#FFFFFF",
    borderWidth: 1,
    borderColor: "#B4001A",
  },
  checkboxText: {
    fontSize: 14,
    color: COLOR_SCALES.gray[90],
  },
  continueButton: {
    backgroundColor: "#FF0025",
    paddingVertical: 8,
    paddingHorizontal: 20,
    borderRadius: 24,
    borderWidth: 2,
    borderColor: "#420F1B",
    alignItems: "center",
    shadowColor: "#DB0020",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1,
    shadowRadius: 0,
    elevation: 4,
    marginBottom: 40,
    marginTop: 20,
  },
  continueButtonText: {
    color: "#FFFFFF",
    fontSize: 14,
    fontWeight: "500",
  },
  userMessageContainer: {
    alignItems: "flex-end",
    marginBottom: 16,
  },
  userBubble: {
    backgroundColor: COLOR_SCALES.white[20],
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 12,
    maxWidth: "80%",
  },
  userText: {
    color: COLOR_SCALES.gray[90],
    fontSize: 14,
    lineHeight: 20,
  },
  typingContainer: {
    marginBottom: 16,
    alignItems: "flex-start",
  },
  typingText: {
    color: COLOR_SCALES.gray[50],
    fontSize: 14,
    fontStyle: "italic",
  },

  inputContainer: {
    flexDirection: "row",
    alignItems: "flex-end",
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: "#FFFFFF",
    borderTopWidth: 1,
    borderTopColor: COLOR_SCALES.gray[20],
  },
  textInput: {
    flex: 1,
    backgroundColor: COLOR_SCALES.gray[10],
    borderRadius: 24,
    paddingHorizontal: 16,
    paddingVertical: 12,
    marginRight: 8,
    maxHeight: 100,
    fontSize: 14,
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[100],
  },
  sendButton: {
    backgroundColor: "#B4001A",
    width: 40,
    height: 40,
    borderRadius: 20,
    alignItems: "center",
    justifyContent: "center",
  },
  sendButtonIcon: {
    width: 40,
    height: 40,
  },
});
