'use client';

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import Cookies from 'js-cookie';
import { toast } from 'react-toastify';
import { api } from '@/lib/api';
import CareersHeader from '@/components/careers/CareersHeader';
import CareersFooter from '@/components/careers/CareersFooter';
import { CAREERS_API } from '@/lib/careers';
import { ResumePreviewModal } from '@/components/ResumePreviewModal';
import { ResumeUploadConfirmModal } from '@/components/ResumeUploadConfirmModal';
import SearchableSelect from '@/components/SearchableSelect';

interface Profile {
  first_name: string;
  last_name: string;
  phone_number: string;
  city: string;
  state: string;
  total_experience: string | number | null;
  current_company: string;
  current_role: string;
  expected_ctc: string | number | null;
  notice_period: number | null;
  notice_period_id: string | number | null;
  preferred_location: string;
  current_location: string;
  professional_summary: string;
  fresher: boolean;
  resume: string | null;
  skills: string;
}

const csvToArr = (s: string) => (s ? s.split(',').map((x) => x.trim()).filter(Boolean) : []);
const arrToCsv = (a: string[]) => a.filter(Boolean).join(', ');

const EMPTY: Profile = {
  first_name: '', last_name: '', phone_number: '', city: '', state: '',
  total_experience: '', current_company: '', current_role: '', expected_ctc: '',
  notice_period: null, notice_period_id: null, preferred_location: '', current_location: '', professional_summary: '', fresher: true, resume: null,
  skills: '',
};

