import React, { useMemo, useState } from 'react';
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { ErrBox, Loading, Screen, SearchInput, SrcNote } from '../components/ui';
import { load } from '../lib/api';
import { C } from '../lib/theme';
import type { TraitsResponse } from '../lib/types';
import { useLoad } from '../lib/use-load';

export default function Dna() {
  const [cat, setCat] = useState('all');
  const [q, setQ] = useState('');
  const { data, err, loading, refresh } = useLoad(() => load<TraitsResponse>('traits'));

  const cats = useMemo(
    () => (data ? ['all', ...new Set(data.traits.map((t) => t.category))] : ['all']),
    [data],
  );

  let body: React.ReactNode = null;
  if (loading && !data) body = <Loading />;
  else if (err) body = <ErrBox msg={err} />;
  else if (data) {
    const ql = q.trim().toLowerCase();
    const subset = data.traits.filter(
      (t) =>
        (cat === 'all' || t.category === cat) &&
        (!ql ||
          t.trait.toLowerCase().includes(ql) ||
          (t.result || '').toLowerCase().includes(ql)),
    );

    body = (
      <>
        <SearchInput value={q} onChange={setQ} placeholder={`Search ${data.trait_count} traits…`} />
        <ScrollView horizontal showsHorizontalScrollIndicator={false}
          style={{ marginBottom: 8 }} contentContainerStyle={{ gap: 6, paddingBottom: 6 }}>
          {cats.map((c) => (
            <Pressable key={c} onPress={() => setCat(c)}
              style={[s.chip, cat === c && s.chipActive]}>
              <Text style={{
                fontSize: 12, color: cat === c ? C.accent : C.muted,
                textTransform: 'capitalize',
              }}>
                {c}
              </Text>
            </Pressable>
          ))}
        </ScrollView>
        {subset.map((t) => (
          <View key={t.trait} style={s.trait}>
            <View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 10, alignItems: 'baseline' }}>
              <Text style={{ fontSize: 13, fontWeight: '500', color: C.text, flex: 1 }}>{t.trait}</Text>
              <Text style={{ fontSize: 10, color: C.dim, letterSpacing: 0.5, textTransform: 'uppercase' }}>
                {t.category}
              </Text>
            </View>
            <Text style={{ fontSize: 12, color: C.accent, marginTop: 2 }}>{t.result}</Text>
            {t.position_estimate != null && t.scale ? (
              <View style={{ marginTop: 9 }}>
                <View style={s.track}>
                  <View style={[s.dot, { left: `${Math.round(t.position_estimate * 100)}%` }]} />
                </View>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 4 }}>
                  <Text style={{ fontSize: 10, color: C.dim }}>{t.scale.left}</Text>
                  <Text style={{ fontSize: 10, color: C.dim }}>{t.scale.right}</Text>
                </View>
              </View>
            ) : null}
          </View>
        ))}
        {!subset.length ? (
          <Text style={{ color: C.muted, fontSize: 13, textAlign: 'center', padding: 24 }}>
            No traits match.
          </Text>
        ) : null}
        <SrcNote>{data.source} — slider positions are visual estimates from the report.</SrcNote>
      </>
    );
  }

  return <Screen onRefresh={refresh}>{body}</Screen>;
}

const s = StyleSheet.create({
  chip: {
    paddingVertical: 5, paddingHorizontal: 12, borderRadius: 16, borderWidth: 1,
    borderColor: C.border, backgroundColor: C.surface,
  },
  chipActive: { borderColor: C.accent, backgroundColor: C.accentDim },
  trait: {
    backgroundColor: C.surface, borderWidth: 1, borderColor: C.border, borderRadius: 12,
    paddingVertical: 12, paddingHorizontal: 14, marginBottom: 8,
  },
  track: { height: 4, borderRadius: 2, backgroundColor: C.surface2 },
  dot: {
    position: 'absolute', top: -4, marginLeft: -5.5, width: 11, height: 11,
    borderRadius: 5.5, backgroundColor: C.accent, borderWidth: 2, borderColor: C.bg,
  },
});
