'use client'
import React, { use, useEffect, useState } from "react";

import { useParams, useRouter } from "next/navigation";
import { inputMask } from "@/utils/functions";

import Image from "next/image";
import IconSeash from "../../../../../../public/assets/Images/Icons/search.svg";
import IconCadastroRealizado
    from "../../../../../../public/assets/Images/ImageTrabalheConosco/iconCadastroRealizado.png";

import { toast } from "react-toastify";
import { API_URL, TOKEN } from "@/utils/constants/selectConstants";
import { ICheckoutSearchAddress } from "@/utils/Interfaces/ICheckoutContext";
import { useWebContext } from "@/app/(site)/providers";
import { BiUpload, BiX } from "react-icons/bi";

import { z } from "zod";

import { IoMdClose } from "react-icons/io";
import { getJobs } from "@/actions/pageWorkTous";

export default function Page() {
    const { isMobile } = useWebContext();
    const { slug } = useParams<{ slug: string[] }>();
    const router = useRouter();
    const { dataStates, dataVagas } = useWebContext();
    const [cities, setCityes] = useState<any[]>([])

    const [nome, setNome] = useState<string>('')
    const [email, setEmail] = useState<string>('')
    const [phoneNumber, setPhoneNumber] = useState<string>('')

    const [zipCode, setZipCode] = useState<string>('')
    const [state, setState] = useState<string>('')
    const [city, setCity] = useState<string>('')
    const [address, setAddress] = useState<string>('')
    const [district, setDistrict] = useState<string>('')
    const [number, setNumber] = useState<string>('')
    const [complement, setComplement] = useState<string>('')
    const [atualmenteTrabalhando, setAualmenteTrabalhando] = useState<boolean>(false)
    const [file, setFile] = useState<File | null>(null);
    const [modalSuccess, setModalSuccess] = useState<boolean>(false);
    const [nomeVaga, setNomeVaga] = useState<string>('');

    useEffect(() => {
        if (state) {
            fetch(`${API_URL}Cidades/consultar/?EstadosId=${state}&order=Nome`, {
                headers: {
                    Authorization: TOKEN
                },
            })
                .then(res => res.json())
                .then(body => setCityes(Object.values(body)))
        }
    }, [state])

    const handleSearchCep = () => {
        if (!zipCode) {
            toast.error('O campo CEP é obrigatório.');
            return;
        }

        fetch(`${API_URL}IndividuosEnderecos/ConsultaCep`, {
            method: 'POST',
            headers: {
                Authorization: TOKEN
            },
            body: JSON.stringify({ Cep: zipCode })
        })
            .then(res => {
                if (!res.ok) {
                    throw res;
                }

                return res.json();
            })
            .then((body: ICheckoutSearchAddress) => {
                setDistrict(body.bairro);
                setAddress(body.logradouro);
                setState(body.estado_id);
                setCity(body.cidade_id);
            })
            .catch(error => {
                toast.error('CEP inválido.');
            });
    }

    const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (!e.target.files) {
            return;
        }
        setFile(e.target.files[0]);
    }

    const toBase64 = (file: File) => {
        return new Promise((resolve, reject) => {
            const fileReader = new FileReader();
            fileReader.readAsDataURL(file);
            fileReader.onload = () => {
                resolve(fileReader.result);
            };
            fileReader.onerror = (error) => {
                reject(error);
            };
        });
    };

    const handleRegisterCurriculo = async () => {

        let formData = {
            VagasId: "",
            Nome: "",
            Telefone: "",
            Email: "",
            Cep: "",
            Logradouro: "",
            Numero: "",
            Bairro: "",
            EstadosId: "",
            CidadesId: "",
            Complemento: "",
            TrabalhaAtualmente: false,
            NomeArquivo: "",
            Arquivo: ""
        };

        const vaga = z.object({
            Nome: z.string({ message: 'O campo nome é obrigatório' }),
            Telefone: z.string({ message: 'O campo telefone é obrigatório' }),
            Email: z.string({ message: 'O campo nome é obrigatório' }).email('Preencha o campo com um e-mail válido.'),
            Cep: z.string({ message: 'O campo CEP é obrigatório' }),
            Logradouro: z.string({ message: 'O campo Logradouro é obrigatório' }),
            Numero: z.string({ message: 'O campo Número é obrigatório' }),
            Bairro: z.string({ message: 'O campo Bairro é obrigatório' }),
            EstadosId: z.string({ message: 'O campo Estado é obrigatório' }),
            CidadesId: z.string({ message: 'O campo Cidade é obrigatório' }),
            NomeArquivo: z.string({ message: 'O campo Currículo é obrigatório' }),
            Arquivo: z.string({ message: 'O campo Currículo é obrigatório' }),
        })

        formData.VagasId = slug[0];
        formData.Nome = nome;
        formData.Email = email;
        formData.Telefone = phoneNumber;
        formData.Cep = zipCode;
        formData.Logradouro = address;
        formData.Numero = number;
        formData.Complemento = complement || "";
        formData.Bairro = district;
        formData.EstadosId = state;
        formData.CidadesId = city
        formData.TrabalhaAtualmente = atualmenteTrabalhando;

        if (file) {
            formData.NomeArquivo = (file?.name || "").replace(/\s/g, '');
            formData.Arquivo = await toBase64(file as File) as string;
        }

        const data = vaga.safeParse(formData)

        if (!data.success) {
            Object.values(data.error.flatten().fieldErrors).map(item => {
                toast.error(item[0]);
            })
            return;
        }

        const res = await fetch(`${API_URL}VagasCandidatos/NovoCandidato`, {
            method: 'post',
            headers: {
                'Authorization': TOKEN
            },
            body: JSON.stringify(formData)
        });
        const body = await res.json();

        if (res.status === 200 || res.status === 201) {
            setModalSuccess(true);
        } else {
            toast.error(body.mensagem);
        }
    }

    const handleCloseModalSuccess = () => {
        setModalSuccess(false);
        router.push('/trabalhe-conosco');
    }

    useEffect(() => {
        (async () => {
            try {
                const data = await getJobs('');
                if (data && typeof data === 'object') {
                    let dados = Object.values(data);
                    const vagaSelecionada = dados.find(
                        (item): item is { Id: string; CargosNome: string } => 
                            typeof item === 'object' && item !== null && 'Id' in item && 'CargosNome' in item && item.Id === slug[0]
                    ) as { Id: string; CargosNome: string } | undefined;

                    setNomeVaga(vagaSelecionada?.CargosNome || '');
                } else {
                    console.warn('getJobs returned unexpected data:', data);
                }
            } catch (error) {
                console.error(error);
            }
        })();
    }, [slug]);

    return (
        <div className="flex flex-col items-center">
            {!isMobile &&
                <div className="w-[816px] mt-[35px] pb-[35px]">
                    <h1 className="text-grandstander uppercase text-center text-[56px] text-plamev-blue-500 leading-[56px]">
                        Cadastre-se e boa sorte futuro PLAMEVER
                    </h1>
                    <p className="text-center">Preencha os campos abaixo com seus dados.</p>
                </div>
            }

            {isMobile &&
                <div className="w-[327px] m-auto mt-[35px] pb-[35px]">
                    <h1 className="text-grandstander uppercase text-center text-[40px] text-plamev-blue-500 leading-[40px]">
                        Cadastre-se e boa sorte futuro PLAMEVER
                    </h1>
                    <p className="text-center">Preencha os campos abaixo com seus dados.</p>
                </div>
            }

            {!isMobile &&
                <div className="w-[816px] border-b-[2px] border-dashed pb-[32px]">
                    <p className="text-poppins text-[18px] font-bold text-plamev-blue-500">Cadastro para a vaga de:</p>
                    <p className="text-poppins text-[18px] font-bold text-plamev-dark-300">
                        {nomeVaga}
                    </p>
                </div>
            }

            {isMobile &&
                <div className="w-[327px] border-b-[2px] border-dashed pb-[32px]">
                    <p className="text-poppins text-[18px] font-bold text-plamev-blue-500">Cadastro para a vaga de:</p>
                    <p className="text-poppins text-[18px] font-bold text-plamev-dark-300">
                        {nomeVaga}
                    </p>
                </div>
            }

            {!isMobile &&
                <div className="w-[816px] mt-[32px]">
                    <h3 className="text-plamev-dark-400 text-[14px] text-poppins font-bold  mb-2">Dados pessoais</h3>

                    <div className="flex mb-2">
                        <div className="w-full">
                            <input
                                type="text"
                                id="Nome"
                                name="Nome"
                                placeholder="Seu nome"
                                value={nome}
                                onChange={({ target }) => setNome(target.value)}
                                className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                            />
                        </div>
                    </div>

                    <div className="flex mb-2 flex-col sm:flex-row justify-between items-center gap-4">
                        <div className="flex relative flex-1 w-[100%] sm:w-auto">
                            <input
                                type="text"
                                placeholder="CEP"
                                value={inputMask(zipCode, 'cep')}
                                onChange={({ target }) => setZipCode(target.value)}
                                className="bg-plamev-light-50 flex-1 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                            />

                            <div className="absolute top-[15px] right-[10px]">
                                <button type="button" onClick={() => handleSearchCep()}>
                                    <Image src={IconSeash} alt="Pesquisar CEP" />
                                </button>
                            </div>
                        </div>

                        <select
                            value={state}
                            onChange={({ target }) => setState(target.value)}
                            className="bg-plamev-light-50 py-3 flex-1 border-plamev-dark-50 border-2 border-solid rounded-md w-full pl-2"
                        >
                            <option value="">Estado</option>
                            {dataStates.length > 0 && dataStates.map((item, key: number) => (
                                <option value={item.Id} key={key}>{item.Nome}</option>
                            ))}
                        </select>

                        <select
                            value={city}
                            onChange={({ target }) => setCity(target.value)}
                            className="bg-plamev-light-50 py-3 flex-1 border-plamev-dark-50 border-2 border-solid rounded-md w-full pl-2"
                        >
                            <option value="">Cidade</option>
                            {cities.length > 0 && cities.map((item, key: number) => (
                                <option value={item.Id} key={key}>{item.Nome}</option>
                            ))}
                        </select>
                    </div>

                    <div className="flex mb-2 flex-col sm:flex-row justify-between items-center gap-4">
                        <input
                            type="text"
                            placeholder="Endereço"
                            value={address}
                            onChange={({ target }) => setAddress(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />

                        <input
                            type="text"
                            placeholder="Bairro"
                            value={district}
                            onChange={({ target }) => setDistrict(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />
                    </div>

                    <div className="flex mb-2 flex-col sm:flex-row justify-between items-center gap-4">
                        <input
                            type="text"
                            placeholder="Número"
                            value={number}
                            onChange={({ target }) => setNumber(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />

                        <input
                            type="text"
                            placeholder="Complemento"
                            value={complement}
                            onChange={({ target }) => setComplement(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />
                    </div>

                    <h3 className="text-plamev-dark-400 text-[14px] text-poppins font-bold mb-2">Dados de contato</h3>

                    <div className="flex mb-2  flex-col sm:flex-row justify-between items-center gap-4">
                        <input
                            type="email"
                            placeholder="E-mail"
                            value={email}
                            onChange={({ target }) => setEmail(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />
                    </div>

                    <div className="flex mb-2  flex-col sm:flex-row justify-between items-center gap-4">
                        <input
                            type="text"
                            placeholder="Telefone de Contato"
                            maxLength={15}
                            value={inputMask(phoneNumber, 'telefone')}
                            onChange={({ target }) => setPhoneNumber(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />
                    </div>

                    <h3 className="text-plamev-dark-400 text-[14px] text-poppins font-bold  mb-2">
                        Está trabalhando atualmente?
                    </h3>

                    <div className="flex mb-2  flex-col sm:flex-row  items-center gap-5">
                        <div className="flex gap-3">
                            <input
                                type="radio"
                                id="sim"
                                onClick={() => setAualmenteTrabalhando(true)}
                                checked={atualmenteTrabalhando}
                            />
                            <label htmlFor="sim">Sim</label>
                        </div>

                        <div className="flex gap-3">
                            <input
                                type="radio"
                                id="nao"
                                onClick={() => setAualmenteTrabalhando(false)}
                                checked={!atualmenteTrabalhando}
                            />
                            <label htmlFor="nao">Não</label>
                        </div>
                    </div>

                    <h3 className="text-plamev-dark-400 text-[14px] text-poppins font-bold  mb-2">Anexar currículo</h3>
                    <div className="flex mb-2  flex-col sm:flex-row  items-center gap-5">
                        <div className="flex flex-col items-center">
                            <label
                                htmlFor="file-upload"
                                className="cursor-pointer flex gap-5 justify-center items-center w-[219px] h-[54px] bg-plamev-dark-50 text-plamev-blue-900 rounded-md shadow focus:outline-none focus:ring-2 focus:ring-blue-300"
                            >
                                <BiUpload /> Escolher Arquivo
                            </label>

                            <input
                                id="file-upload"
                                type="file"
                                className="hidden"
                                onChange={onFileChange}
                            />
                        </div>
                        {file &&
                            <div className="flex items-center gap-5">
                                <p className="text-gray-500 m-0">{file?.name}</p>
                                <button
                                    onClick={() => setFile(null)}
                                    className="rounded flex justify-center items-center w-[20px] h-[20px] text-white bg-plamev-blue-500"
                                >
                                    <BiX />
                                </button>
                            </div>
                        }
                    </div>
                </div>
            }

            {isMobile &&
                <div className="w-[327px] mt-[32px]">
                    <h3 className="text-plamev-dark-400 text-[14px] text-poppins font-bold  mb-2">Dados pessoais</h3>

                    <div className="flex mb-2">
                        <div className="w-full">
                            <input
                                type="text"
                                id="Nome"
                                name="Nome"
                                placeholder="Seu nome"
                                value={nome}
                                onChange={({ target }) => setNome(target.value)}
                                className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                            />
                        </div>
                    </div>

                    <div className="flex mb-2 flex-col sm:flex-row justify-between items-center gap-4">
                        <div className="flex relative flex-1 w-[100%] sm:w-auto">
                            <input
                                type="text"
                                placeholder="CEP"
                                value={inputMask(zipCode, 'cep')}
                                onChange={({ target }) => setZipCode(target.value)}
                                className="bg-plamev-light-50 flex-1 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                            />

                            <div className="absolute top-[15px] right-[10px]">
                                <button type="button" onClick={() => handleSearchCep()}>
                                    <Image src={IconSeash} alt="Pesquisar CEP" />
                                </button>
                            </div>
                        </div>

                        <select
                            value={state}
                            onChange={({ target }) => setState(target.value)}
                            className="bg-plamev-light-50 py-3 flex-1 border-plamev-dark-50 border-2 border-solid rounded-md w-full pl-2"
                        >
                            <option value="">Estado</option>
                            {dataStates.length > 0 && dataStates.map((item, key: number) => (
                                <option value={item.Id} key={key}>{item.Nome}</option>
                            ))}
                        </select>

                        <select
                            value={city}
                            onChange={({ target }) => setCity(target.value)}
                            className="bg-plamev-light-50 py-3 flex-1 border-plamev-dark-50 border-2 border-solid rounded-md w-full pl-2"
                        >
                            <option value="">Cidade</option>
                            {cities.length > 0 && cities.map((item, key: number) => (
                                <option value={item.Id} key={key}>{item.Nome}</option>
                            ))}
                        </select>
                    </div>

                    <div className="flex mb-2 flex-col sm:flex-row justify-between items-center gap-4">
                        <input
                            type="text"
                            placeholder="Endereço"
                            value={address}
                            onChange={({ target }) => setAddress(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />

                        <input
                            type="text"
                            placeholder="Bairro"
                            value={district}
                            onChange={({ target }) => setDistrict(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />
                    </div>

                    <div className="flex mb-2 flex-col sm:flex-row justify-between items-center gap-4">
                        <input
                            type="text"
                            placeholder="Número"
                            value={number}
                            onChange={({ target }) => setNumber(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />

                        <input
                            type="text"
                            placeholder="Complemento"
                            value={complement}
                            onChange={({ target }) => setComplement(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />
                    </div>

                    <h3 className="text-plamev-dark-400 text-[14px] text-poppins font-bold mb-2">Dados de contato</h3>

                    <div className="flex mb-2  flex-col sm:flex-row justify-between items-center gap-4">
                        <input
                            type="email"
                            placeholder="E-mail"
                            value={email}
                            onChange={({ target }) => setEmail(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />
                    </div>

                    <div className="flex mb-2  flex-col sm:flex-row justify-between items-center gap-4">
                        <input
                            type="text"
                            placeholder="Telefone de Contato"
                            maxLength={15}
                            value={inputMask(phoneNumber, 'telefone')}
                            onChange={({ target }) => setPhoneNumber(target.value)}
                            className="bg-plamev-light-50 border-plamev-dark-50 border-2 border-solid rounded-md w-full h-[52px] pl-2"
                        />
                    </div>

                    <h3 className="text-plamev-dark-400 text-[14px] text-poppins font-bold  mb-2">
                        Está trabalhando atualmente?
                    </h3>

                    <div className="flex mb-2  items-center gap-5">
                        <div className="flex gap-3">
                            <input
                                type="radio"
                                id="sim"
                                onClick={() => setAualmenteTrabalhando(true)}
                                checked={atualmenteTrabalhando}
                            />
                            <label htmlFor="sim">Sim</label>
                        </div>

                        <div className="flex gap-3">
                            <input
                                type="radio"
                                id="nao"
                                onClick={() => setAualmenteTrabalhando(false)}
                                checked={!atualmenteTrabalhando}
                            />
                            <label htmlFor="nao">Não</label>
                        </div>
                    </div>

                    <h3 className="text-plamev-dark-400 text-[14px] text-poppins font-bold  mb-2">Anexar currículo</h3>
                    <div className="flex mb-2  flex-col sm:flex-row  items-center gap-5">
                        <div className="flex flex-col items-center">
                            <label
                                htmlFor="file-upload"
                                className="cursor-pointer flex gap-5 justify-center items-center w-[219px] h-[54px] bg-plamev-dark-50 text-plamev-blue-900 rounded-md shadow focus:outline-none focus:ring-2 focus:ring-blue-300"
                            >
                                <BiUpload /> Escolher Arquivo
                            </label>

                            <input
                                id="file-upload"
                                type="file"
                                className="hidden"
                                onChange={onFileChange}
                            />
                        </div>
                        {file &&
                            <div className="flex items-center gap-5">
                                <p className="text-gray-500 m-0">{file?.name}</p>
                                <button
                                    onClick={() => setFile(null)}
                                    className="rounded flex justify-center items-center w-[20px] h-[20px] text-white bg-plamev-blue-500"
                                >
                                    <BiX />
                                </button>
                            </div>
                        }
                    </div>
                </div>
            }

            {!isMobile &&
                <div
                    className="w-[816px] flex justify-center border-t-[2px] mt-[32px] border-dashed pt-[32px] pb-[32px]"
                >
                    <button
                        type="button"
                        onClick={() => handleRegisterCurriculo()}
                        className="bg-plamev-yellow-500 text-white w-[219px] h-[54px] flex justify-center items-center rounded-[8px]"
                    >
                        Cadastrar para a vaga
                    </button>
                </div>
            }

            {isMobile &&
                <div
                    className="w-[327px] flex justify-center border-t-[2px] mt-[32px] border-dashed pt-[32px] pb-[32px]"
                >
                    <button
                        type="button"
                        onClick={() => handleRegisterCurriculo()}
                        className="bg-plamev-yellow-500 text-white w-[219px] h-[54px] flex justify-center items-center rounded-[8px]"
                    >
                        Cadastrar para a vaga
                    </button>
                </div>
            }

            {modalSuccess &&
                <div
                    className="h-full w-full fixed top-0 z-40 bg-zinc-900/[.70] flex justify-center items-center"
                    onClick={() => handleCloseModalSuccess()}
                >
                    <div className="w-[350px] h-[300px] w-sm-[850px] h-sm-[500px] bg-white rounded-[30px]">
                        <div className="flex justify-end items-center p-5 pb-2">
                            <div
                                className="text-plamev-dark-500 font-thin text-[25px] cursor-pointer"
                                onClick={() => handleCloseModalSuccess()}
                            >
                                <IoMdClose />
                            </div>
                        </div>

                        <div className="flex flex-col items-center justify-center w-[300px] mx-auto">
                            <Image
                                src={IconCadastroRealizado}
                                alt="Cadastro realizado com sucesso!"
                            />
                            <h2 className="text-poppins font-bold text-[24px] text-center text-plamev-blue-500 leading-[24px] mt-[32px] mb-[1rem]">
                                Cadastro realizado com sucesso!
                            </h2>
                            <p className="text-center text-plamev-dark-500 text-[16px] leading-[16px]">
                                Recebemos o seu currículo, aguarde mais instruções para os próximos passos em seu
                                e-mail.
                            </p>
                        </div>
                    </div>
                </div>
            }
        </div>
    )
}