import { useEffect, useState } from 'react'
import {
  View, Text, ScrollView, TouchableOpacity,
  ActivityIndicator, RefreshControl,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useRouter } from 'expo-router'
import { CalendarDays, Sparkles, BookOpen } from 'lucide-react-native'
import { apiFetch } from '@/lib/api'
import { ENDPOINTS } from '@/lib/config'
import { useAuthStore } from '@/lib/store'

interface Note {
  id: string
  title: string
  updatedAt: string
  notebookName?: string
  color?: string
}

export default function HomeScreen() {
  const user = useAuthStore((s) => s.user)
  const [recentNotes, setRecentNotes] = useState<Note[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const router = useRouter()

  const load = async () => {
    try {
      const res = await apiFetch(ENDPOINTS.notes())
      if (res.ok) {
        const data = await res.json()
        setRecentNotes((data.notes ?? []).slice(0, 10))
      }
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

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

  const handleDailyNote = async () => {
    const res = await apiFetch(ENDPOINTS.dailyNote)
    if (res.ok) {
      const data = await res.json()
      router.push(`/note/${data.id}`)
    }
  }

  const formatDate = (iso: string) => {
    const d = new Date(iso)
    return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })
  }

  return (
    <SafeAreaView className="flex-1 bg-paper">
      <ScrollView
        className="flex-1"
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); load() }} tintColor="#A47148" />}
      >
        {/* Header */}
        <View className="px-5 pt-4 pb-2">
          <Text className="text-2xl font-serif italic text-ink">
            Bonjour{user?.name ? `, ${user.name.split(' ')[0]}` : ''} 👋
          </Text>
          <Text className="text-[13px] text-concrete mt-0.5">
            {new Date().toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long' })}
          </Text>
        </View>

        {/* Quick actions */}
        <View className="flex-row gap-3 px-5 mt-4">
          <TouchableOpacity
            onPress={handleDailyNote}
            className="flex-1 bg-white border border-border rounded-2xl p-4 items-center gap-2"
          >
            <CalendarDays size={22} color="#A47148" />
            <Text className="text-[12px] font-semibold text-ink">Note du jour</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => router.push('/(tabs)/notebooks')}
            className="flex-1 bg-white border border-border rounded-2xl p-4 items-center gap-2"
          >
            <BookOpen size={22} color="#A47148" />
            <Text className="text-[12px] font-semibold text-ink">Carnets</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => router.push('/(tabs)/search')}
            className="flex-1 bg-white border border-border rounded-2xl p-4 items-center gap-2"
          >
            <Sparkles size={22} color="#A47148" />
            <Text className="text-[12px] font-semibold text-ink">Recherche IA</Text>
          </TouchableOpacity>
        </View>

        {/* Recent notes */}
        <View className="px-5 mt-6">
          <Text className="text-[11px] font-bold uppercase tracking-widest text-concrete mb-3">
            Récentes
          </Text>

          {loading ? (
            <ActivityIndicator color="#A47148" />
          ) : recentNotes.length === 0 ? (
            <Text className="text-concrete text-[14px]">Aucune note pour l'instant.</Text>
          ) : (
            recentNotes.map((note) => (
              <TouchableOpacity
                key={note.id}
                onPress={() => router.push(`/note/${note.id}`)}
                className="bg-white border border-border rounded-2xl p-4 mb-2.5 active:opacity-70"
              >
                <Text className="text-[15px] font-semibold text-ink" numberOfLines={1}>
                  {note.title || 'Sans titre'}
                </Text>
                <View className="flex-row items-center gap-2 mt-1">
                  {note.notebookName && (
                    <Text className="text-[11px] text-concrete">{note.notebookName}</Text>
                  )}
                  <Text className="text-[11px] text-concrete/60">{formatDate(note.updatedAt)}</Text>
                </View>
              </TouchableOpacity>
            ))
          )}
        </View>

        <View className="h-8" />
      </ScrollView>
    </SafeAreaView>
  )
}
