import React, {useCallback, useEffect, useState} from 'react';
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Keyboard,
  KeyboardAvoidingView,
  Platform,
  Pressable,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import type {NativeStackScreenProps} from '@react-navigation/native-stack';
import {Colors} from '@app/theme/colors';
import {useRecentSearchStore} from '@app/store/recentSearchStore';
import {useAuthStore} from '@app/store/authStore';
import type {RootStackParamList} from '@app/navigation/types';

type Props = NativeStackScreenProps<RootStackParamList, 'Search'>;

const POPULAR: string[] = ['iPhone', 'AirPods', 'Nintendo Switch', 'PS5', 'iPad', 'ルンバ', 'ダイソン', 'Fire TV Stick'];

export const SearchScreen: React.FC<Props> = ({navigation}) => {
  const [keyword, setKeyword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const recent = useRecentSearchStore(s => s.recent);
  const loadRecent = useRecentSearchStore(s => s.load);
  const clearRecent = useRecentSearchStore(s => s.clear);
  const pushRecent = useRecentSearchStore(s => s.push);
  const user = useAuthStore(s => s.user);

  useEffect(() => {
    loadRecent();
  }, [loadRecent]);

  const onSubmit = useCallback(
    async (q?: string) => {
      const k = (q ?? keyword).trim();
      if (!k) {
        Alert.alert('キーワードを入力してください');
        return;
      }
      setSubmitting(true);
      try {
        await pushRecent(k);
        Keyboard.dismiss();
        navigation.navigate('Results', {keyword: k});
      } finally {
        setSubmitting(false);
      }
    },
    [keyword, navigation, pushRecent],
  );

  return (
    <SafeAreaView style={styles.safe} edges={['top']}>
      <KeyboardAvoidingView style={{flex: 1}} behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
        <View style={styles.header}>
          <Text style={styles.title}>価格比較</Text>
          <Pressable onPress={() => navigation.navigate('Account')} hitSlop={12}>
            <Text style={styles.headerLink}>{user ? user.name : 'ログイン'}</Text>
          </Pressable>
        </View>

        <View style={styles.inputRow}>
          <TextInput
            style={styles.input}
            placeholder="商品名で検索 (例: iPhone 16)"
            placeholderTextColor={Colors.subText}
            value={keyword}
            onChangeText={setKeyword}
            returnKeyType="search"
            onSubmitEditing={() => onSubmit()}
            autoFocus
          />
          <Pressable
            style={({pressed}) => [styles.searchBtn, pressed && {opacity: 0.8}]}
            onPress={() => onSubmit()}
            disabled={submitting}
          >
            {submitting ? (
              <ActivityIndicator color="#FFF" />
            ) : (
              <Text style={styles.searchBtnText}>検索</Text>
            )}
          </Pressable>
        </View>

        <FlatList
          data={[
            {type: 'section', title: '最近の検索', data: recent, showClear: true},
            {type: 'section', title: '人気のキーワード', data: POPULAR, showClear: false},
          ] as const}
          keyExtractor={(item, i) => `s-${i}-${item.title}`}
          renderItem={({item}) => (
            <View style={styles.section}>
              <View style={styles.sectionHeader}>
                <Text style={styles.sectionTitle}>{item.title}</Text>
                {item.showClear && item.data.length > 0 ? (
                  <Pressable onPress={clearRecent} hitSlop={8}>
                    <Text style={styles.clear}>クリア</Text>
                  </Pressable>
                ) : null}
              </View>
              <View style={styles.chipWrap}>
                {item.data.length === 0 ? (
                  <Text style={styles.empty}>まだ検索履歴はありません</Text>
                ) : (
                  item.data.map(k => (
                    <Pressable
                      key={k}
                      style={({pressed}) => [styles.chip, pressed && {opacity: 0.7}]}
                      onPress={() => onSubmit(k)}
                    >
                      <Text style={styles.chipText}>{k}</Text>
                    </Pressable>
                  ))
                )}
              </View>
            </View>
          )}
          contentContainerStyle={{paddingBottom: 40}}
        />
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safe: {flex: 1, backgroundColor: Colors.bg},
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingTop: 8,
    paddingBottom: 4,
  },
  title: {fontSize: 22, fontWeight: '700', color: Colors.text},
  headerLink: {color: Colors.primary, fontSize: 14, fontWeight: '600'},
  inputRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  input: {
    flex: 1,
    height: 44,
    backgroundColor: Colors.card,
    borderWidth: 1,
    borderColor: Colors.border,
    borderRadius: 10,
    paddingHorizontal: 12,
    color: Colors.text,
    fontSize: 16,
  },
  searchBtn: {
    height: 44,
    paddingHorizontal: 20,
    borderRadius: 10,
    backgroundColor: Colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  searchBtnText: {color: '#FFF', fontSize: 16, fontWeight: '700'},
  section: {paddingHorizontal: 16, paddingTop: 16},
  sectionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 8,
  },
  sectionTitle: {fontSize: 14, fontWeight: '700', color: Colors.subText},
  clear: {color: Colors.primary, fontSize: 13},
  chipWrap: {flexDirection: 'row', flexWrap: 'wrap', gap: 8},
  chip: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 999,
    backgroundColor: Colors.card,
    borderWidth: 1,
    borderColor: Colors.border,
  },
  chipText: {color: Colors.text, fontSize: 13},
  empty: {color: Colors.subText, fontSize: 13, fontStyle: 'italic'},
});
