import { FormTextAreaField } from "@/components";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  Button,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  Form,
} from "@/ui";
import { useState } from "react";

import { SubmitHandler, useForm } from "react-hook-form";

import { useToast } from "@/ui/use-toast";
import { joiResolver } from "@hookform/resolvers/joi";
import { ISendIncidence_Request_DTO } from "@shared/contexts";
import { t } from "i18next";
import Joi from "joi";
import { HelpCircleIcon } from "lucide-react";
import { useSupport } from "../hooks";

const formSchema = Joi.object({
  incidence: Joi.string().min(10).required().messages({
    "string.empty": "Debe escribir algo antes de enviar",
    "string.min": "El texto es demasiado corto. Debe tener al menos 10 caracteres",
    "string.max": "El texto es demasiado largo.",
    "any.required": "La descripción es requerida",
  }),
});

type SupportDataForm = ISendIncidence_Request_DTO;

export default function SupportModal() {
  const [isOpen, setIsOpen] = useState(false);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const { toast } = useToast();
  const { useSubmitIncidence } = useSupport();

  const form = useForm<SupportDataForm>({
    mode: "onBlur",
    resolver: joiResolver(formSchema),
    defaultValues: {
      incidence: "",
    },
  });

  const { handleSubmit, watch, reset } = form;

  const incidenceValue = watch("incidence");

  const { mutate } = useSubmitIncidence({
    mutateOptions: {
      onSuccess: () => {
        toast({
          title: "Incidencia enviada",
          description: "La incidencia se ha enviado correctamente",
          variant: "success",
        });
        setIsOpen(false);
        reset();
      },
      onError: () => {
        toast({
          title: "Error en el envío",
          description:
            "No se ha podido enviar la incidencia correctamente. Por favor, inténtalo de nuevo.",
          variant: "destructive",
        });
      },
    },
  });

  const onSubmit: SubmitHandler<SupportDataForm> = async (data) => {
    mutate(data);
  };

  const handleClose = () => {
    if (incidenceValue.trim()) {
      setShowConfirmDialog(true);
    } else {
      setIsOpen(false);
      reset();
    }
  };

  const confirmClose = () => {
    setShowConfirmDialog(false);
    setIsOpen(false);
    reset();
  };

  return (
    <>
      <Dialog open={isOpen} onOpenChange={setIsOpen}>
        <DialogTrigger asChild>
          <Button
            variant='outline'
            size='icon'
            className='overflow-hidden rounded-full bg-primary text-primary-foreground'
            onClick={() => setIsOpen(true)}
          >
            <HelpCircleIcon className='w-5 h-5' />
            <span className='sr-only'>Abrir ventana de soporte</span>
          </Button>
        </DialogTrigger>
        <DialogContent className='sm:max-w-xl'>
          <DialogHeader className='mb-2'>
            <DialogTitle>{t("support.modal.title")}</DialogTitle>
            <DialogDescription>{t("support.modal.subtitle")}</DialogDescription>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={handleSubmit(onSubmit)} className='space-y-4'>
              <FormTextAreaField
                name='incidence'
                placeholder='Describe la incidencia aquí...'
                className='min-h-96'
              />
              <DialogFooter>
                <Button type='button' variant='outline' onClick={handleClose}>
                  Cancelar
                </Button>
                <Button type='submit'>Enviar incidencia</Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      <AlertDialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>¿Estás seguro de que quieres cancelar?</AlertDialogTitle>
            <AlertDialogDescription>
              Has escrito texto en el campo de descripción. Si cierras la ventana, perderás los
              cambios no guardados.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setShowConfirmDialog(false)}>
              Volver al formulario
            </AlertDialogCancel>
            <AlertDialogAction onClick={confirmClose}>Sí, cerrar</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
