"use client";
import { Input } from "./ui/input";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Button } from "@/app/_components/ui/button";

import { useMutation } from "@tanstack/react-query";
import { useToast } from "@/app/_components/ui/use-toast";
import { useRouter } from "next/navigation";
import { z } from "zod";
import { POST } from "@/app/api/rainha/routes";
import { parseISO, differenceInYears } from "date-fns";
import { validarCPF } from "../validate/cpf";
import { CheckCheck, ChevronLeftIcon, FileDigit } from "lucide-react";
import Link from "next/link";
import { useState } from "react";

const MAX_FILE_SIZE = 5000000;
const ACCEPTED_IMAGE_TYPES = [
  "image/jpeg",
  "image/jpg",
  "image/png",
  "image/webp",
  "application/pdf",
];

const formSchema = z.object({
  nome: z.string().refine((val) => val.length >= 3, {
    message: "Tem que ter no minimo 3 caracteres",
  }),
  email: z.string().refine((val) => val.length >= 3, {
    message: "Tem que ter no minimo 3 caracteres",
  }),
  telefone: z.string().refine((val) => val.length >= 3, {
    message: "Tem que ter no minimo 3 caracteres",
  }),
  cpf: z.string().refine(
    (val) => {
      return validarCPF(val);
    },
    {
      message: "CPF inválido",
    },
  ),

  datanascimento: z
    .string()
    .transform((val) => {
      const date = parseISO(val);
      // Aqui, você pode verificar se a data de nascimento está dentro do intervalo desejado
      const age = differenceInYears(new Date(), date);
      const validateAte = age < 5 || age > 9;
      if (validateAte) {
        return "A idade deve estar entre 5 e 9 anos.";
      }
      return date;
    })
    .refine(
      (val) => {
        return val >= new Date("1900-01-01");
      },
      {
        message: "Data de nascimento inválida tem que ter entre 5 e 9 anos",
      },
    ),
  acompanhante: z.string().refine((val) => val.length >= 3, {
    message: "Tem que ter no minimo 3 caracteres",
  }),

  candidateDocument: z
    .any()
    // To not allow empty files
    .refine((files) => files?.length >= 1, { message: "Image is required." })
    // To not allow files other than images
    .refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
      message: ".jpg, .jpeg, .png and .webp files are accepted.",
    })
    // To not allow files larger than 5MB
    .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
      message: `Max file size is 5MB.`,
    }),

  companionDocument: z
    .any()
    // To not allow empty files
    .refine((files) => files?.length >= 1, { message: "Image is required." })
    // To not allow files other than images
    .refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
      message: ".jpg, .jpeg, .png and .webp files are accepted.",
    })
    // To not allow files larger than 5MB
    .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
      message: `Max file size is 5MB.`,
    }),

  facePhoto: z
    .any()
    // To not allow empty files
    .refine((files) => files?.length >= 1, { message: "Image is required." })
    // To not allow files other than images
    .refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
      message: ".jpg, .jpeg, .png and .webp files are accepted.",
    })
    // To not allow files larger than 5MB
    .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
      message: `Max file size is 5MB.`,
    }),

  bodyPhoto: z
    .any()
    // To not allow empty files
    .refine((files) => files?.length >= 1, { message: "Image is required." })
    // To not allow files other than images
    .refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
      message: ".jpg, .jpeg, .png and .webp files are accepted.",
    })
    // To not allow files larger than 5MB
    .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
      message: `Max file size is 5MB.`,
    }),
  instagram: z.string().optional(),
  attachmentOne: z
    .any()
    // To not allow empty files
    .refine((files) => files?.length >= 1, { message: "Image is required." })
    // To not allow files other than images
    .refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
      message: ".jpg, .jpeg, .png and .webp files are accepted.",
    })
    // To not allow files larger than 5MB
    .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
      message: `Max file size is 5MB.`,
    }),
  proofOfResidence: z
    .any()
    // To not allow empty files
    .refine((files) => files?.length >= 1, { message: "Image is required." })
    // To not allow files other than images
    .refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
      message: ".jpg, .jpeg, .png and .webp files are accepted.",
    })
    // To not allow files larger than 5MB
    .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
      message: `Max file size is 5MB.`,
    }),
});

