import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { CreateTreasuryPaymentDTO } from '@/types/treasury';
import { treasuryService } from '@/services/treasuryService';
import { toast } from 'sonner';

interface TreasuryPaymentFormModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const formSchema = z.object({
  paymentOrderId: z.string().min(1, 'ID da Ordem de Pagamento é obrigatório'),
  transactionRef: z.string().optional(),
  status: z.enum(['PENDING', 'PAID', 'REJECTED', 'CANCELLED']),
  message: z.string().optional(),
});

type FormValues = z.infer<typeof formSchema>;

export function TreasuryPaymentFormModal({
  open,
  onClose,
  onSuccess,
}: TreasuryPaymentFormModalProps) {
  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      paymentOrderId: '',
      transactionRef: '',
      status: 'PENDING',
      message: '',
    },
  });

  const onSubmit = async (data: FormValues) => {
    try {
      const dto: CreateTreasuryPaymentDTO = {
        paymentOrderId: data.paymentOrderId,
        transactionRef: data.transactionRef || undefined,
        status: data.status,
        message: data.message || undefined,
      };

      await treasuryService.createTreasuryPayment(dto);
      toast.success('Confirmação de pagamento registrada com sucesso');

      form.reset();
      onSuccess();
      onClose();
    } catch (error: any) {
      toast.error(error.message || 'Erro ao registrar confirmação de pagamento');
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Nova Confirmação de Pagamento</DialogTitle>
          <DialogDescription>
            Registre uma nova confirmação de pagamento efetivado
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="paymentOrderId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>ID da Ordem de Pagamento *</FormLabel>
                  <FormControl>
                    <Input placeholder="UUID da ordem de pagamento" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="transactionRef"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Referência da Transação</FormLabel>
                  <FormControl>
                    <Input placeholder="Referência bancária" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Status *</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="PENDING">Pendente</SelectItem>
                      <SelectItem value="PAID">Pago</SelectItem>
                      <SelectItem value="REJECTED">Rejeitado</SelectItem>
                      <SelectItem value="CANCELLED">Cancelado</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="message"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Mensagem</FormLabel>
                  <FormControl>
                    <Textarea
                      rows={3}
                      placeholder="Mensagem adicional sobre a confirmação..."
                      className="resize-none"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="button" variant="outline" onClick={onClose} disabled={form.formState.isSubmitting}>
                Cancelar
              </Button>
              <Button type="submit" disabled={form.formState.isSubmitting}>
                {form.formState.isSubmitting ? 'Registrando...' : 'Registrar'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
