'use client';

import { useJobDraft } from './job-draft-context';
import { 
  BriefcaseIcon,
  MapPinIcon,
  CurrencyEuroIcon,
  UserGroupIcon,
  GiftIcon,
  ExclamationTriangleIcon,
  ClockIcon,
  HomeIcon,
  CheckBadgeIcon,
  AcademicCapIcon,
  BuildingOfficeIcon,
  CalendarIcon,
  DocumentTextIcon,
} from '@heroicons/react/24/outline';
import { 
  SparklesIcon,
  CheckCircleIcon,
  StarIcon,
} from '@heroicons/react/24/solid';

const ICON_SIZES = {
  xs: 'w-3 h-3',
  sm: 'w-4 h-4',
  md: 'w-5 h-5',
  lg: 'w-6 h-6',
} as const;

function formatLocation(location: any): string {
  if (!location) return '';
  const parts = [];
  if (location.city) parts.push(location.city);
  if (location.postalCode) parts.push(`(${location.postalCode})`);
  if (location.department) parts.push(location.department);
  if (location.remote && location.remote !== 'none') {
    if (location.remote === 'partial') parts.push('• Télétravail partiel');
    if (location.remote === 'full') parts.push('• Télétravail complet');
  }
  return parts.join(' ');
}

// ========== NOUVELLE FONCTION DE RENDU ==========
function renderTextContent(content: any) {
  if (!content?.content) return null;

  const textContent = content.content?.[0]?.content?.[0]?.text;
  if (textContent && typeof textContent === 'string') {
    const lines = textContent.split('\n');
    let html = '';
    let inList = false;

    lines.forEach((line) => {
      const trimmed = line.trim();
      
      if (!trimmed) {
        if (inList) {
          html += '</ul>';
          inList = false;
        }
        html += '<div class="h-2"></div>';
        return;
      }

      // Titre numéroté
      const titleMatch = trimmed.match(/^(\d+)\.\s+(.+)$/);
      if (titleMatch) {
        if (inList) {
          html += '</ul>';
          inList = false;
        }
        html += `<h3 class="text-md font-bold mt-6 mb-3 text-gray-900">${titleMatch[1]}. ${titleMatch[2]}</h3>`;
        return;
      }

      // Bullet point
      const bulletMatch = trimmed.match(/^[·•\-]\s+(.+)$/);
      if (bulletMatch) {
        if (!inList) {
          html += '<ul class="list-disc list-outside space-y-2 mb-4 text-gray-800 ml-6">';
          inList = true;
        }
        html += `<li class="pl-2 leading-relaxed">${bulletMatch[1]}</li>`;
        return;
      }

      // Texte normal
      if (inList) {
        html += '</ul>';
        inList = false;
      }
      html += `<p class="mb-3 text-gray-800 leading-relaxed">${trimmed}</p>`;
    });

    if (inList) html += '</ul>';

    return <div dangerouslySetInnerHTML={{ __html: html }} />;
  }

  return null;
}