type FormData = z.infer<typeof formSchema>;

const CreateRainha = () => {
  const router = useRouter();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const {
    handleSubmit,
    register,
    formState: { errors },
  } = useForm<FormData>({
    mode: "onBlur",
    resolver: zodResolver(formSchema),
  });

  const mutation = useMutation({
    mutationFn: async (data: any) => {
      setLoading(true);
      let dataResponse = data;
      return POST(dataResponse).then((response) => response);
    },
    onError: (error) => {
      toast({
        title: error.message,
      });
      setLoading(false);
    },
    onSuccess: (data) => {
      if (data.error) {
        toast({
          variant: "destructive",
          title: data.error,
        });
        setLoading(false);
      } else {
        toast({
          title: "Rainha Mirin cadastrado com sucesso",
        });
        setLoading(false);
        router.push("/");
      }
    },
  });

  const onSubmit = async (data: FormData) => {
    const formData = new FormData();
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        const value = data[key as keyof FormData];
        if (value instanceof FileList) {
          if (value.length > 0) {
            // Adiciona apenas o primeiro arquivo do FileList com o nome 'files'
            formData.append("files", value[0]);
          }
        } else {
          // Se não for um FileList, adiciona o valor normalmente
          formData.append(key, value);
        }
      }
    }
    formData.append("tipo", "Mirin");
    //mutation.mutate(formData);
  };

  return (
    <>
      {loading === true ? (
        <div className="mt-52 flex h-full items-center justify-center">
          <h1 className="text-center text-3xl font-semibold">
            Aguarde o carregamento e não feche essa pagina
          </h1>
        </div>
      ) : (
        <>
          <Link
            href="/"
            className="flex items-center px-4 py-6 text-blue-500 hover:text-blue-700"
          >
            <ChevronLeftIcon size={24} className="mr-2" /> Voltar
          </Link>
          <div className="mb-5 flex flex-col items-center justify-center px-4">
            <form onSubmit={handleSubmit(onSubmit)} className="w-full md:w-1/2">
              <h1 className="mb-4 bg-gradient-to-r from-pink-500 to-purple-600 bg-clip-text text-center text-2xl font-bold text-transparent">
                Cadastro Rainha Mirim
              </h1>
              <div className="mb-4">
                <label
                  htmlFor="nome"
                  className="block text-sm font-medium text-black"
                >
                  Nome da candidata:
                </label>
                <Input
                  type="text"
                  id="nome"
                  {...register("nome")}
                  required
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent p-2"
                  placeholder="Digite o nome"
                />
                {errors.nome?.message && (
                  <p className="text-sm text-red-400">{errors.nome?.message}</p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="email"
                  className="block text-sm font-medium text-black"
                >
                  E-mail:
                </label>
                <Input
                  type="email"
                  id="email"
                  {...register("email")}
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent  p-2"
                />
                {errors.email?.message && (
                  <p className="text-sm text-red-400">
                    {errors.email?.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="telefone"
                  className="block text-sm font-medium text-black"
                >
                  Telefone:
                </label>
                <Input
                  type="text"
                  id="telefone"
                  {...register("telefone")}
                  required
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent p-2"
                  placeholder="Digite o telefone"
                />
                {errors.telefone?.message && (
                  <p className="text-sm text-red-400">
                    {errors.telefone?.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="cpf"
                  className="block text-sm font-medium text-black"
                >
                  CPF Candidata ou Responsável:
                </label>
                <Input
                  type="text"
                  id="cpf"
                  {...register("cpf")}
                  required
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent p-2"
                  placeholder="Digite o cpf"
                />
                {errors.cpf?.message && (
                  <p className="text-sm text-red-400">{errors.cpf?.message}</p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="acompanhante"
                  className="block text-sm font-medium text-black"
                >
                  Nome do responsável legal:
                </label>
                <Input
                  type="text"
                  id="acompanhante"
                  {...register("acompanhante")}
                  required
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent p-2"
                  placeholder="Digite o acompanhante"
                />
                {errors.acompanhante?.message && (
                  <p className="text-sm text-red-400">
                    {errors.acompanhante?.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="instagram"
                  className="block text-sm font-medium text-black"
                >
                  Instagram (@Nome):
                </label>
                <Input
                  type="text"
                  id="instagram"
                  step="0.001"
                  {...register("instagram")}
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent  p-2"
                />
                {errors.instagram?.message && (
                  <p className="text-sm text-red-400">
                    {errors.instagram?.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="datanascimento"
                  className="block text-sm font-medium text-black"
                >
                  Data Nascimento:
                </label>
                <input
                  type="date"
                  id="dateNasc"
                  required
                  {...register("datanascimento")}
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent p-2 text-black "
                />
                {errors.datanascimento?.message && (
                  <p className="text-sm text-red-400">
                    {errors.datanascimento?.message}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="candidateDocument"
                  className="block text-sm font-medium text-black"
                >
                  Documento com foto da candidata:
                </label>
                <input
                  type="file"
                  id="candidateDocument"
                  {...register("candidateDocument")}
                  placeholder="Arquivo"
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent  p-2 "
                  required
                />
                {errors.candidateDocument?.message && (
                  <p className="text-sm text-red-400">
                    {"Documento do candidato obrigatorio"}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="companionDocument"
                  className="block text-sm font-medium text-black"
                >
                  Documento com foto do responsável legal:
                </label>
                <input
                  type="file"
                  id="companionDocument"
                  {...register("companionDocument")}
                  placeholder="Arquivo"
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent  p-2 "
                  required
                />
                {errors.companionDocument?.message && (
                  <p className="text-sm text-red-400">
                    {"Documento do candidato obrigatorio"}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="facePhoto"
                  className="block text-sm font-medium text-black"
                >
                  Foto do rosto (candidata):
                </label>
                <input
                  type="file"
                  id="facePhoto"
                  {...register("facePhoto")}
                  placeholder="Arquivo"
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent  p-2 "
                  required
                />
                {errors.facePhoto?.message && (
                  <p className="text-sm text-red-400">
                    {"Documento do candidato obrigatorio"}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="bodyPhoto"
                  className="block text-sm font-medium text-black"
                >
                  Foto corpo (candidata):
                </label>
                <input
                  type="file"
                  id="bodyPhoto"
                  {...register("bodyPhoto")}
                  placeholder="Arquivo"
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent  p-2 "
                  required
                />
                {errors.bodyPhoto?.message && (
                  <p className="text-sm text-red-400">
                    {"Documento do candidato obrigatorio"}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="attachmentOne"
                  className="block text-sm font-medium text-black"
                >
                  Anexo I Declaração cumprimento dos requisitos:
                </label>
                <div className="flex items-center justify-between gap-4">
                  <input
                    type="file"
                    id="attachmentOne"
                    {...register("attachmentOne")}
                    placeholder="Arquivo"
                    className="mb-2 mt-1 w-full rounded-md border bg-transparent  p-2 "
                    required
                  />
                  <a
                    href="/anexo.pdf"
                    target="_blank"
                    className="cursor-pointer"
                  >
                    <FileDigit />
                  </a>
                </div>
                {errors.attachmentOne?.message && (
                  <p className="text-sm text-red-400">
                    {"Documento do candidato obrigatorio"}
                  </p>
                )}
              </div>
              <div className="mb-4">
                <label
                  htmlFor="proofOfResidence"
                  className="block text-sm font-medium text-black"
                >
                  Comprovante de residencia:
                </label>
                <input
                  type="file"
                  id="proofOfResidence"
                  {...register("proofOfResidence")}
                  placeholder="Arquivo"
                  className="mb-2 mt-1 w-full rounded-md border bg-transparent  p-2 "
                  required
                />
                {errors.proofOfResidence?.message && (
                  <p className="text-sm text-red-400">
                    {"Documento do candidato obrigatorio"}
                  </p>
                )}
              </div>
              <div className="flex items-center justify-center">
                <Button
                  className="bg-pink-500 font-bold text-white"
                  disabled={true}
                >
                  Inscrições encerradas
                </Button>
              </div>
            </form>
          </div>
        </>
      )}
    </>
  );
};

export default CreateRainha;
