import { useEffect, useState } from 'react';
import { FiAlertCircle, FiCamera, FiUpload } from 'react-icons/fi';
import { ToastContainer } from "react-toastify";
import useLang from '../hooks/lang';
import "react-toastify/dist/ReactToastify.css";
import '../index.css';
import useToast from '../hooks/toast';

const API = "https://bug-report-api.onrender.com"
const apiKey = "4654f786058b1481334d8e901818c996ffc48c41626e6a29e71858284ed29cda8a6a5ed547a8baca2648c895d2e5f39f93ebcc39c725f5177f7531698ca47e7ce1c758d1d2f10b68f0df149c81464d73c8b160d16081d5a9cab57bcb6d23f92b9f9ffa9354b5e072ef10710a27d8ecb7cdc6813995c8c7d3f287acb915c799db"

interface BugReporter {
  apiKey?: string;
  lang: string;
}

export const API_UPLOAD_IMAGE_URL =
  "https://file.itmafrica.com/api/uploadimage/test";

const BugReporter: React.FC<BugReporter> = ({ lang = "en" }) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [screenshot, setScreenshot] = useState<any>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [show, setshow] = useState(false);
  const [active, setActive] = useState(true);
  const [messageError] = useState<any>({
    fr: "Une erreur est survenue lors de la soumission du rapport !",
    en: "An error occurred while submitting the report !"
  })

  const [message] = useState<any>({
    fr: "Rapport de bug soumis avec succès !",
    en: "Bug report submitted successfully!"
  })
  const { dico } = useLang({ lang })
  const { success, error } = useToast()

  const handleScreenshotChange = (e: any) => {
    if (e.target.files && e.target.files[0]) {
      setScreenshot(e.target.files[0]);
    }
  };


  const uploadImage = async (content: any) => {
    try {
      const response: any = await fetch(API_UPLOAD_IMAGE_URL, {
        method: "POST",
        body: content,
      });
      const data = await response.json();
      return data.uri;
    } catch (error: any) {
      console.log(error)
      return "https://www.itmafrica.com/_next/image?url=https%3A%2F%2Fitmafrica.blob.core.windows.net%2Ftest%2FLogo_RDC.png&w=128&q=75";
    }
  };

  async function register() {
    setIsSubmitting(true)

    const body = new FormData();
    body.append("file", screenshot);

    const picture = await uploadImage(body)

    return fetch(`${API}/api/bug-reports`, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${apiKey}`
      },
      method: "POST",
      body: JSON.stringify({
        data: {
          title,
          description,
          picture,
          type: "bug",
          step: "new",
          originUrl: window.location.origin
        }
      })
    })
      .then(function (res) {
        return res.json()
      })
      .then(function (res) {
        success(message[lang])
        setIsSubmitting(false)
        return res
      })
      .catch(function () {
        setIsSubmitting(false)
        error(messageError[lang]);
      })
  }


  const handleSubmit = async (e: any) => {
    e.preventDefault();
    e.stopPropagation()

    try {

      await register()
      // Réinitialiser le formulaire après soumission réussie
      setTitle('');
      setDescription('');
      setScreenshot(null);
      setshow(false)
    } catch (err) {
      console.log(err)
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(function () {
    document.addEventListener("scroll", function () {
      if (show == false) {
        setActive(false)
      }
    })
    document.addEventListener("scrollend", function () {
      setActive(true)
    })
  }, [show])

  return (
    <>
      {active && <div
        onClick={function (e: any) {
          e.preventDefault();
          e.stopPropagation()
          setshow(function (state) {
            return !state
          })
        }}
        className="space-y-1 p-3 transition-all duration-300 hover:shadow-3xl rounded-full shadow-2xl fixed z-50 cursor-pointer bg-white bottom-[10px] right-[10px] rounded-full"
      >
        <h2 title={dico("bug.reporter.title")} className="text-md text-center font-bold text-gray-900 flex items-center justify-center">
          <FiAlertCircle className="text-xl text-yellow-500 animate-pulse" />
        </h2>
      </div>}
      {show &&
        <div
          onClick={function (e) {
            e.stopPropagation()
            setshow(false)
          }}
          className="w-full z-50 fixed z-50 bottom-[15px] right-[15px] flex items-center justify-end"
        >
          <form
            onClick={function (e) {
              e.stopPropagation()
            }}
            onSubmit={handleSubmit}
            className="max-w-3xs lg:max-w-2xs bg-white p-5 rounded-xl shadow-2xl transform transition-all duration-300 hover:shadow-3xl"
          >
            <div className="space-y-1">
              <h2 className="text-3xl font-bold text-gray-900 flex items-center">
                <FiAlertCircle className="mr-3 text-yellow-500 animate-pulse" />
                {dico("bug.reporter.title")}
              </h2>
              <p className="text-sm text-gray-500">
                {dico("bug.reporter.description")}
              </p>
            </div>
            {/* Titre */}
            <div className="space-y-1 mt-5">
              <div className="flex items-center justify-between">
                <label htmlFor="title" className="block text-sm font-medium text-gray-700">
                  {dico("bug.reporter.titleBug")}
                </label>
                <span className="text-sm text-gray-500">{title.length}/100</span>
              </div>
              <input
                type="text"
                id="title"
                value={title}
                onChange={(e) => setTitle(e.target.value.slice(0, 100))}
                required
                className="block w-full px-4 py-3 rounded-lg border-2 border-gray-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition-all"
                placeholder={dico("bug.reporter.placeholderTitleBug")}
              />
            </div>
            {/* Description */}
            <div className="space-y-1 pt-2">
              <div className="flex items-center justify-between">
                <label htmlFor="description" className="block text-sm font-medium text-gray-700">
                  {dico("bug.reporter.descriptionBug")}
                </label>
                <span className="text-sm text-gray-500">{description.length}/500</span>
              </div>
              <textarea
                id="description"
                value={description}
                onChange={(e) => setDescription(e.target.value.slice(0, 500))}
                required
                rows={5}
                className="block w-full px-4 py-3 rounded-lg border-2 border-gray-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition-all"
                placeholder={dico("bug.reporter.placeholderDescription")}
              />
            </div>
            {/* Capture d'écran */}
            <div className="space-y-1 pt-2">
              <label className="block text-sm font-medium text-gray-700">
                {dico("bug.reporter.captureBug")}
              </label>
              <div className="relative group">
                <label className="flex flex-col items-center justify-center p-5 border-2 border-dashed border-gray-200 rounded-lg hover:border-indigo-500 transition-all cursor-pointer">
                  {screenshot ? (
                    <>
                      <img
                        src={URL.createObjectURL(screenshot)}
                        alt="Preview"
                        className="w-32 h-32 object-cover rounded-md mb-4"
                      />
                      <span className="text-indigo-600 font-medium">{screenshot.name}</span>
                    </>
                  ) : (
                    <>
                      <FiCamera className="w-8 h-8 text-gray-400 group-hover:text-indigo-500 transition-all" />
                      <span className="mt-2 text-sm text-gray-500 group-hover:text-indigo-600 transition-all">
                        {dico("bug.reporter.placeholderCaptureBug")}
                      </span>
                    </>
                  )}
                  <input
                    type="file"
                    accept="image/*"
                    onChange={handleScreenshotChange}
                    className="hidden"
                  />
                </label>
                {screenshot && (
                  <button
                    type="button"
                    onClick={() => setScreenshot(null)}
                    className="absolute -top-2 -right-2 p-2 bg-red-500 rounded-full text-white hover:bg-red-600 transition-all"
                  >
                    <FiAlertCircle className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
            {/* Bouton de soumission */}
            <div className="pt-6">
              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full flex items-center justify-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 transition-all transform hover:scale-105"
              >
                {isSubmitting ? (
                  <div className="flex items-center">
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-3"></div>
                    {dico("bug.reporter.soumettreLoading")}
                  </div>
                ) : (
                  <>
                    <FiUpload className="mr-2" />
                    {dico("bug.reporter.soumettre")}
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      }
      <ToastContainer />
    </>
  );
};

export default BugReporter;