import { useEffect, useRef } from 'react';
import type { Locale } from '../../data/site';
import { buildCvLeadFormMessage, buildLeadFormUrl } from '../../data/lead-form';
import type { ProfessionSlug } from '../../data/navigation';
import { localizedPath } from '../../i18n/utils';
import { flagIconClass } from '../../lib/countries/flag';

export type CVDetail = {
  slug: string;
  name: string;
  photo?: string;
  country: string;
  countryLabel: string;
  countryIsoCode: string;
  profession: string;
  professionLabel: string;
  age: number;
  experienceYears: number;
  experienceNote?: string;
  educationLevelLabel?: string;
  religionLabel?: string;
  maritalStatusLabel?: string;
  serviceType?: string;
  serviceTypeLabel?: string;
  skills: string[];
  languages: string[];
  salary?: number;
  priceType?: string;
  priceTypeLabel?: string;
  hasVideo: boolean;
  bio?: string;
  waHref: string;
};

type Labels = {
  nationality: string;
  profession: string;
  age: string;
  experience: string;
  salary: string;
  skills: string;
  languages: string;
  maritalStatus: string;
  educationLevel: string;
  serviceType: string;
  bookViaWhatsApp: string;
  requestViaForm: string;
  musanedNote: string;
  close: string;
  basicInfo: string;
  religion: string;
  videoAvailable: string;
  perMonth: string;
  years: string;
};

type Props = {
  cv: CVDetail | null;
  locale: Locale;
  labels: Labels;
  onClose: () => void;
};

