import React from 'react';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native';
import { useFormContext } from 'react-hook-form';
import { useRouter } from 'expo-router';
import { useSettings } from '@/theme';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

interface FormButtonsProps {
  onSubmit: (data: any) => void;
  submitLabel?: string;
}

export function FormButtons({ onSubmit, submitLabel = 'Submit' }: FormButtonsProps) {
  const router = useRouter();
  const { theme } = useSettings();
  const { handleSubmit, formState: { isSubmitting } } = useFormContext();
  const insets = useSafeAreaInsets();

  const cancel = () => {
    if (router.canGoBack()) {
      router.back();
    } else {
      router.replace('/');
    }
  };

  return (
    <View style={[styles.container, { backgroundColor: theme.background, borderTopColor: theme.border, paddingBottom: insets.bottom + 12 }]}>
      <TouchableOpacity
        style={[styles.cancelButton, { borderColor: theme.borderStrong, backgroundColor: theme.card }]}
        onPress={cancel}
        disabled={isSubmitting}
        activeOpacity={0.7}
        accessibilityRole="button"
        accessibilityLabel="Cancel"
        accessibilityState={{ disabled: isSubmitting }}
      >
        <Text style={[styles.cancelButtonText, { color: theme.textSecondary }]}>Cancel</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.submitButton, { backgroundColor: theme.accent }, isSubmitting && styles.buttonDisabled]}
        onPress={handleSubmit(onSubmit)}
        disabled={isSubmitting}
        activeOpacity={0.8}
        accessibilityRole="button"
        accessibilityLabel={isSubmitting ? 'Saving' : submitLabel}
        accessibilityState={{ disabled: isSubmitting, busy: isSubmitting }}
      >
        <Text style={[styles.submitButtonText, { color: theme.accentText }]}>
          {isSubmitting ? 'Saving...' : submitLabel}
        </Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    paddingHorizontal: 12,
    paddingVertical: 12,
    borderTopWidth: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    gap: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: -2 },
    shadowOpacity: 0.05,
    shadowRadius: 6,
    elevation: 3,
  },
  cancelButton: {
    flex: 1,
    paddingVertical: 12,
    borderRadius: 10,
    borderWidth: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  cancelButtonText: {
    fontSize: 15,
    fontWeight: '600',
  },
  submitButton: {
    flex: 1,
    paddingVertical: 12,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  submitButtonText: {
    fontSize: 15,
    fontWeight: '600',
  },
  buttonDisabled: {
    opacity: 0.6,
  },
});