export default function CandidateProfilePage() {
  const router = useRouter();
  const [form, setForm] = useState<Profile>(EMPTY);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [resumeView, setResumeView] = useState<{ url: string | null; name: string } | null>(null);
  const [pendingResume, setPendingResume] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [ctcOpts, setCtcOpts] = useState<{ value: string; label: string }[]>([]);
  const [noticeOpts, setNoticeOpts] = useState<{ value: string; label: string }[]>([]);
  const [desigOpts, setDesigOpts] = useState<{ value: string; label: string }[]>([]);
  const [skillOpts, setSkillOpts] = useState<{ value: string; label: string }[]>([]);

  const listOf = (res: any): any[] => {
    const d = res?.data ?? res;
    return Array.isArray(d) ? d : (d?.results ?? []);
  };

  useEffect(() => {
    if (!Cookies.get('access_token')) { router.push('/login'); return; }
    api.get('/candidates/me/')
      .then((res: any) => {
        const p = res?.data ?? {};
        const skillNames = Array.isArray(p.skills) ? p.skills.map((s: any) => s?.name ?? s).filter(Boolean) : [];
        setForm({ ...EMPTY, ...p, resume: (p as any).resume_url ?? p.resume ?? null, notice_period_id: p.notice_period_id != null ? String(p.notice_period_id) : '', skills: skillNames.join(', ') });
      })
      .catch(() => toast.error('Could not load your profile.'))
      .finally(() => setLoading(false));

    (async () => {
      try {
        const ctcs = listOf(await api.get('/master-data/annual-ctc'));
        if (ctcs.length) setCtcOpts(ctcs.map((c: any) => ({ value: String(Math.round(Number(c.value))), label: c.label })));
      } catch {}
      try {
        const nps = listOf(await api.get('/public/notice-periods/'));
        if (nps.length) setNoticeOpts(nps.map((n: any) => ({ value: String(n.id), label: n.label })));
      } catch {}
      try {
        const dgs = listOf(await api.get('/public/designations/'));
        if (dgs.length) setDesigOpts(dgs.map((d: any) => ({ value: d.name, label: d.name })));
      } catch {}
      try {
        const sks = listOf(await api.get('/public/skills/'));
        if (sks.length) setSkillOpts(sks.map((s: any) => ({ value: s.name, label: s.name })));
      } catch {}
    })();
  }, [router]);

  const set = (k: keyof Profile, v: any) => setForm((f) => ({ ...f, [k]: v }));

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const { resume, ...rest } = form; // resume handled separately
      const payload = { ...rest, skills: csvToArr(form.skills) };
      await api.patch('/candidates/me/', payload);
      toast.success('Profile updated.');
    } catch (err: any) {
      toast.error(err?.data?.message || 'Could not save profile.');
    } finally { setSaving(false); }
  };

  const uploadResume = async (file: File) => {
    setUploading(true);
    try {
      // Upload + two-stage parse (LLM primary, package-parser fallback). The
      // endpoint saves the résumé against the profile immediately.
      const fd = new FormData();
      fd.append('file', file);
      const res: any = await api.upload('/candidates/upload-resume/', fd);
      const parsed = res?.parsed_data ?? {};
      // Only auto-fill when the parse found something identifying — otherwise
      // the file is probably not a readable résumé.
      const identifying = !!(parsed.first_name || parsed.email || parsed.phone_number);
      setForm((f) => {
        const next: Profile = { ...f, resume: res?.resume_url ?? f.resume };
        if (identifying) {
          // Refresh parsed fields from the new résumé; values it no longer
          // contains are cleared rather than kept stale.
          next.first_name = parsed.first_name || '';
          next.last_name = parsed.last_name || '';
          next.phone_number = parsed.phone_number || '';
          next.city = parsed.city || '';
          next.state = parsed.state || '';
          next.current_location = parsed.current_location || '';
          next.current_company = parsed.current_company || '';
          next.current_role = parsed.current_role || '';
          next.professional_summary = parsed.professional_summary || '';
          next.total_experience = parsed.total_experience ?? '';
          next.fresher = typeof parsed.fresher === 'boolean' ? parsed.fresher : f.fresher;
          // Rarely stated in résumés — fill only when found, never clear.
          if (parsed.notice_period != null) next.notice_period = parsed.notice_period;
        }
        return next;
      });
      if (identifying) {
        toast.success('Résumé updated & parsed — review the filled details and save.');
      } else {
        toast.warn(res?.message || 'Résumé updated, but details could not be read. Please fill the form manually.');
      }
    } catch (err: any) {
      toast.error(err?.data?.detail || err?.data?.message || 'Could not upload résumé.');
    } finally { setUploading(false); }
  };

  const F = ({ label, k, type = 'text', required = false }: { label: string; k: keyof Profile; type?: string; required?: boolean }) => (
    <div>
      <label className="block text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">
        {label} {required && <span className="text-red-500 font-bold">*</span>}
      </label>
      <input
        type={type}
        value={(form[k] ?? '') as string}
        onChange={(e) => set(k, e.target.value)}
        className="w-full px-3 py-2.5 text-sm border border-slate-300 bg-white focus:outline-none focus:border-[#405189]"
      />
    </div>
  );

  const Sel = ({ label, k, options, required = false, placeholder = 'Select…', isNumeric = false }: { label: string; k: keyof Profile; options: { value: string; label: string }[]; required?: boolean; placeholder?: string; isNumeric?: boolean }) => {
    let curVal = '';
    if (form[k] !== null && form[k] !== undefined) {
      curVal = isNumeric ? String(Math.round(Number(form[k]))) : String(form[k]);
    }
    return (
      <div>
        <label className="block text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">
          {label} {required && <span className="text-red-500 font-bold">*</span>}
        </label>
        <select
          value={curVal}
          onChange={(e) => set(k, e.target.value)}
          className="w-full px-3 py-2.5 text-sm border border-slate-300 bg-white focus:outline-none focus:border-[#405189] cursor-pointer"
        >
          <option value="">{placeholder}</option>
          {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      </div>
    );
  };

  const resumeUrl = form.resume
    ? (form.resume.startsWith('http') ? form.resume : `${CAREERS_API.replace('/api/v1', '')}${form.resume}`)
    : null;

  const resumeName = typeof form.resume === 'string' && form.resume
    ? decodeURIComponent(form.resume.split('/').pop() || '')
    : '';

  return (
    <div className="min-h-screen bg-slate-50">
      <CareersHeader />
      <div className="max-w-3xl mx-auto px-4 sm:px-6 py-8">
        <h1 className="text-2xl font-black text-slate-800">My Profile</h1>
        <p className="text-sm text-slate-500 mt-1">Keep your details and résumé up to date — recruiters see this.</p>

        {loading ? (
          <p className="text-slate-400 text-sm mt-8">Loading…</p>
        ) : (
          <>
            {/* Résumé card */}
            <div className="bg-white border border-slate-200 p-6 shadow-sm mt-6">
              <h2 className="font-bold text-slate-800 mb-3">Résumé</h2>
              <div className="flex flex-wrap items-center gap-3">
                {resumeUrl ? (
                  <button
                    type="button"
                    onClick={() => setResumeView({ url: form.resume, name: resumeName || 'Résumé' })}
                    className="text-sm font-bold text-[#405189] underline hover:text-[#334267] cursor-pointer bg-transparent border-0 p-0"
                  >
                    <i className="fa-solid fa-eye mr-1" /> Preview résumé
                  </button>
                ) : (
                  <span className="text-sm text-slate-400">No résumé uploaded yet.</span>
                )}
                <label className="text-sm font-bold px-4 py-2 bg-[#405189] text-white hover:bg-[#334267] transition cursor-pointer">
                  {uploading ? 'Uploading & parsing…' : 'Upload / Replace'}
                  <input
                    ref={fileInputRef}
                    type="file" accept=".pdf,.doc,.docx" className="hidden" disabled={uploading}
                    onChange={(e) => {
                      const f = e.target.files?.[0];
                      if (f) setPendingResume(f); // preview + confirm first — upload happens on confirm
                      e.target.value = ''; // allow re-selecting the same file after cancel
                    }}
                  />
                </label>
              </div>
            </div>

            {/* Details form */}
            <form onSubmit={save} className="bg-white border border-slate-200 p-6 shadow-sm mt-4">
              <h2 className="font-bold text-slate-800 mb-4">Details</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <F label="First name" k="first_name" required />
                <F label="Last name" k="last_name" required />
                <F label="Phone" k="phone_number" required />
                <F label="City" k="city" required />
                <F label="State" k="state" required />
                <F label="Preferred location" k="preferred_location" />
              </div>

              <label className="flex items-center gap-2 mt-5 text-sm font-semibold text-slate-700 cursor-pointer">
                <input type="checkbox" checked={form.fresher} onChange={(e) => set('fresher', e.target.checked)} className="w-4 h-4 accent-[#405189]" />
                I am a fresher (no work experience)
              </label>

              {!form.fresher && (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4">
                  <F label="Total experience (years)" k="total_experience" type="number" required />
                  <F label="Current location" k="current_location" />
                  {Sel({ label: 'Notice period', k: 'notice_period_id', options: noticeOpts, required: true, placeholder: 'Select notice period', isNumeric: true })}
                  <F label="Current company" k="current_company" required />
                  {Sel({ label: 'Designation', k: 'current_role', options: desigOpts, required: true, placeholder: 'Select designation' })}
                  {Sel({ label: 'Expected CTC', k: 'expected_ctc', options: ctcOpts, required: true, placeholder: 'Select expected CTC', isNumeric: true })}
                </div>
              )}
              <div className="mt-4">
                <label className="block text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">Key skills</label>
                <SearchableSelect isMulti isCreatable
                  options={skillOpts}
                  value={csvToArr(form.skills)}
                  onChange={(vals: any) => set('skills', arrToCsv((vals || []).map((v: any) => (typeof v === 'object' ? v.value : v))))}
                  placeholder="Select or type skills…"
                  controlBgClass="bg-white" />
              </div>
              <div className="mt-4">
                <label className="block text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">Professional summary</label>
                <textarea
                  rows={4}
                  value={form.professional_summary ?? ''}
                  onChange={(e) => set('professional_summary', e.target.value)}
                  className="w-full px-3 py-2.5 text-sm border border-slate-300 bg-white focus:outline-none focus:border-[#405189]"
                />
              </div>
              <button type="submit" disabled={saving} className="mt-5 px-6 py-2.5 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition disabled:opacity-50">
                {saving ? 'Saving…' : 'Save changes'}
              </button>
            </form>
          </>
        )}

        {resumeView && (
          <ResumePreviewModal
            url={resumeView.url}
            name={resumeView.name}
            onClose={() => setResumeView(null)}
          />
        )}

        {pendingResume && (
          <ResumeUploadConfirmModal
            file={pendingResume}
            busy={uploading}
            onConfirm={async () => {
              await uploadResume(pendingResume);
              setPendingResume(null);
            }}
            onCancel={() => setPendingResume(null)}
            onChooseAnother={() => {
              setPendingResume(null);
              setTimeout(() => fileInputRef.current?.click(), 50);
            }}
          />
        )}
      </div>
      <CareersFooter />
    </div>
  );
}
