// app/auth/register/category.tsx
import { auth_api } from '@/screens/auth/login/lib/api';
import { products_api } from '@/screens/home/lib/api';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Stack, useLocalSearchParams, useRouter } from 'expo-router';
import { Check } from 'lucide-react-native';
import React from 'react';
import { ScrollView, StyleSheet, Text, TouchableOpacity } from 'react-native';

export default function CategorySelectScreen() {
  const router = useRouter();
  const { phone, stir, person_type } = useLocalSearchParams<{
    phone: string;
    stir: string;
    person_type: 'band' | 'ytt';
  }>();

  const [selected, setSelected] = React.useState<number | null>(null);

  const { data } = useQuery({
    queryKey: ['categories'],
    queryFn: () => products_api.getCategorys(),
  });

  const { mutate, isPending } = useMutation({
    mutationFn: (body: {
      phone: string;
      stir: string;
      person_type: string;
      activate_types: number[];
    }) => auth_api.register(body),
    onSuccess: () => router.replace('/'),
  });

  return (
    <>
      <Stack.Screen options={{ title: 'Yo‘nalishni tanlang' }} />

      <ScrollView contentContainerStyle={styles.container}>
        {data?.data?.data.map((c: any) => {
          const active = selected === c.id;
          return (
            <TouchableOpacity key={c.id} style={styles.item} onPress={() => setSelected(c.id)}>
              <Text style={styles.text}>{c.name}</Text>
              {active && <Check size={20} color="#2563eb" />}
            </TouchableOpacity>
          );
        })}
      </ScrollView>

      <TouchableOpacity
        disabled={!selected || isPending}
        style={[styles.bottom, (!selected || isPending) && { opacity: 0.5 }]}
        onPress={() => {
          if (phone && stir && person_type && selected) {
            mutate({
              activate_types: [selected],
              person_type: person_type,
              phone: `998${phone}`,
              stir: stir,
            });
          }
        }}
      >
        <Text style={styles.bottomText}>{isPending ? 'Yuborilmoqda...' : 'Tasdiqlash'}</Text>
      </TouchableOpacity>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 16,
    paddingBottom: 120,
  },
  item: {
    paddingVertical: 18,
    borderBottomWidth: 1,
    borderColor: '#e2e8f0',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  text: {
    fontSize: 16,
    fontWeight: '600',
  },
  bottom: {
    position: 'absolute',
    bottom: 20,
    left: 16,
    right: 16,
    height: 54,
    borderRadius: 16,
    backgroundColor: '#2563eb',
    alignItems: 'center',
    justifyContent: 'center',
  },
  bottomText: {
    color: '#fff',
    fontWeight: '800',
    fontSize: 16,
  },
});
