'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import type { User } from '@/types';
import { api } from '@/lib/api';
import { fetchPublicJobs, fetchPublicJobsPaged, applyToJob, type PublicJob } from '@/lib/careers';
import { completionItems, completionPercent, type CandidateProfile } from './ProfileCompletion';
import CandidateMyApplications from './CandidateMyApplications';

const PAGE_SIZE = 6;

export default function CandidateHome({ user }: { user: User }) {
  const name = user.full_name || user.email.split('@')[0];

  // ---- profile summary (left)
  const [profile, setProfile] = useState<CandidateProfile & Record<string, any>>({});
  const pct = completionPercent(profile as CandidateProfile);
  const pending = completionItems(profile as CandidateProfile).filter((i) => !i.done);

  // ---- jobs (right, paginated)
  const [jobs, setJobs] = useState<PublicJob[]>([]);
  const [count, setCount] = useState(0);
  const [page, setPage] = useState(1);
  const [q, setQ] = useState('');
  const [qInput, setQInput] = useState('');
  const [loading, setLoading] = useState(true);
  const [applying, setApplying] = useState<number | null>(null);
  const totalPages = Math.max(1, Math.ceil(count / PAGE_SIZE));

  // ---- candidate applications
  const [apps, setApps] = useState<any[]>([]);
  const [appsLoading, setAppsLoading] = useState(true);
  const [applyPreviewJob, setApplyPreviewJob] = useState<PublicJob | null>(null);

  const loadApplications = () => {
    setAppsLoading(true);
    api.get('/public/my-applications/')
      .then((res: any) => setApps(res?.data ?? []))
      .catch(() => setApps([]))
      .finally(() => setAppsLoading(false));
  };

  useEffect(() => {
    api.get('/candidates/me/')
      .then((r: any) => {
        const p = r?.data ?? {};
        const skills = Array.isArray(p.skills) ? p.skills.map((s: any) => s?.name ?? s) : [];
        setProfile({ ...p, skills });
      })
      .catch(() => {});

    loadApplications();
  }, []);

  useEffect(() => {
    let alive = true;
    setLoading(true);
    fetchPublicJobsPaged(page, PAGE_SIZE, q)
      .then((res) => {
        if (alive) {
          setJobs(res.results || []);
          setCount(res.count || 0);
        }
      })
      .catch(() => {
        if (alive) {
          setJobs([]);
          setCount(0);
        }
      })
      .finally(() => {
        if (alive) setLoading(false);
      });
    return () => {
      alive = false;
    };
  }, [page, q]);

  const onApply = async (job: PublicJob) => {
    setApplying(job.id);
    const res = await applyToJob(job.public_id || job.id);
    setApplying(null);
    if (res.ok) {
      toast.success(res.message);
      loadApplications();
    } else {
      toast.info(res.message);
    }
  };


  return (
    <>
      <div className="space-y-5">
        {/* Banner */}
        <div className="rounded-none p-6 text-white relative overflow-hidden" style={{ background: 'linear-gradient(135deg,#23b7e5 0%,#405189 100%)' }}>
          <p className="text-sm font-medium opacity-75">Candidate Portal</p>
          <h1 className="text-2xl font-bold mt-0.5">{name} 👋</h1>
          <p className="text-sm opacity-70 mt-1">Track your applications and apply to new roles.</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-5 items-start">
          {/* ---------- LEFT: profile + applied JDs ---------- */}
          <div className="space-y-5 lg:col-span-1">
            {/* Profile summary */}
            <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 shadow-sm">
              <div className="flex items-center gap-3">
                <span className="w-12 h-12 rounded-full bg-[#405189] text-white flex items-center justify-center text-lg font-bold shrink-0">
                  {(name || 'U').charAt(0).toUpperCase()}
                </span>
                <div className="min-w-0">
                  <p className="font-bold text-slate-800 dark:text-white truncate">{profile.first_name ? `${profile.first_name} ${profile.last_name || ''}` : name}</p>
                  <p className="text-xs text-slate-500 truncate">{user.email}</p>
                </div>
              </div>

              {/* completion */}
              <div className="mt-4">
                <div className="flex items-center justify-between mb-1">
                  <span className="text-[11px] font-bold uppercase tracking-wide text-slate-500">Profile completeness</span>
                  <span className={`text-sm font-black ${pct >= 80 ? 'text-emerald-600' : pct >= 50 ? 'text-amber-600' : 'text-rose-600'}`}>{pct}%</span>
                </div>
                <div className="w-full h-2 bg-slate-200 dark:bg-slate-800 rounded-none overflow-hidden">
                  <div className={`h-full ${pct >= 80 ? 'bg-emerald-500' : pct >= 50 ? 'bg-amber-500' : 'bg-rose-500'} transition-all`} style={{ width: `${pct}%` }} />
                </div>
                {pending.length > 0 && <p className="text-[10px] text-slate-400 mt-1.5">Missing: {pending.map((p) => p.label).join(', ')}</p>}
              </div>

              {/* key facts */}
              <dl className="mt-4 space-y-1.5 text-xs">
                {[
                  ['Location', profile.current_location || profile.city],
                  ['Qualification', (profile as any).highest_qualification],
                  ['Experience', profile.fresher ? 'Fresher' : (profile.total_experience ? `${profile.total_experience} yrs` : null)],
                  ['Notice period', (profile as any).notice_period ? `${(profile as any).notice_period} days` : null],
                ].map(([k, v]) => v ? (
                  <div key={k as string} className="flex justify-between gap-2">
                    <dt className="text-slate-400">{k}</dt>
                    <dd className="font-semibold text-slate-700 dark:text-slate-300 text-right">{v as string}</dd>
                  </div>
                ) : null)}
              </dl>

              <Link href="/profile" className="mt-4 block text-center px-4 py-2 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition">
                Edit profile
              </Link>
            </div>

            {/* Applied JDs */}
            <CandidateMyApplications apps={apps} loading={appsLoading} />
          </div>

          {/* ---------- RIGHT: paginated jobs list ---------- */}
          <div className="lg:col-span-2 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 shadow-sm">
            <div className="flex items-center justify-between gap-3 flex-wrap mb-4">
              <h3 className="text-sm font-bold text-slate-800 dark:text-white">Open positions <span className="text-slate-400 font-normal">({count})</span></h3>
              <form onSubmit={(e) => { e.preventDefault(); setPage(1); setQ(qInput); }} className="flex border border-slate-200 dark:border-slate-700">
                <input value={qInput} onChange={(e) => setQInput(e.target.value)} placeholder="Search…"
                  className="px-3 py-1.5 text-sm bg-white dark:bg-slate-900 focus:outline-none w-40" />
                <button type="submit" className="px-3 bg-[#405189] text-white text-xs font-bold">Go</button>
              </form>
            </div>

            {loading ? (
              <p className="text-slate-400 text-sm py-8 text-center">Loading…</p>
            ) : jobs.length === 0 ? (
              <p className="text-slate-400 text-sm py-8 text-center">No open positions found.</p>
            ) : (
              <div className="space-y-3">
                {jobs.map((j) => {
                  const isApplied = j.is_applied || apps.some((a: any) => a.job_id === j.id);
                  return (
                    <div key={j.id} className="border border-slate-200 dark:border-slate-800 p-4 flex flex-col sm:flex-row sm:items-center gap-3">
                      <div className="flex-1 min-w-0">
                        <Link href={`/careers/jobs/${j.public_id || j.id}`} className="font-bold text-slate-800 dark:text-slate-200 hover:text-[#405189]">{j.title}</Link>
                        <div className="flex flex-wrap gap-x-3 gap-y-0.5 mt-1 text-xs text-slate-500 dark:text-slate-400">
                          <span>{j.client_name || 'Indovision'}</span>
                          {j.location && <span><i className="fa-solid fa-location-dot mr-1" />{j.location}</span>}
                          {j.experience_band && <span><i className="fa-solid fa-briefcase mr-1" />{j.experience_band}</span>}
                        </div>
                      </div>
                      <div className="flex items-center gap-2 shrink-0">
                        <Link href={`/careers/jobs/${j.public_id || j.id}`} className="text-xs font-bold px-3 py-1.5 border border-[#405189]/30 text-[#405189] hover:bg-[#405189]/5 transition">Details</Link>
                        {isApplied ? (
                          <span className="text-xs font-bold px-3 py-1.5 bg-emerald-50 text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800 flex items-center gap-1">
                            <i className="fa-solid fa-circle-check text-[10px]" /> Applied
                          </span>
                        ) : (
                          <button onClick={() => setApplyPreviewJob(j)} disabled={applying === j.id}
                            className="text-xs font-bold px-3 py-1.5 bg-[#405189] text-white hover:bg-[#334267] transition disabled:opacity-50">
                            {applying === j.id ? '…' : 'Apply'}
                          </button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex items-center justify-between mt-4 pt-4 border-t border-slate-100 dark:border-slate-800">
                <button disabled={page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}
                  className="text-xs font-bold px-3 py-1.5 border border-slate-200 dark:border-slate-700 disabled:opacity-40 hover:bg-slate-50 dark:hover:bg-slate-800 transition">
                  ← Prev
                </button>
                <span className="text-xs text-slate-500">Page {page} of {totalPages}</span>
                <button disabled={page >= totalPages} onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                  className="text-xs font-bold px-3 py-1.5 border border-slate-200 dark:border-slate-700 disabled:opacity-40 hover:bg-slate-50 dark:hover:bg-slate-800 transition">
                  Next →
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ---- JD Preview & Apply Confirmation Modal ---- */}
      {applyPreviewJob && (
        <div
          className="fixed inset-0 z-[120] flex items-center justify-center bg-slate-950/70 backdrop-blur-sm p-4"
          onClick={() => applying !== applyPreviewJob.id && setApplyPreviewJob(null)}
        >
          <div onClick={(e) => e.stopPropagation()} className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col rounded-none">
            {/* Modal Header */}
            <div className="flex items-start justify-between gap-4 px-6 py-4 border-b border-slate-100 dark:border-slate-800">
              <div>
                <h2 className="text-base font-black text-slate-800 dark:text-white">{applyPreviewJob.title}</h2>
                <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">
                  {applyPreviewJob.client_name || 'Indovision'}
                  {applyPreviewJob.location && <span className="ml-2"><i className="fa-solid fa-location-dot mr-1" />{applyPreviewJob.location}</span>}
                </p>
              </div>
              <button onClick={() => setApplyPreviewJob(null)} className="text-slate-400 hover:text-slate-700 dark:hover:text-white text-lg shrink-0 transition">
                <i className="fa-solid fa-xmark" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
              {/* Quick facts */}
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                {[
                  { icon: 'fa-location-dot', label: 'Location', val: applyPreviewJob.location },
                  { icon: 'fa-briefcase', label: 'Experience', val: applyPreviewJob.experience_band },
                  { icon: 'fa-indian-rupee-sign', label: 'CTC', val: applyPreviewJob.ctc_band },
                  { icon: 'fa-clock', label: 'Shift', val: applyPreviewJob.shift },
                ].filter((f) => f.val).map((f) => (
                  <div key={f.label} className="bg-slate-50 dark:bg-slate-800/60 border border-slate-100 dark:border-slate-700 px-3 py-2">
                    <p className="text-[10px] font-bold uppercase tracking-wide text-slate-400 mb-0.5">{f.label}</p>
                    <p className="text-xs font-semibold text-slate-700 dark:text-slate-200 flex items-center gap-1.5">
                      <i className={`fa-solid ${f.icon} text-[#405189]`} />{f.val}
                    </p>
                  </div>
                ))}
              </div>

              {/* Must-have skills */}
              {applyPreviewJob.must_have_skills && (
                <div>
                  <p className="text-[11px] font-extrabold uppercase tracking-wide text-slate-500 mb-1.5">Required Skills</p>
                  <div className="flex flex-wrap gap-1.5">
                    {applyPreviewJob.must_have_skills.split(',').filter((s) => s.trim()).map((s, i) => (
                      <span key={i} className="text-[11px] px-2 py-0.5 bg-[#405189]/10 text-[#405189] border border-[#405189]/20">{s.trim()}</span>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Modal Footer — Confirm Apply */}
            <div className="px-6 py-4 border-t border-slate-100 dark:border-slate-800 bg-slate-50 dark:bg-slate-900 flex items-center justify-between gap-4">
              <p className="text-xs text-slate-500 dark:text-slate-400">
                <i className="fa-solid fa-circle-info mr-1 text-[#405189]" />
                Confirm your interest in this role.
              </p>
              <div className="flex items-center gap-2 shrink-0">
                <button
                  onClick={() => setApplyPreviewJob(null)}
                  disabled={applying === applyPreviewJob.id}
                  className="px-4 py-2 text-xs font-bold text-slate-500 hover:text-slate-800 dark:text-slate-400 dark:hover:text-white transition disabled:opacity-50"
                >
                  Cancel
                </button>
                <button
                  onClick={async () => {
                    const job = applyPreviewJob;
                    await onApply(job);
                    setApplyPreviewJob(null);
                  }}
                  disabled={applying === applyPreviewJob.id}
                  className="inline-flex items-center gap-1.5 bg-[#405189] hover:bg-[#334267] text-white text-xs font-bold px-5 py-2 transition disabled:opacity-50 cursor-pointer"
                >
                  {applying === applyPreviewJob.id ? (
                    <><i className="fa-solid fa-spinner fa-spin" /> Applying…</>
                  ) : (
                    <><i className="fa-solid fa-paper-plane" /> Apply</>
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
