import React, { useState, useMemo } from 'react';
import {
  View, Text, ScrollView, TouchableOpacity, StyleSheet, Linking,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useBooking } from '../context/BookingContext';
import { COLORS, FONTS, FONT_SIZE, SPACING } from '../theme';
import { testimonialsData } from '../data/testimonials';

type Filter = 'all' | 'hypnosis' | 'trauma' | 'coaching' | 'mindfulness';

const FILTERS: { id: Filter; label: string }[] = [
  { id: 'all',         label: 'All' },
  { id: 'hypnosis',    label: 'Hypnosis' },
  { id: 'trauma',      label: 'Trauma & EMDR' },
  { id: 'coaching',    label: 'Coaching' },
  { id: 'mindfulness', label: 'Mindfulness' },
];

const HYPNOSIS_TAGS    = ['Hypnotherapy', 'Hypnosis', 'Yager Therapy', 'Subconscious Healing', 'Self-Sabotage', 'Self-Esteem'];
const TRAUMA_TAGS      = ['Trauma Counseling', 'EMDR', 'Panic Attacks', 'Grief Counseling', 'Inner Safety'];
const COACHING_TAGS    = ['Life Coaching', 'Transitions', 'Kigali In-Person', 'Procrastination', 'Focus', 'Performance Coaching', 'Self-Confidence'];
const MINDFULNESS_TAGS = ['Mindfulness', 'Breath Work', 'Embodiment', 'Body Awareness', 'Somatic Healing', 'Burnout Support', 'Stress Management', 'Anxiety', 'Relationships'];