export default function JobPreview() {
  const { job } = useJobDraft();

  if (!job) {
    return (
      <div className="bg-white rounded-xl shadow-lg p-8 text-center text-gray-500">
        <p>Aucune offre à prévisualiser</p>
      </div>
    );
  }

  const locationText = formatLocation(job.location);

  return (
    <div className="bg-white rounded-xl shadow-lg overflow-hidden max-w-5xl mx-auto">
      {/* HEADER */}
      <div className="bg-gradient-to-r from-blue-600 via-blue-700 to-indigo-700 p-8">
        
        {job.offerType === 'premium' && (
          <div className="inline-flex items-center gap-2 bg-yellow-400 text-yellow-900 px-4 py-2 rounded-full text-sm font-bold mb-4">
            <StarIcon className={ICON_SIZES.sm} />
            OFFRE PREMIUM
          </div>
        )}

        <div className="flex items-start justify-between gap-4 mb-4">
          <h1 className="text-4xl font-black text-gray-900 flex-1">
            {job.title || 'Sans titre'}
          </h1>
          
         <button className="btn btn-primary px-8 py-3.5 text-sm font-bold shadow-lg flex-shrink-0 hover:shadow-xl transition-all">
			📩 Publier
			</button>
        </div>

        {job.company && (
          <div className="flex items-center gap-2 text-xl mb-6 text-gray-800">
            <BuildingOfficeIcon className={ICON_SIZES.md} />
            <span className="font-semibold">{job.company}</span>
          </div>
        )}

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 text-sm">
          {locationText && (
            <div className="flex items-center gap-2 bg-white/90 rounded-lg px-4 py-3 text-gray-900">
              <MapPinIcon className={ICON_SIZES.md} />
              <span className="font-medium">{locationText}</span>
            </div>
          )}
          
          {job.contractType && (
            <div className="flex items-center gap-2 bg-white/90 rounded-lg px-4 py-3 text-gray-900">
              <BriefcaseIcon className={ICON_SIZES.md} />
              <span className="font-medium">{job.contractType}</span>
            </div>
          )}
          
          {job.workSchedule && (
            <div className="flex items-center gap-2 bg-white/90 rounded-lg px-4 py-3 text-gray-900">
              <ClockIcon className={ICON_SIZES.md} />
              <span className="font-medium">{job.workSchedule}</span>
            </div>
          )}
          
          {(job.salaryMin > 0 || job.salaryMax > 0) && (
            <div className="flex items-center gap-2 bg-white/90 rounded-lg px-4 py-3 text-gray-900">
              <CurrencyEuroIcon className={ICON_SIZES.md} />
              <span className="font-medium">
                {job.salaryMin > 0 && job.salaryMax > 0 
                  ? `${job.salaryMin.toLocaleString()} - ${job.salaryMax.toLocaleString()} €`
                  : job.salaryMin > 0 
                  ? `À partir de ${job.salaryMin.toLocaleString()} €`
                  : `Jusqu'à ${job.salaryMax.toLocaleString()} €`
                }
                {job.salaryUnit === 'monthly' ? '/mois' : '/an'}
              </span>
            </div>
          )}

          {job.workMode && (
            <div className="flex items-center gap-2 bg-white/90 rounded-lg px-4 py-3 text-gray-900">
              <HomeIcon className={ICON_SIZES.md} />
              <span className="font-medium">{job.workMode}</span>
            </div>
          )}

          {job.startDate && (
            <div className="flex items-center gap-2 bg-white/90 rounded-lg px-4 py-3 text-gray-900">
              <CalendarIcon className={ICON_SIZES.md} />
              <span className="font-medium">Début : {job.startDate}</span>
            </div>
          )}
        </div>
      </div>

      {/* CONTENU */}
      <div className="p-8 space-y-8">
        
        {/* DESCRIPTION */}
        {job.description && (
          <section className="bg-gray-50 rounded-xl p-6">
            <h2 className="text-2xl font-bold mb-4 flex items-center gap-3 text-gray-900">
              <DocumentTextIcon className={ICON_SIZES.md} />
              Description du poste
            </h2>
            <div className="prose prose-sm max-w-none">
              {renderTextContent(job.description)}
            </div>
          </section>
        )}

        {/* MISSIONS */}
        {job.missions && (
          <section className="border-l-4 border-blue-600 pl-6">
            <h2 className="text-2xl font-bold mb-4 flex items-center gap-3 text-gray-900">
              <CheckBadgeIcon className={ICON_SIZES.md} />
              Vos missions principales
            </h2>
            <div className="prose prose-sm max-w-none">
              {renderTextContent(job.missions)}
            </div>
          </section>
        )}

        {/* PROFIL */}
        {job.candidateProfile && (
          <section className="border-l-4 border-green-600 pl-6">
            <h2 className="text-2xl font-bold mb-4 flex items-center gap-3 text-gray-900">
              <UserGroupIcon className={ICON_SIZES.md} />
              Profil recherché
            </h2>
            <div className="prose prose-sm max-w-none">
              {renderTextContent(job.candidateProfile)}
            </div>
          </section>
        )}

        {/* COMPÉTENCES - COULEUR CHANGÉE */}
        {job.skills && job.skills.length > 0 && (
          <section className="bg-blue-50 rounded-xl p-6">
            <h2 className="text-2xl font-bold mb-4 flex items-center gap-3 text-gray-900">
              <BriefcaseIcon className={ICON_SIZES.md} />
              Compétences techniques requises
            </h2>
            <div className="flex flex-wrap gap-2">
              {job.skills.map((skill: string, index: number) => (
                <span key={index} className="px-4 py-2 bg-blue-600 text-blue-50 rounded-full text-sm font-medium shadow-sm">
                  {skill}
                </span>
              ))}
            </div>
          </section>
        )}

        {/* SOFT SKILLS - COULEUR CHANGÉE */}
        {job.softSkills && job.softSkills.length > 0 && (
          <section className="bg-purple-50 rounded-xl p-6">
            <h2 className="text-2xl font-bold mb-4 flex items-center gap-3 text-gray-900">
              <UserGroupIcon className={ICON_SIZES.md} />
              Qualités humaines recherchées
            </h2>
            <div className="flex flex-wrap gap-2">
              {job.softSkills.map((skill: string, index: number) => (
                <span key={index} className="px-4 py-2 bg-purple-600 text-purple-50 rounded-full text-sm font-medium shadow-sm">
                  {skill}
                </span>
              ))}
            </div>
          </section>
        )}

        {/* AVANTAGES */}
        {job.benefits && job.benefits.length > 0 && (
          <section className="bg-green-50 rounded-xl p-6">
            <h2 className="text-2xl font-bold mb-4 flex items-center gap-3 text-gray-900">
              <GiftIcon className={ICON_SIZES.md} />
              Avantages proposés
            </h2>
            <ul className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {job.benefits.map((benefit: string, index: number) => (
                <li key={index} className="flex items-start gap-3 text-gray-800 bg-white rounded-lg p-3 shadow-sm">
                  <CheckCircleIcon className={`${ICON_SIZES.md} text-green-600 flex-shrink-0 mt-0.5`} />
                  <span className="font-medium">{benefit}</span>
                </li>
              ))}
            </ul>
          </section>
        )}

        {/* AMÉNAGEMENTS SENIORS */}
        {job.seniorAdaptations && job.seniorAdaptations.length > 0 && (
          <section className="bg-indigo-50 rounded-xl p-6">
            <h2 className="text-2xl font-bold mb-4 flex items-center gap-3 text-gray-900">
              <AcademicCapIcon className={ICON_SIZES.md} />
              Aménagements seniors
            </h2>
            <ul className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {job.seniorAdaptations.map((adaptation: string, index: number) => (
                <li key={index} className="flex items-start gap-3 text-gray-800 bg-white rounded-lg p-3 shadow-sm">
                  <CheckCircleIcon className={`${ICON_SIZES.md} text-indigo-600 flex-shrink-0 mt-0.5`} />
                  <span className="font-medium">{adaptation}</span>
                </li>
              ))}
            </ul>
          </section>
        )}

        {/* CONTRAINTES */}
        {job.constraints && job.constraints.length > 0 && (
          <section className="bg-orange-50 rounded-xl p-6 border-2 border-orange-200">
            <h2 className="text-2xl font-bold mb-4 flex items-center gap-3 text-gray-900">
              <ExclamationTriangleIcon className={ICON_SIZES.md} />
              Points d'attention
            </h2>
            <ul className="space-y-3">
              {job.constraints.map((constraint: string, index: number) => (
                <li key={index} className="flex items-start gap-3 text-gray-800 bg-white rounded-lg p-3 shadow-sm">
                  <ExclamationTriangleIcon className={`${ICON_SIZES.md} text-orange-600 flex-shrink-0 mt-0.5`} />
                  <span className="font-medium">{constraint}</span>
                </li>
              ))}
            </ul>
          </section>
        )}

        {/* FOOTER */}
        <div className="border-t-2 pt-6 text-center">
          <p className="text-sm text-gray-500 italic">
            Cette offre respecte les principes de non-discrimination et d'égalité des chances conformément à la législation en vigueur.
          </p>
        </div>
      </div>
    </div>
  );
}
