'use client'

import { useRef, useState } from "react";
import axios, { AxiosError } from "axios";

import { CheckboxInput, Input, Submit } from "./form";
import { FloatingLabel } from "../floating-label";
import { CloudflareTurnstile } from "../turnstile";

export default function ContactForm() {
  const [anon, setAnon] = useState(false);
  const formRef = useRef<HTMLFormElement | null>(null);
  const [status, setStatus] = useState<'success' | 'loading' | 'failed' | 'idle'>('idle');
  const [errorMsg, setErrorMsg] = useState("");

  const statusMsg = {
    success: 'Sended!',
    loading: 'Sending...',
    failed: 'Failed :(',
    idle: 'Send!'
  }

  const send = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setStatus('idle');
    setErrorMsg('');

    if (status == 'loading' || !formRef.current) return;
    
    const formData = new FormData(formRef.current);
    
    const data = {
      anon,
      name: formData.get('name')?.toString(),
      email: formData.get('email')?.toString(),
      message: formData.get('message')!.toString(),
      "cf-turnstile-response": formData.get('cf-turnstile-response')?.toString()
    }
    
    if ((!data.name || !data.email) && !data.anon) {
      setErrorMsg("Name and email are required. Unless you check the box to send anonymously");
      return;
    }
    
    if (data.message.length < 1) {
      setErrorMsg("What do you want to tell me???");
      return;
    }
    
    if (!data["cf-turnstile-response"]) {
      setErrorMsg("Please fill in the captcha");
      return;
    }

    setStatus('loading');

    try {
      await axios.post('/api/contact', data);
      setStatus('success');
    }
    catch (err) {
      setStatus('failed');
      setErrorMsg("Something went wrong, Sorry...");

      if (err instanceof AxiosError) {
        if (err.status == 429) setErrorMsg("Limit reached, please try again later...");
        if (err.status == 403) setErrorMsg("Captcha failed or expired, please try again later");
      }
    }
  }

  return (
    <form action="POST" className="space-y-4" ref={formRef} onSubmit={send}>
      <FloatingLabel placeholder="Leave an anonymous message, but I can't reply to you">
        <CheckboxInput
          name="anon"
          placeholder="Send anonymously🤫"
          onChange={setAnon}
        />
      </FloatingLabel>
      <label className={anon ? "hidden" : "block"} htmlFor="contact-name">
        <div className="mb-2">Name</div>
        <Input
          id="contact-name"
          className="w-full"
          name="name"
          type="text"
          placeholder="Any name you want me to know"
        />
      </label>
      <label className={anon ? "hidden" : "block"} htmlFor="contact-email">
        <div className="mb-2">Email</div>
        <Input
          id="contact-email"
          className="w-full"
          name="email"
          type="email"
        />
      </label>
      <label className="block" htmlFor="contact-msg">
        <div className="mb-2">Message</div>
        <textarea
          name="message"
          id="contact-msg"
          className="max-h-96 h-32 w-full p-3 bg-background border border-primary"
          placeholder="Tell me something cool, or ask question"
        />
      </label>
      <CloudflareTurnstile />
      <div className="text-primary">{errorMsg}</div>
      <Submit disabled={status === "loading"} className="w-full">{statusMsg[status]}</Submit>
    </form>
  );
}
