import { useRouter } from "expo-router";
import type { ReactNode } from "react";
import { Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { Product } from "@sheikbras/domain";
import { Icon, ProductCard, T, colors } from "@sheikbras/ui-native";
import { useStore } from "../lib/store";

export function Screen({ children, edges = ["top"] }: { children: ReactNode; edges?: ("top" | "bottom")[] }) {
  const i = useSafeAreaInsets();
  return <View style={{ flex: 1, backgroundColor: colors.bg, paddingTop: edges.includes("top") ? i.top : 0, paddingBottom: edges.includes("bottom") ? i.bottom : 0 }}>{children}</View>;
}
export function TopBar({ title, right }: { title: string; right?: ReactNode }) {
  const r = useRouter();
  return (
    <View style={{ flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 8, height: 52, backgroundColor: colors.surface, borderBottomWidth: 1, borderBottomColor: colors.border }}>
      <Pressable accessibilityRole="button" accessibilityLabel="Voltar" onPress={() => r.back()} hitSlop={8} style={{ width: 44, height: 44, alignItems: "center", justifyContent: "center" }}><Icon name="cl" /></Pressable>
      <T v="h3" style={{ flex: 1 }} numberOfLines={1}>{title}</T>{right}
    </View>
  );
}
export function Toast() {
  const { toast } = useStore(); const i = useSafeAreaInsets();
  if (!toast) return null;
  return <View pointerEvents="none" style={{ position: "absolute", left: 16, right: 16, bottom: i.bottom + 76, alignItems: "center" }}><View style={{ backgroundColor: colors.text, borderRadius: 12, paddingHorizontal: 16, paddingVertical: 10 }}><T v="small" w={500} color={colors.bg}>{toast}</T></View></View>;
}
/** Card ligado ao estado do app. */
export function Card({ p, width }: { p: Product; width?: number | string }) {
  const r = useRouter(); const { favs, toggleFav, notify } = useStore();
  return <ProductCard product={p} width={width} onPress={() => r.push(`/p/${p.id}`)} favorite={favs.includes(p.id)} onFavorite={(on) => { toggleFav(p.id, on); notify(on ? "Salvo nos favoritos" : "Removido dos favoritos"); }} />;
}
export const SectionTitle = ({ children, action, onAction }: { children: string; action?: string; onAction?: () => void }) => (
  <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "baseline", paddingHorizontal: 16, marginBottom: 12 }}>
    <T v="h2">{children}</T>{action ? <Pressable onPress={onAction} hitSlop={8}><T v="small" w={600} color={colors.primary}>{action}</T></Pressable> : null}
  </View>
);
