import React, { useState } from 'react';
import { View, TouchableOpacity, Alert } from 'react-native';
import { AppContainer, MyText, tw } from 'common-ui';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useRouter } from 'expo-router';
import { FormikHelpers } from 'formik';
import BannerForm, { BannerFormData } from '@/components/BannerForm';
import { trpc } from '@/src/trpc-client';

export default function CreateBanner() {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const initialValues: BannerFormData = {
    name: '',
    imageUrl: '',
    description: '',
    productIds: [],
    redirectUrl: '',
    // serialNum removed - assigned automatically by backend
  };

  const createBannerMutation = trpc.admin.banner.createBanner.useMutation();
  const { refetch: refetchBanners } = trpc.admin.banner.getBanners.useQuery(undefined, {
    enabled: false,
  });

  const handleSubmit = async (values: BannerFormData, imageUrl?: string) => {
    if (!imageUrl) {
      Alert.alert('Error', 'Image is required');
      return;
    }

    setIsSubmitting(true);

    try {
      await createBannerMutation.mutateAsync({
        name: values.name,
        imageUrl,
        description: values.description || undefined,
        productIds: values.productIds.length > 0 ? values.productIds : [],
        redirectUrl: values.redirectUrl || undefined,
      });

      await refetchBanners()
      Alert.alert('Success', 'Banner created successfully', [
        {
          text: 'OK',
          onPress: () => router.back(),
        }
      ]);
    } catch (error) {
      
      Alert.alert('Error', 'Failed to create banner. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleCancel = () => {
    router.back();
  };

  return (
    <AppContainer>
      <View style={tw`flex-1 bg-white`}>
        {/* Header */}
        <View style={tw`flex-row items-center justify-between px-6 py-4 border-b border-gray-200`}>
          <TouchableOpacity onPress={handleCancel} style={tw`p-2`}>
            <MaterialIcons name="arrow-back" size={24} color="#374151" />
          </TouchableOpacity>
          <MyText style={tw`text-xl font-bold text-gray-900`}>Create Banner</MyText>
          <View style={tw`w-10`} />
        </View>

        <BannerForm
          initialValues={initialValues}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
          submitButtonText="Create Banner"
          isSubmitting={isSubmitting}
        />
      </View>
    </AppContainer>
  );
}
