'use client';

import Link from 'next/link';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import CareersHeader from '@/components/careers/CareersHeader';
import CareersFooter from '@/components/careers/CareersFooter';
import {
  fetchPublicJob, fetchPublicJobs, applyToJob, timeAgo,
  captureTracking, getTrackingToken, getLegacySource, type PublicJob,
} from '@/lib/careers';
import { cleanHtmlText } from '@/lib/format';

const SAVED_KEY = 'savedJobs';
const getSaved = (): number[] => {
  if (typeof window === 'undefined') return [];
  try { return JSON.parse(localStorage.getItem(SAVED_KEY) || '[]'); } catch { return []; }
};

export default function CareersJobDetailClient() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const searchParams = useSearchParams();
  // Opaque encrypted tracking token from the published link (?t=...). The
  // platform it encodes is resolved by the backend — never read here.
  const urlToken = searchParams.get('t');
  // Legacy plain source, still honoured for links published before tokens.
  const urlSource = searchParams.get('source') || searchParams.get('utm_source');

  const [job, setJob] = useState<PublicJob | null>(null);
  const [related, setRelated] = useState<PublicJob[]>([]);
  const [loading, setLoading] = useState(true);
  const [applying, setApplying] = useState(false);
  const [notFound, setNotFound] = useState(false);
  const [saved, setSaved] = useState(false);
  // Local override so the button flips to "Applied" straight after applying,
  // without waiting for a refetch. The authoritative value is job.is_applied,
  // which the API only populates for a logged-in candidate.
  const [justApplied, setJustApplied] = useState(false);

  // Keep the tracking token / legacy source across the register-login detour.
  useEffect(() => {
    captureTracking(urlToken, urlSource);
  }, [urlToken, urlSource]);

  useEffect(() => {
    setLoading(true);
    setJustApplied(false);   // clear the local flag when switching jobs
    fetchPublicJob(id)
      .then((j) => { setJob(j); setSaved(getSaved().includes(Number(id))); })
      .catch(() => setNotFound(true))
      .finally(() => setLoading(false));
    fetchPublicJobs().then((all) => setRelated(all.filter((x) => String(x.id) !== String(id)).slice(0, 5))).catch(() => {});
  }, [id]);

  const applied = justApplied || Boolean(job?.is_applied);
  const appliedAt = job?.applied_at;
  const appliedAtLabel = appliedAt
    ? new Date(appliedAt).toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' })
    : '';

  const onApply = async () => {
    if (!job || applied) return;
    setApplying(true);
    const trackingToken = getTrackingToken(urlToken);
    // Only used when there is no token (a pre-token link); the backend always
    // prefers the token when both are present.
    const finalSource = getLegacySource(urlSource) || 'direct';
    const res = await applyToJob(job.public_id || job.id, finalSource, trackingToken);
    setApplying(false);
    if (res.message === 'not-authenticated') {
      // Carry the opaque token (not the platform name) through registration.
      const trackQs = trackingToken
        ? `&t=${encodeURIComponent(trackingToken)}`
        : `&source=${encodeURIComponent(finalSource)}`;
      router.push(`/register?job=${job.public_id || job.id}${trackQs}`);
      return;
    }
    if (res.ok) {
      setJustApplied(true);
      toast.success(res.message);
    } else {
      // "You have already applied to this job." comes back as a 200 with
      // created=false, but guard here too in case of a race (e.g. two tabs).
      if (/already applied/i.test(res.message)) setJustApplied(true);
      toast.info(res.message);
    }
  };

  const toggleSave = () => {
    if (!job) return;
    const cur = getSaved();
    const next = cur.includes(job.id) ? cur.filter((x) => x !== job.id) : [...cur, job.id];
    localStorage.setItem(SAVED_KEY, JSON.stringify(next));
    setSaved(next.includes(job.id));
    toast.success(next.includes(job.id) ? 'Saved to your list' : 'Removed from saved');
  };

  const highlights = (job?.must_have_skills || '')
    .split(',').map((s) => s.trim()).filter(Boolean);

  // Group recommended jobs by their own associated client, with the current
  // JD's client listed first and the rest alphabetically.
  const currentClient = job?.client_name || 'Indovision Services';
  const relatedByClient = related.reduce<Record<string, PublicJob[]>>((acc, r) => {
    const key = r.client_name || 'Indovision Services';
    (acc[key] ||= []).push(r);
    return acc;
  }, {});
  const clientNames = Object.keys(relatedByClient).sort((a, b) => {
    if (a === currentClient) return -1;
    if (b === currentClient) return 1;
    return a.localeCompare(b);
  });

  return (
    <div className="min-h-screen bg-slate-50">
      <CareersHeader />
      <div className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
        <Link href="/careers/jobs" className="text-sm text-slate-500 hover:text-[#405189]">← Back to jobs</Link>

        {loading ? (
          <p className="text-slate-400 text-sm mt-6">Loading…</p>
        ) : notFound || !job ? (
          <div className="bg-white border border-slate-200 p-10 text-center text-slate-400 mt-6">This position is no longer available.</div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-5 mt-4 items-start">
            {/* ---------------- MAIN (left) ---------------- */}
            <div className="lg:col-span-2 space-y-5">
              {/* Header card */}
              <div className="bg-white border border-slate-200 p-6 shadow-sm">
                <div className="flex items-start justify-between gap-4">
                  <div className="min-w-0">
                    <h1 className="text-xl font-black text-slate-800">{job.title}</h1>
                    <p className="text-sm text-[#405189] font-semibold mt-0.5">{job.client_name || 'Indovision Services'}</p>
                    <div className="flex flex-wrap gap-x-5 gap-y-1.5 mt-3 text-sm text-slate-600">
                      <span className="inline-flex items-center gap-1.5"><i className="fa-solid fa-briefcase text-slate-400" />{job.experience_band || 'Not specified'}</span>
                      <span className="inline-flex items-center gap-1.5"><i className="fa-solid fa-indian-rupee-sign text-slate-400" />{job.ctc_band || 'Not Disclosed'}</span>
                      <span className="inline-flex items-center gap-1.5"><i className="fa-solid fa-location-dot text-slate-400" />{job.location || '—'}</span>
                    </div>
                  </div>
                  <div className="w-14 h-14 shrink-0 bg-[#405189]/10 flex items-center justify-center text-[#405189] font-black text-lg">
                    {(job.client_name || 'IV').slice(0, 2).toUpperCase()}
                  </div>
                </div>

                <div className="flex flex-wrap items-center justify-between gap-3 mt-5 pt-4 border-t border-slate-100">
                  <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-500">
                    <span>Posted: <b className="text-slate-700">{timeAgo(job.created_at)}</b></span>
                    {job.num_positions ? <span>Openings: <b className="text-slate-700">{job.num_positions}</b></span> : null}
                    <span>Applicants: <b className="text-slate-700">{job.applicants_count ?? 0}</b></span>
                  </div>
                  <div className="flex items-center gap-2">
                    {applied ? (
                      <span
                        title={appliedAtLabel ? `Applied on ${appliedAtLabel}` : 'You have already applied'}
                        className="px-6 py-2 text-sm font-bold bg-[#0ab39c]/10 text-[#0ab39c] border border-[#0ab39c]/30 inline-flex items-center gap-2 cursor-default"
                      >
                        <i className="fa-solid fa-circle-check" /> Applied
                      </span>
                    ) : (
                      <button onClick={onApply} disabled={applying}
                        className="px-6 py-2 text-sm font-bold bg-[#405189] text-white hover:bg-[#334267] transition disabled:opacity-50">
                        {applying ? 'Applying…' : 'Apply'}
                      </button>
                    )}
                  </div>
                </div>
              </div>

              {/* Job highlights */}
              {(highlights.length > 0 || job.qualifications || job.certification) && (
                <div className="bg-white border border-slate-200 p-6 shadow-sm">
                  <h2 className="font-bold text-slate-800 mb-3">Job highlights</h2>
                  <ul className="space-y-2 text-sm text-slate-700">
                    {highlights.slice(0, 8).map((h, i) => (
                      <li key={i} className="flex gap-2"><i className="fa-solid fa-circle-check text-[#0ab39c] mt-1 text-xs" /><span>{h}</span></li>
                    ))}
                    {job.qualifications && <li className="flex gap-2"><i className="fa-solid fa-circle-check text-[#0ab39c] mt-1 text-xs" /><span>Qualification: {job.qualifications}</span></li>}
                    {job.certification && <li className="flex gap-2"><i className="fa-solid fa-circle-check text-[#0ab39c] mt-1 text-xs" /><span>Certification: {job.certification}</span></li>}
                  </ul>
                </div>
              )}

              {/* Job description */}
              <div className="bg-white border border-slate-200 p-6 shadow-sm">
                <h2 className="font-bold text-slate-800 mb-3">Job description</h2>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4">
                  {[
                    ['Department', job.department], ['Shift', job.shift], ['Working days', job.working_days],
                    ['Notice period', job.notice_period], ['Good-to-have', job.good_to_have_skills],
                  ].map(([k, v]) => v ? (
                    <div key={k as string} className="bg-slate-50 border border-slate-100 p-2.5">
                      <p className="text-[10px] uppercase font-bold text-slate-400">{k}</p>
                      <p className="text-xs text-slate-700 mt-0.5">{v as string}</p>
                    </div>
                  ) : null)}
                </div>
                {job.work_details ? (
                  <p className="text-sm text-slate-700 whitespace-pre-line leading-relaxed">{cleanHtmlText(job.work_details)}</p>
                ) : (
                  <p className="text-sm text-slate-400">No detailed description provided.</p>
                )}
                <div className="mt-6">
                  {applied ? (
                    <div className="inline-flex flex-col gap-1">
                      <span className="px-8 py-2.5 bg-[#0ab39c]/10 text-[#0ab39c] border border-[#0ab39c]/30 font-bold text-sm inline-flex items-center gap-2 cursor-default">
                        <i className="fa-solid fa-circle-check" /> Applied
                      </span>
                      {appliedAtLabel && (
                        <span className="text-xs text-slate-500">You applied on {appliedAtLabel}.</span>
                      )}
                    </div>
                  ) : (
                    <button onClick={onApply} disabled={applying}
                      className="px-8 py-2.5 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition disabled:opacity-50">
                      {applying ? 'Applying…' : 'Apply for this role'}
                    </button>
                  )}
                </div>
              </div>
            </div>

            {/* ---------------- SIDEBAR (right): related roles grouped by client ---------------- */}
            <div className="lg:col-span-1 space-y-5">
              {related.length === 0 ? (
                <div className="bg-white border border-slate-200 p-5 shadow-sm">
                  <h3 className="font-bold text-slate-800 mb-1">{currentClient} roles</h3>
                  <p className="text-xs text-slate-400 mb-3">you might be interested in</p>
                  <p className="text-xs text-slate-400">No other openings right now.</p>
                </div>
              ) : (
                clientNames.map((client) => (
                  <div key={client} className="bg-white border border-slate-200 p-5 shadow-sm">
                    <h3 className="font-bold text-slate-800 mb-1">{client} roles</h3>
                    <p className="text-xs text-slate-400 mb-3">you might be interested in</p>
                    <div className="divide-y divide-slate-100">
                      {relatedByClient[client].map((r) => (
                        <Link key={r.id} href={`/careers/jobs/${r.public_id || r.id}`} className="block py-3 hover:bg-slate-50 -mx-2 px-2 transition">
                          <p className="font-bold text-sm text-slate-800 leading-snug">{r.title}</p>
                          <div className="flex flex-col gap-0.5 mt-1.5 text-xs text-slate-500">
                            {r.experience_band && <span><i className="fa-solid fa-briefcase mr-1.5 text-slate-400" />{r.experience_band}</span>}
                            {r.location && <span><i className="fa-solid fa-location-dot mr-1.5 text-slate-400" />{r.location}</span>}
                            <span className="text-[11px] text-slate-400 mt-0.5">Posted {timeAgo(r.created_at)}</span>
                          </div>
                        </Link>
                      ))}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        )}
      </div>
      <CareersFooter />
    </div>
  );
}