export default function CVDetailDialog({ cv, locale, labels, onClose }: Props) {
  const dialogRef = useRef<HTMLDialogElement>(null);

  useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;

    if (cv) {
      if (!dialog.open) dialog.showModal();
    } else if (dialog.open) {
      dialog.close();
    }
  }, [cv]);

  useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;

    function handleClose() {
      onClose();
    }

    dialog.addEventListener('close', handleClose);
    return () => dialog.removeEventListener('close', handleClose);
  }, [onClose]);

  return (
    <dialog ref={dialogRef} className="modal" onClick={(e) => e.target === dialogRef.current && dialogRef.current?.close()}>
      {cv && (
        <div className="modal-box max-w-4xl max-h-[90vh] overflow-y-auto p-0">
          <button
            type="button"
            className="btn btn-sm btn-circle absolute inset-s-3 top-3 z-10"
            onClick={() => dialogRef.current?.close()}
            aria-label={labels.close}
          >
            ✕
          </button>

          <div className="grid gap-0 lg:grid-cols-5">
            <div className="bg-base-200 p-6 lg:col-span-2">
              {cv.photo ? (
                <img src={cv.photo} alt={cv.name} className="aspect-square w-full rounded-box object-cover shadow-md" />
              ) : (
                <div className="flex aspect-square w-full items-center justify-center rounded-box bg-base-300">
                  <svg className="h-24 w-24 text-base-content/30" fill="currentColor" viewBox="0 0 256 256" aria-hidden="true">
                    <path d="M230.92 212c-15.23-26.33-38.7-45.21-66.09-54.16a72 72 0 1 0-73.66 0C63.78 166.79 40.31 185.67 25.08 212a8 8 0 1 0 13.85 8c18.84-32.56 52.14-52 89.07-52s70.23 19.44 89.07 52a8 8 0 1 0 13.85-8Z" />
                  </svg>
                </div>
              )}

              <div className="mt-4 space-y-3">
                {cv.hasVideo && (
                  <span className="badge badge-accent">{labels.videoAvailable}</span>
                )}
                {cv.salary && (
                  <div className="card card-border bg-base-100">
                    <div className="card-body py-4">
                      <p className="text-sm text-base-content/60">{labels.salary}</p>
                      <p className="text-2xl font-bold text-primary">
                        {cv.salary} <span className="icon-saudi_riyal"/> <span className="text-base-content/60 text-sm">{cv.priceTypeLabel ?? labels.perMonth}</span>
                      </p>
                    </div>
                  </div>
                )}
                <a
                  href={cv.waHref}
                  target="_blank"
                  rel="noopener noreferrer"
                  data-gads-conversion="whatsapp"
                  className="btn btn-block btn-lg border-0 text-white"
                  style={{ backgroundColor: '#25d366' }}
                >
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="h-5 w-5" aria-hidden="true">
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.435 9.884-9.883 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                  </svg>
                  {labels.bookViaWhatsApp}
                </a>
                <a
                  href={buildLeadFormUrl(locale, {
                    serviceCategory: 'recruitment',
                    profession: cv.profession as ProfessionSlug,
                    nationality: cv.country,
                    message: buildCvLeadFormMessage(
                      locale,
                      {
                        slug: cv.slug,
                        name: cv.name,
                        professionLabel: cv.professionLabel,
                        countryLabel: cv.countryLabel,
                        age: cv.age,
                        experienceYears: cv.experienceYears,
                        experienceNote: cv.experienceNote,
                      },
                      labels.years,
                    ),
                  })}
                  className="btn btn-block btn-outline btn-primary"
                >
                  {labels.requestViaForm}
                </a>
                <div role="alert" className="alert alert-info text-sm">
                  <span>{labels.musanedNote}</span>
                </div>
              </div>
            </div>

            <div className="space-y-6 p-6 lg:col-span-3">
              <div>
                <h2 className="text-2xl font-bold">{cv.name}</h2>
                <p className="mt-1 text-base-content/70">
                  {cv.professionLabel} · <span className={flagIconClass(cv.countryIsoCode)} aria-hidden="true" /> {cv.countryLabel}
                </p>
              </div>

              <div className="card card-border bg-base-100">
                <div className="card-body">
                  <h3 className="card-title text-lg">{labels.basicInfo}</h3>
                  <div className="overflow-x-auto">
                    <table className="table">
                      <tbody>
                        {cv.serviceTypeLabel && (
                          <tr>
                            <td className="w-40 font-medium text-base-content/60">{labels.serviceType}</td>
                            <td>{cv.serviceTypeLabel}</td>
                          </tr>
                        )}
                        <tr>
                          <td className="w-40 font-medium text-base-content/60">{labels.nationality}</td>
                          <td><span className={flagIconClass(cv.countryIsoCode)} aria-hidden="true" /> {cv.countryLabel}</td>
                        </tr>
                        <tr>
                          <td className="font-medium text-base-content/60">{labels.profession}</td>
                          <td>
                            <a href={localizedPath(locale, `professions/${cv.profession}`)} className="link link-primary">
                              {cv.professionLabel}
                            </a>
                          </td>
                        </tr>
                        <tr>
                          <td className="font-medium text-base-content/60">{labels.age}</td>
                          <td>{cv.age} {labels.years}</td>
                        </tr>
                        <tr>
                          <td className="font-medium text-base-content/60">{labels.experience}</td>
                          <td>
                            {cv.experienceYears} {labels.years}
                            {cv.experienceNote ? ` (${cv.experienceNote})` : ''}
                          </td>
                        </tr>
                        {cv.educationLevelLabel && (
                          <tr>
                            <td className="font-medium text-base-content/60">{labels.educationLevel}</td>
                            <td>{cv.educationLevelLabel}</td>
                          </tr>
                        )}
                        {cv.religionLabel && (
                          <tr>
                            <td className="font-medium text-base-content/60">{labels.religion}</td>
                            <td>{cv.religionLabel}</td>
                          </tr>
                        )}
                        {cv.maritalStatusLabel && (
                          <tr>
                            <td className="font-medium text-base-content/60">{labels.maritalStatus}</td>
                            <td>{cv.maritalStatusLabel}</td>
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>

              {cv.languages.length > 0 && (
                <div className="card card-border bg-base-100">
                  <div className="card-body">
                    <h3 className="card-title text-lg">{labels.languages}</h3>
                    <div className="mt-2 flex flex-wrap gap-2">
                      {cv.languages.map((language) => (
                        <span key={language} className="badge badge-outline badge-lg">{language}</span>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {cv.skills.length > 0 && (
                <div className="card card-border bg-base-100">
                  <div className="card-body">
                    <h3 className="card-title text-lg">{labels.skills}</h3>
                    <div className="mt-2 flex flex-wrap gap-2">
                      {cv.skills.map((skill) => (
                        <span key={skill} className="badge badge-secondary badge-soft badge-lg">{skill}</span>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {cv.bio && (
                <div className="prose prose-sm max-w-none">
                  {cv.bio.split(/\n{2,}/).map((paragraph, i) => (
                    <p key={i}>{paragraph}</p>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
      <form method="dialog" className="modal-backdrop">
        <button type="submit">{labels.close}</button>
      </form>
    </dialog>
  );
}
