import { AutoCompleteItem } from "@/apis/autoCompleteApi";
import { getSearchResults, SearchResultItem } from "@/apis/searchApi";
import styles from "@/app/tabStyles/indexStyles";
import { useDiscoveryContext } from "@/contexts/DiscoveryContext";
import { FontAwesome } from "@expo/vector-icons";
import Feather from "@expo/vector-icons/Feather";
import React from "react";
import {
  Keyboard,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from "react-native";


export default function TabTwoScreen() {
  const { query, setQuery, suggestions } = useDiscoveryContext();

  const [tags, setTags] = React.useState<AutoCompleteItem[]>([]);

  const [searchResults, setSearchResults] = React.useState<SearchResultItem[]>([]);

  const getIconName = (type: AutoCompleteItem["type"]) => {
    switch (type) {
      case "PERSON":
        return "user";
      case "SHOW":
        return "television";
      case "YEAR":
        return "calendar";
      default:
        return "tag";
    }
  };

  function tagAdded(tag: AutoCompleteItem) {
    console.log("Tag added:", tag);
    const nextTags = tags.some((t) => t.text === tag.text)
      ? tags
      : [...tags, tag];

    setTags(nextTags);

    const tagStrings = nextTags.map((t) => t.text);

    getSearchResults(tagStrings, 20)
      .then(setSearchResults)
      .catch(console.error);

    setQuery("");
    Keyboard.dismiss();

    console.log("Searching with tags:", tagStrings);
  }



  return (
    <View style={[styles.mainContainer]}>
      <View style={styles.header}>
        <Text style={[styles.title, { fontSize: 28 }]}>Durchsuchen</Text>
      </View>

      <View style={{ paddingHorizontal: 10 }}>


        <View style={styles.searchContainer}>
          <TextInput
            value={query}
            onChangeText={setQuery}
            placeholder="Wonach suchst du?"
            placeholderTextColor=""
            style={{
              fontSize: 18,
              fontWeight: "500",
              color: "hsl(221, 39%, 80%)",
              width: "90%",
              height: "100%",
            }}
            returnKeyType="search"
            onSubmitEditing={() => console.log("Search:", query)}
            autoCapitalize="none"
          />

          {query.length === 0 ? (
            <Feather name="search" size={24} color="hsl(221, 39%, 80%)" />
          ) : (
            <Feather
              name="x"
              size={24}
              color="hsl(221, 39%, 80%)"
              onPress={() => setQuery("")}
            />
          )}
        </View>

        <View style={styles.tagContainer}>
          {tags.map((tag) => (
            <TouchableOpacity
              key={tag.text}
              onPress={() =>
                setTags((prev) => prev.filter((t) => t.text !== tag.text))
              }
            >
              <View style={styles.tag}>
                <FontAwesome
                  name={getIconName(tag.type)}
                  size={16}
                  color="#bbb"
                  style={{ marginRight: 6 }}
                />
                <Text style={styles.tagLabel}>{tag.text}</Text>
                <FontAwesome
                  name="times-circle"
                  size={16}
                  color="#bbb"
                  style={{ marginLeft: 6 }}
                />
              </View>
            </TouchableOpacity>
          ))}
        </View>

        {query.length > 0 && (
          <View style={styles.suggestionsSection}>
            <Text style={styles.suggestionTitle}>Suchvorschläge</Text>
            <ScrollView keyboardShouldPersistTaps="handled">
              {suggestions.map((suggestion, idx) => (
                <TouchableOpacity
                  key={suggestion.text + "_" + idx}
                  style={styles.suggestionContainer}
                  onPress={() => {
                    tagAdded(suggestion);
                  }}
                >
                  <FontAwesome
                    name={getIconName(suggestion.type)}
                    size={16}
                    color="hsl(0, 0%, 90%)"
                  />
                  <Text style={styles.suggestionLabel}>{suggestion.text}</Text>
                </TouchableOpacity>
              ))}

            </ScrollView>


          </View>
        )}
      </View>

      <View style={{ flex: 1 }} >

        <ScrollView keyboardShouldPersistTaps="handled">
          {searchResults.map((result: SearchResultItem, idx) => {
            switch (result.type) {
              case "PERSON":
                return (
                  <View key={result.data.id + "_" + idx} style={styles.personRow}>
                    <View style={styles.avatarCircle}>
                    <FontAwesome name="user" size={22} color="#ccc" />
                  </View>

                  {/* Text */}
                  <View style={{ flex: 1 }}>
                    <Text style={styles.personName}>{result.data.name || "Unbekannt"} ({"25"})</Text>
                    <Text style={styles.personMeta}>
                     aus: {"unterscheidlichen Shows"}
                    </Text>
                  </View>

                  {/* Chevron */}
                  <FontAwesome name="chevron-right" size={14} color="#888" />
                  </View>
                );
              case "SHOW":
                return (
                  <View key={result.data.id + "_" + idx}>
                    <Text style={{ color: "skyblue" }}>
                      {result.data.title} (Show)
                    </Text>
                  </View>
                );
              default:
                return null;
            }
          })}
        </ScrollView>


      </View>
    </View>
  );
}
