import { useEffect, useState } from 'react';
import axios from 'axios';
import DOMPurify from 'dompurify';
import SkillRender from './SkillRender'; // Ensure this import is correctly pointing to your SkillRender component

const JobOfferContent = ({ id, skills }) => {
  const [jobOffer, setJobOffer] = useState(null);

  const fetchJobOfferById = async (jobId) => {
    try {
      const response = await axios.get(`https://izaac.knck.pl/api/jobposting/joboffers/${jobId}`);
      setJobOffer(response.data);
    } catch (error) {
      console.error('Failed to fetch job offer:', error);
    }
  };

  const processHTML = (htmlString) => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlString, 'text/html');
    doc.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach((tag) => {
      tag.classList.add('no-tailwindcss-base', 'text-xl');
    });
    doc.querySelectorAll('p').forEach((tag) => {
      tag.classList.add('no-tailwindcss-base', 'text-slate-800', 'text-lg');
    });
    doc.querySelectorAll('ol, ul').forEach((tag) => tag.classList.add('no-tailwindcss-base'));
    doc.querySelectorAll('li').forEach((tag) => tag.classList.add('lista'));
    return doc.body.innerHTML;
  };

  const cleanAndProcessData = (userInput) => {
    const sanitizedHTML = DOMPurify.sanitize(userInput, { USE_PROFILES: { html: true } });
    return processHTML(sanitizedHTML);
  };

  const renderContent = (htmlString) => {
    return <div dangerouslySetInnerHTML={{ __html: cleanAndProcessData(htmlString) }} />;
  };

  useEffect(() => {
    fetchJobOfferById(id);
  }, [id]);

  return (
    <>
      {jobOffer && (
        <>
          <h1 className="my-4 mx-6 text-3xl font-bold text-slate-800">{jobOffer.name} w {jobOffer.company_name}</h1>
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-4">
          {jobOffer.skill_levels && jobOffer.skill_levels.map((skillLevel) => {
              const skill = skills.find((s) => s.id === parseInt(skillLevel.skill_id));
              return skill ? (
                <SkillRender key={skill.id} skill={skill.skill_name} level={skillLevel.skill_level} />
              ) : null;
            })}
          </div>
          <div className="text-slate-800 font-medium mt-4">{renderContent(jobOffer.content)}</div>
        </>
      )}
    </>
  );
};

export default JobOfferContent;