export default function TestimonialsScreen() {
  const [filter, setFilter] = useState<Filter>('all');
  const { openBookingModal } = useBooking();
  const openWhatsApp = () => Linking.openURL('https://wa.me/250790000000');

  const filtered = useMemo(() => {
    if (filter === 'all') return testimonialsData;
    return testimonialsData.filter(t => {
      if (filter === 'hypnosis')    return t.tags.some(tag => HYPNOSIS_TAGS.includes(tag));
      if (filter === 'trauma')      return t.tags.some(tag => TRAUMA_TAGS.includes(tag));
      if (filter === 'coaching')    return t.tags.some(tag => COACHING_TAGS.includes(tag));
      if (filter === 'mindfulness') return t.tags.some(tag => MINDFULNESS_TAGS.includes(tag));
      return true;
    });
  }, [filter]);

  return (
    <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>

      {/* Header */}
      <View style={styles.pageHeader}>
        <Text style={styles.overline}>Client Success</Text>
        <Text style={styles.pageTitle}>Testimonials</Text>
        <Text style={styles.pageSubtitle}>
          Read what clients say about working with Manuel Haeussler.
        </Text>
        <View style={styles.divider} />
        <Text style={styles.privacyNote}>
          To respect client confidentiality, the initials or names used below have been configured in line with client consent. Each testimonial is a genuine reflection of deep personal work.
        </Text>
      </View>

      {/* Filter Bar */}
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        style={styles.filterBar}
        contentContainerStyle={styles.filterBarContent}
      >
        {FILTERS.map(f => {
          const count = f.id === 'all' ? testimonialsData.length
            : testimonialsData.filter(t => {
                if (f.id === 'hypnosis')    return t.tags.some(tag => HYPNOSIS_TAGS.includes(tag));
                if (f.id === 'trauma')      return t.tags.some(tag => TRAUMA_TAGS.includes(tag));
                if (f.id === 'coaching')    return t.tags.some(tag => COACHING_TAGS.includes(tag));
                if (f.id === 'mindfulness') return t.tags.some(tag => MINDFULNESS_TAGS.includes(tag));
                return false;
              }).length;
          return (
            <TouchableOpacity
              key={f.id}
              style={[styles.filterBtn, filter === f.id && styles.filterBtnActive]}
              onPress={() => setFilter(f.id)}
            >
              <Text style={[styles.filterText, filter === f.id && styles.filterTextActive]}>
                {f.label}
              </Text>
              <View style={[styles.filterCount, filter === f.id && styles.filterCountActive]}>
                <Text style={[styles.filterCountText, filter === f.id && styles.filterCountTextActive]}>
                  {count}
                </Text>
              </View>
            </TouchableOpacity>
          );
        })}
      </ScrollView>

      {/* Cards */}
      <View style={styles.grid}>
        {filtered.map(t => (
          <View key={t.id} style={styles.card}>
            <View style={styles.cardQuoteIcon}>
              <Ionicons name="chatbubble-ellipses" size={40} color={COLORS.slate100} />
            </View>
            <Text style={styles.shortQuote}>"{t.shortQuote}"</Text>
            <View style={styles.cardDivider} />
            <Text style={styles.cardText}>{t.text}</Text>
            <View style={styles.cardFooter}>
              <View style={styles.cardMeta}>
                <Text style={styles.cardName}>— {t.name}</Text>
                {t.age > 0 && <Text style={styles.cardAge}>, {t.age} years old</Text>}
              </View>
              <View style={styles.verifiedBadge}>
                <Text style={styles.verifiedText}>Verified</Text>
              </View>
            </View>
            <View style={styles.tagsRow}>
              {t.tags.map((tag, i) => (
                <View key={i} style={styles.tag}>
                  <Text style={styles.tagText}>{tag}</Text>
                </View>
              ))}
            </View>
          </View>
        ))}

        {filtered.length === 0 && (
          <View style={styles.emptyState}>
            <Ionicons name="heart-outline" size={40} color={COLORS.slate300} />
            <Text style={styles.emptyText}>No testimonials match this filter.</Text>
            <TouchableOpacity onPress={() => setFilter('all')}>
              <Text style={styles.emptyAction}>Reset filters</Text>
            </TouchableOpacity>
          </View>
        )}
      </View>

      {/* CTA */}
      <View style={styles.cta}>
        <Text style={styles.ctaTitle}>Ready to Make Your Own Breakthroughs?</Text>
        <Text style={styles.ctaBody}>
          Every recovery begins with a single step. Let's find your unique waves of healing.
        </Text>
        <View style={styles.rowBtns}>
          <TouchableOpacity style={styles.btnDark} onPress={openBookingModal}>
            <Ionicons name="call" size={14} color={COLORS.white} />
            <Text style={styles.btnDarkText}>Book FREE Call</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.btnOutline} onPress={openWhatsApp}>
            <Text style={styles.btnOutlineText}>WhatsApp</Text>
          </TouchableOpacity>
        </View>
      </View>

    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container:          { flex: 1, backgroundColor: COLORS.white },
  pageHeader:         { padding: SPACING.lg, paddingVertical: SPACING.xl, gap: SPACING.sm, backgroundColor: COLORS.slate50, borderBottomWidth: 1, borderBottomColor: COLORS.slate200 },
  overline:           { fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs, color: COLORS.slate400, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 3 },
  pageTitle:          { fontFamily: FONTS.heading, fontSize: FONT_SIZE.xxl, fontWeight: '900', color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: -0.5 },
  pageSubtitle:       { fontFamily: FONTS.serif, fontSize: FONT_SIZE.base, color: COLORS.slate500, fontStyle: 'italic' },
  divider:            { width: 48, height: 2, backgroundColor: COLORS.slate900 },
  privacyNote:        { fontFamily: FONTS.serif, fontSize: FONT_SIZE.xs, color: COLORS.slate500, lineHeight: 18 },
  filterBar:          { borderBottomWidth: 1, borderBottomColor: COLORS.slate200, backgroundColor: COLORS.slate50 },
  filterBarContent:   { paddingHorizontal: SPACING.md, paddingVertical: SPACING.sm, gap: SPACING.sm },
  filterBtn:          { flexDirection: 'row', alignItems: 'center', gap: SPACING.xs, paddingHorizontal: SPACING.md, paddingVertical: SPACING.xs + 2, borderWidth: 1, borderColor: COLORS.slate200, backgroundColor: COLORS.white },
  filterBtnActive:    { backgroundColor: COLORS.slate900, borderColor: COLORS.slate900 },
  filterText:         { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, color: COLORS.slate800, textTransform: 'uppercase', letterSpacing: 1 },
  filterTextActive:   { color: COLORS.white },
  filterCount:        { backgroundColor: COLORS.slate100, paddingHorizontal: 5, paddingVertical: 1 },
  filterCountActive:  { backgroundColor: COLORS.white },
  filterCountText:    { fontFamily: FONTS.mono, fontSize: FONT_SIZE.xxs, color: COLORS.slate500 },
  filterCountTextActive: { color: COLORS.slate900 },
  grid:               { padding: SPACING.lg, gap: SPACING.lg },
  card:               { backgroundColor: COLORS.white, borderWidth: 1, borderColor: COLORS.slate200, padding: SPACING.lg, gap: SPACING.md },
  cardQuoteIcon:      { position: 'absolute', top: SPACING.md, right: SPACING.md, opacity: 0.6 },
  shortQuote:         { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.base, color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: 0.5, lineHeight: 22, paddingRight: SPACING.xl },
  cardDivider:        { height: 1, backgroundColor: COLORS.slate100 },
  cardText:           { fontFamily: FONTS.serif, fontSize: FONT_SIZE.sm, color: COLORS.slate500, lineHeight: 20 },
  cardFooter:         { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  cardMeta:           { flexDirection: 'row', alignItems: 'center' },
  cardName:           { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xs, color: COLORS.slate900 },
  cardAge:            { fontFamily: FONTS.serif, fontSize: FONT_SIZE.xs, color: COLORS.slate400 },
  verifiedBadge:      { backgroundColor: COLORS.slate100, paddingHorizontal: SPACING.sm, paddingVertical: 2 },
  verifiedText:       { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, color: COLORS.slate600, textTransform: 'uppercase', letterSpacing: 1 },
  tagsRow:            { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING.xs },
  tag:                { backgroundColor: COLORS.slate50, borderWidth: 1, borderColor: COLORS.slate100, paddingHorizontal: SPACING.sm, paddingVertical: 3 },
  tagText:            { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, color: COLORS.slate600, textTransform: 'uppercase', letterSpacing: 1 },
  emptyState:         { alignItems: 'center', paddingVertical: SPACING.xxl, gap: SPACING.sm },
  emptyText:          { fontFamily: FONTS.serif, fontSize: FONT_SIZE.sm, color: COLORS.slate400, fontStyle: 'italic' },
  emptyAction:        { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.sm, color: COLORS.slate900, textDecorationLine: 'underline' },
  cta:                { backgroundColor: COLORS.slate50, padding: SPACING.lg, paddingVertical: SPACING.xl, gap: SPACING.md, borderTopWidth: 1, borderTopColor: COLORS.slate200 },
  ctaTitle:           { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xl, color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: -0.5 },
  ctaBody:            { fontFamily: FONTS.serif, fontSize: FONT_SIZE.sm, color: COLORS.slate500, lineHeight: 20 },
  rowBtns:            { flexDirection: 'row', gap: SPACING.sm },
  btnDark:            { flex: 1, backgroundColor: COLORS.slate900, paddingVertical: SPACING.sm + 4, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: SPACING.xs },
  btnDarkText:        { color: COLORS.white, fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, textTransform: 'uppercase', letterSpacing: 2 },
  btnOutline:         { flex: 1, borderWidth: 1, borderColor: COLORS.slate200, paddingVertical: SPACING.sm + 4, alignItems: 'center', justifyContent: 'center' },
  btnOutlineText:     { color: COLORS.slate900, fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, textTransform: 'uppercase', letterSpacing: 2 },
});
