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';
import fr from '../dictionaries/fr';

const API = "https://api.bug.itmafrica.com"
const apiKey = "20d5569c4a112ce362057d2020ae4d71a63f0c6976d4c791edcf4bd4376227c8a822bf954e0397052ea6fb34500f36c336fc14e98a56c327ba4aadf9381a1494e296301d4818db6d758e7dd4188dfe59d32b556a4c759d498a8428fc708e4484c91cc58a7ce642e6dab0a1147b3c1e1191126831c92a486037644ac73dfe33ad"
interface BugReporter {
  apiKey?: string;
  lang: string;
}

const BugReporter: React.FC<BugReporter> = ({ lang = "en" }) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [screenshot, setScreenshot] = useState<File | null>(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]);
    }
  };
  async function register() {
    setIsSubmitting(true)
    return fetch(`${API}/api/bug-reports`, {
      headers: {
        "Content-Type": "application/json",
        authorization: `Bearer ${apiKey}`
      },
      method: "post",
      body: JSON.stringify({
        data: {
          title,
          description,
          picture: screenshot ? URL.createObjectURL(screenshot) : "",
          origin: 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-5 right-5 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 bottom-24 right-5 flex items-center justify-end "
        >
          <form
            onClick={function (e) {
              e.stopPropagation()
            }}
            onSubmit={handleSubmit}
            className="max-w-2xl bg-white p-8 bg-white 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-2 mt-8">
              <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-2 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-2 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-8 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;