import { useEffect, useState } from 'react'
import {
  View, Text, FlatList, TouchableOpacity,
  ActivityIndicator, RefreshControl, StyleSheet,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useRouter } from 'expo-router'
import { ChevronRight } from 'lucide-react-native'
import { apiFetch } from '@/lib/api'
import { ENDPOINTS } from '@/lib/config'
import { C } from '../_layout'

interface Notebook {
  id: string
  name: string
  icon: string | null
  _count: { notes: number }
}

export default function NotebooksScreen() {
  const [notebooks, setNotebooks] = useState<Notebook[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const router = useRouter()

  const load = async () => {
    try {
      const res = await apiFetch(ENDPOINTS.notebooks)
      if (res.ok) {
        const data = await res.json()
        setNotebooks(data.notebooks ?? [])
      }
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

  useEffect(() => { load() }, [])

  if (loading) {
    return (
      <SafeAreaView style={[s.safe, { alignItems: 'center', justifyContent: 'center' }]}>
        <ActivityIndicator color={C.brand} />
      </SafeAreaView>
    )
  }

  return (
    <SafeAreaView style={s.safe}>
      <View style={s.header}>
        <Text style={s.title}>Carnets</Text>
      </View>
      <FlatList
        data={notebooks}
        keyExtractor={(item) => item.id}
        contentContainerStyle={s.list}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); load() }} tintColor={C.brand} />}
        renderItem={({ item }) => (
          <TouchableOpacity onPress={() => router.push(`/notebook/${item.id}`)} style={s.card}>
            <Text style={s.icon}>{item.icon ?? '📓'}</Text>
            <View style={{ flex: 1 }}>
              <Text style={s.cardTitle}>{item.name}</Text>
              <Text style={s.cardMeta}>{item._count?.notes ?? 0} notes</Text>
            </View>
            <ChevronRight size={16} color={C.concrete} />
          </TouchableOpacity>
        )}
        ListEmptyComponent={<Text style={s.empty}>Aucun carnet.</Text>}
      />
    </SafeAreaView>
  )
}

const s = StyleSheet.create({
  safe: { flex: 1, backgroundColor: C.paper },
  header: { paddingHorizontal: 20, paddingTop: 16, paddingBottom: 8 },
  title: { fontSize: 22, fontStyle: 'italic', fontWeight: '700', color: C.ink },
  list: { paddingHorizontal: 20, paddingTop: 8, paddingBottom: 32 },
  card: { flexDirection: 'row', alignItems: 'center', backgroundColor: C.white, borderWidth: 1, borderColor: C.border, borderRadius: 16, padding: 16, marginBottom: 10 },
  icon: { fontSize: 24, marginRight: 12 },
  cardTitle: { fontSize: 15, fontWeight: '600', color: C.ink },
  cardMeta: { fontSize: 12, color: C.concrete, marginTop: 2 },
  empty: { textAlign: 'center', color: C.concrete, marginTop: 48 },
})
