import React from 'react';
import { View, Alert } from 'react-native';
import { tw, AppContainer } from 'common-ui';
import CouponForm from '../../../src/components/CouponForm';
import { trpc } from '@/src/trpc-client';
import { useRouter } from 'expo-router';

export default function CreateCoupon() {
  const router = useRouter();
  const createCoupon = trpc.admin.coupon.create.useMutation();
  const createReservedCoupon = trpc.admin.coupon.createReservedCoupon.useMutation();

  const handleCreateCoupon = (values: any) => {
    console.log('Form values:', values); // Debug log
    const { isReservedCoupon, ...rest } = values;
    // Transform targetUsers array to targetUser for backend compatibility
    const payload = {
      ...rest,
      targetUser: rest.targetUsers?.[0] || undefined,
    };
    delete payload.targetUsers;
    console.log('Payload:', payload); // Debug log

    const mutation = isReservedCoupon ? createReservedCoupon : createCoupon;
    const isLoading = isReservedCoupon ? createReservedCoupon.isPending : createCoupon.isPending;

    if (isLoading) return; // Prevent double submission

    mutation.mutate(payload, {
      onSuccess: () => {
        Alert.alert('Success', `${isReservedCoupon ? 'Reserved coupon' : 'Coupon'} created successfully`, [
          { text: 'OK', onPress: () => router.back() }
        ]);
      },
      onError: (error: any) => {
        Alert.alert('Error', error.message || 'Failed to create coupon');
      },
    });
  };

  return (
    <AppContainer>
      <CouponForm
        onSubmit={handleCreateCoupon}
        isLoading={createCoupon.isPending || createReservedCoupon.isPending}
      />
    </AppContainer>
  );
}