import React, { useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { __ } from '@/lib/i18n';
import { CouponsApi, type CouponFormData } from '@/lib/api/coupons';
import { showErrorToast, showSuccessToast } from '@/lib/errorHandling';
import { usePageHeader } from '@/contexts/PageHeaderContext';
import { Button } from '@/components/ui/button';
import { useFABConfig } from '@/hooks/useFABConfig';
import CouponForm from './CouponForm';

export default function CouponNew() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const formRef = useRef<HTMLFormElement>(null);
  const { setPageHeader, clearPageHeader } = usePageHeader();

  // Hide FAB on create page
  useFABConfig('none');

  // Create mutation
  const createMutation = useMutation({
    mutationFn: (data: CouponFormData) => CouponsApi.create(data),
    onSuccess: (coupon) => {
      queryClient.invalidateQueries({ queryKey: ['coupons'] });
      showSuccessToast(__('Coupon created successfully'), `${__('Coupon')} ${coupon.code} ${__('created')}`);
      navigate('/coupons');
    },
    onError: (error) => {
      showErrorToast(error);
    },
  });

  // Set contextual header
  useEffect(() => {
    const actions = (
      <div className="flex gap-2">
        <Button size="sm" variant="ghost" onClick={() => navigate('/coupons')}>
          {__('Cancel')}
        </Button>
        <Button
          size="sm"
          onClick={() => formRef.current?.requestSubmit()}
          disabled={createMutation.isPending}
        >
          {createMutation.isPending ? __('Creating...') : __('Create')}
        </Button>
      </div>
    );

    setPageHeader(__('New Coupon'), actions);
    return () => clearPageHeader();
  }, [createMutation.isPending, setPageHeader, clearPageHeader, navigate]);

  return (
    <div>
      <CouponForm
        mode="create"
        onSubmit={async (data) => {
          await createMutation.mutateAsync(data);
        }}
        formRef={formRef}
        hideSubmitButton={true}
      />
    </div>
  );
}
