import { useLocalSearchParams, useRouter } from "expo-router";
import { useMemo, useState } from "react";
import { FlatList, Pressable, ScrollView, View } from "react-native";
import { SORT_LABEL, applyFilter, blank, chips, clearFilters, filterModel, fromQuery, removeChip, run, search, type SearchState, type SortKey } from "@sheikbras/domain";
import { Button, Chip, Icon, Sheet, T, colors } from "@sheikbras/ui-native";
import { Card, Screen } from "../components/common";
import { FilterList } from "../components/FilterList";

function initial(p: { q?: string; c?: string; frete?: string }): SearchState {
  let s = p.q ? fromQuery(p.q) : blank(); if (p.c) s = applyFilter(s, "cat", p.c); if (p.frete) s = applyFilter(s, "free", "1", true); return s;
}
export default function Busca() {
  const r = useRouter(); const params = useLocalSearchParams<{ q?: string; c?: string; frete?: string; sheet?: string }>();
  const [S, setS] = useState<SearchState>(() => initial(params)); const [n, setN] = useState(12);
  const [sheet, setSheet] = useState<null | "f" | "s">(params.sheet === "f" ? "f" : null); const [draft, setDraft] = useState<SearchState>(S);
  const list = useMemo(() => search(S), [S]); const cs = chips(S); const set = (s: SearchState) => { setS(s); setN(12); };
  const quick: [string, boolean, () => void][] = [["Frete grátis", S.free, () => set(applyFilter(S, "free", "1", !S.free))], ["Em oferta", S.offer, () => set(applyFilter(S, "offer", "1", !S.offer))], ["4★ ou mais", S.rating === 4, () => set(applyFilter(S, "rating", S.rating === 4 ? "0" : "4"))], ["Verificados", S.ver, () => set(applyFilter(S, "ver", "1", !S.ver))]];
  const bb = (label: string, icon: string, onPress: () => void, badge?: number) => (
    <Pressable accessibilityRole="button" accessibilityLabel={label} onPress={onPress} style={{ minHeight: 44, paddingHorizontal: 16, borderRadius: 12, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.surface, flexDirection: "row", alignItems: "center", gap: 8 }}>
      <Icon name={icon} size={18} /><T v="small" w={600}>{label}</T>{badge ? <View style={{ minWidth: 20, height: 20, borderRadius: 10, backgroundColor: colors.primary, alignItems: "center", justifyContent: "center", paddingHorizontal: 5 }}><T v="cap" w={700} color="#fff">{badge}</T></View> : null}
    </Pressable>);
  const header = (
    <View style={{ gap: 12, paddingBottom: 12 }}>
      <View style={{ flexDirection: "row", gap: 8 }}>{bb("Filtros", "sliders", () => { setDraft(S); setSheet("f"); }, cs.length)}{bb("Ordenar", "sort", () => setSheet("s"))}<View style={{ flex: 1 }} /><Pressable accessibilityRole="button" accessibilityLabel="Alternar grade e lista" onPress={() => set({ ...S, view: S.view === "grid" ? "list" : "grid" })} style={{ width: 44, height: 44, borderRadius: 12, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.surface, alignItems: "center", justifyContent: "center" }}><Icon name={S.view === "grid" ? "menu" : "grid"} size={18} /></Pressable></View>
      <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 8 }}>{quick.map(([l, on, f]) => <Chip key={l} label={l} on={on} onPress={f} />)}</ScrollView>
      {cs.length ? <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8, alignItems: "center" }}>{S.q ? <T v="cap" color={colors.muted}>Entendemos:</T> : null}{cs.map((c) => <Chip key={c.key} strong={c.label || undefined} label={c.value} on onRemove={() => set(removeChip(S, c.key))} />)}<Chip label="Limpar tudo" onPress={() => set(clearFilters(S))} /></View> : null}
      <T v="small" color={colors.muted}>{list.length} {list.length === 1 ? "resultado" : "resultados"}</T>
    </View>);
  return (
    <Screen>
      <View style={{ flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: 8, height: 56, backgroundColor: colors.surface, borderBottomWidth: 1, borderBottomColor: colors.border }}>
        <Pressable accessibilityRole="button" accessibilityLabel="Voltar" onPress={() => r.back()} style={{ width: 44, height: 44, alignItems: "center", justifyContent: "center" }}><Icon name="cl" /></Pressable>
        <View style={{ flex: 1, height: 44, borderRadius: 999, borderWidth: 1, borderColor: colors.border, backgroundColor: colors.bg, flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 14 }}><Icon name="search" size={20} color={colors.muted} /><T v="body" style={{ fontSize: 15, flex: 1 }} numberOfLines={1}>{S.q || S.c || "Todos os produtos"}</T></View>
      </View>
      <FlatList key={S.view} data={list.slice(0, n)} numColumns={S.view === "grid" ? 2 : 1} keyExtractor={(p) => String(p.id)} contentContainerStyle={{ padding: 16, paddingBottom: 32 }} columnWrapperStyle={S.view === "grid" ? { gap: 12 } : undefined} ItemSeparatorComponent={() => <View style={{ height: 12 }} />}
        ListHeaderComponent={header} renderItem={({ item }) => <View style={{ flex: 1 }}><Card p={item} /></View>} onEndReached={() => list.length > n && setN(n + 12)} onEndReachedThreshold={0.6}
        ListEmptyComponent={<View style={{ alignItems: "center", gap: 12, paddingVertical: 48 }}><T v="h3">Nenhum resultado encontrado</T><T v="small" color={colors.muted} style={{ textAlign: "center" }}>Remova algum filtro ou tente outro termo.</T>{cs.length ? <Button label="Limpar filtros" full={false} variant="secondary" onPress={() => set(clearFilters(S))} /> : null}</View>} />
      <Sheet visible={sheet === "f"} tall onClose={() => setSheet(null)} title="Filtros" footer={<><Button label="Limpar" variant="secondary" style={{ flex: 1 }} onPress={() => setDraft(clearFilters(draft))} /><Button label={`Ver ${run(draft).length} resultados`} style={{ flex: 1.4 }} onPress={() => { set(draft); setSheet(null); }} /></>}>
        <FilterList groups={filterModel(draft)} onChange={(f, v, c) => setDraft(applyFilter(draft, f, v, c))} />
      </Sheet>
      <Sheet visible={sheet === "s"} onClose={() => setSheet(null)} title="Ordenar por">
        <View style={{ paddingBottom: 16 }}>{(Object.keys(SORT_LABEL) as SortKey[]).map((k) => <Pressable key={k} accessibilityRole="radio" accessibilityState={{ checked: S.sort === k }} onPress={() => { set({ ...S, sort: k }); setSheet(null); }} style={{ minHeight: 52, flexDirection: "row", alignItems: "center", gap: 12 }}><View style={{ width: 22, height: 22, borderRadius: 11, borderWidth: 1.5, borderColor: S.sort === k ? colors.primary : colors.border, alignItems: "center", justifyContent: "center" }}>{S.sort === k ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: colors.primary }} /> : null}</View><T v="body" style={{ fontSize: 15 }}>{SORT_LABEL[k]}</T></Pressable>)}</View>
      </Sheet>
    </Screen>
  );
}
