'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import { useAuth } from '@/components/auth-context';
import { toast } from 'react-toastify';
import SearchableSelect from '@/components/SearchableSelect';
import { SKILL_OPTIONS } from '@/data/skills';
import CandidateProfileEditor from '@/components/careers/CandidateProfileEditor';

interface ProfileForm {
  full_name: string;
  phone: string;
  location: string;
  skills: string;
  experience_years: number;
  bio: string;
}

const EMPTY: ProfileForm = {
  full_name: '', phone: '', location: '', skills: '', experience_years: 0, bio: '',
};

const ROLE_LABEL: Record<string, string> = {
  ADMIN: 'Super Admin', RECRUITER: 'Recruiter', INTERVIEWER: 'Interviewer', CANDIDATE: 'Candidate',
};

export default function ProfilePage() {
  const router = useRouter();
  const { user, refreshUser } = useAuth();
  const [form, setForm] = useState<ProfileForm>(EMPTY);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [locationOptions, setLocationOptions] = useState<{ value: string; label: string }[]>([]);
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    fetch('/data/india-locations.json')
      .then((res) => res.json())
      .then((data) => {
        if (Array.isArray(data)) {
          // Extract unique states/UTs
          const states = Array.from(new Set(data.map((item: any) => item.state))).filter(Boolean).sort();
          const stateOpts = states.map((st) => ({
            value: st,
            label: st,
          }));

          // Sort cities alphabetically
          const sortedCities = [...data].sort((a: any, b: any) => (a.name || '').localeCompare(b.name || ''));
          const cityOpts = sortedCities.map((item: any) => ({
            value: `${item.name}, ${item.state}`,
            label: `${item.name}, ${item.state}`,
          }));

          setLocationOptions([...stateOpts, ...cityOpts]);
        }
      })
      .catch((err) => {
        console.error('Error fetching locations:', err);
      });
  }, []);

  const filteredLocationOptions = (() => {
    if (!searchQuery) {
      return locationOptions.slice(0, 100);
    }
    const q = searchQuery.toLowerCase();
    return locationOptions
      .filter((opt) => opt.label.toLowerCase().includes(q))
      .slice(0, 100);
  })();

  useEffect(() => {
    if (!user) return;
    setForm({
      full_name: user.full_name ?? '',
      phone: user.phone ?? '',
      location: user.location ?? '',
      skills: user.skills ?? '',
      experience_years: user.experience_years ?? 0,
      bio: user.bio ?? '',
    });
    setLoading(false);
  }, [user]);

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      await api.put('/users/profile/', form);
      refreshUser();
      toast.success('Profile updated');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Could not update profile');
    } finally {
      setSaving(false);
    }
  };

  const initial = (form.full_name || user?.email || 'U').charAt(0).toUpperCase();
  const inputCls = 'w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none px-3 py-2 text-sm focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none';

  return (
        <main className={`flex-1 ${user?.role === 'CANDIDATE' ? 'p-2 sm:p-4 md:p-6' : 'p-4 sm:p-6'} overflow-y-auto`}>
          {loading ? (
            <p className="text-vz-muted">Loading…</p>
          ) : (
            <div className={`${user?.role === 'CANDIDATE' ? 'max-w-[1400px] w-[94%] sm:w-[90%]' : 'max-w-3xl'} mx-auto space-y-6`}>
              {/* Identity header */}
              <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none p-6 shadow-sm flex items-center gap-4">
                <span className="w-16 h-16 rounded-full bg-[#405189] text-white flex items-center justify-center text-2xl font-semibold shrink-0">
                  {initial}
                </span>
                <div className="min-w-0">
                  <h2 className="text-lg font-semibold text-[#495057] dark:text-white truncate">
                    {form.full_name || user?.email}
                  </h2>
                  <p className="text-sm text-vz-muted truncate">{user?.email}</p>
                  <div className="flex items-center gap-2 mt-1.5">
                    <span className="text-[10px] tracking-wider font-semibold uppercase text-[#405189] bg-[#405189]/10 px-2 py-0.5 rounded-none">
                      {user ? (ROLE_LABEL[user.role] || user.role) : ''}
                    </span>
                    {user?.mfa_enabled && (
                      <span className="text-[10px] font-semibold text-[#0ab39c] bg-[#0ab39c]/10 px-2 py-0.5 rounded-none">
                        MFA Active
                      </span>
                    )}
                  </div>
                </div>
              </div>

              {/* Candidates edit their full profile; other roles use the basic staff form. */}
              {user?.role === 'CANDIDATE' ? (
                <CandidateProfileEditor />
              ) : (
              <form onSubmit={save} className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none p-6 shadow-sm space-y-5">
                <h3 className="text-base font-semibold text-[#495057] dark:text-white">Edit details</h3>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <label className="block">
                    <span className="text-xs font-medium text-slate-500">Full name</span>
                    <input value={form.full_name} onChange={(e) => setForm({ ...form, full_name: e.target.value })} className={`mt-1 ${inputCls}`} />
                  </label>
                  <label className="block">
                    <span className="text-xs font-medium text-slate-500">Phone</span>
                    <input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} className={`mt-1 ${inputCls}`} />
                  </label>
                  <label className="block">
                    <span className="text-xs font-medium text-slate-500">Location</span>
                    <SearchableSelect
                      isMulti={false}
                      options={filteredLocationOptions}
                      value={form.location}
                      onChange={(val) => setForm({ ...form, location: val || '' })}
                      onSearchChange={setSearchQuery}
                      placeholder="Select location..."
                      className="mt-1"
                      controlBgClass="bg-white dark:bg-slate-800"
                    />
                  </label>
                  <label className="block">
                    <span className="text-xs font-medium text-slate-500">Experience (years)</span>
                    <input type="number" min={0} value={form.experience_years}
                      onChange={(e) => setForm({ ...form, experience_years: Math.max(0, Number(e.target.value) || 0) })}
                      className={`mt-1 ${inputCls}`} />
                  </label>
                </div>

                <label className="block">
                  <span className="text-xs font-medium text-slate-500">Skills</span>
                  <SearchableSelect
                    isMulti={true}
                    isCreatable={true}
                    wrap={true}
                    options={SKILL_OPTIONS}
                    value={form.skills ? form.skills.split(',').map((s) => s.trim()).filter(Boolean) : []}
                    onChange={(val) => setForm({ ...form, skills: (val || []).join(', ') })}
                    placeholder="Select or type skills..."
                    className="mt-1"
                    controlBgClass="bg-white dark:bg-slate-800"
                  />
                </label>

                <label className="block">
                  <span className="text-xs font-medium text-slate-500">Bio</span>
                  <textarea rows={4} value={form.bio}
                    onChange={(e) => setForm({ ...form, bio: e.target.value })} className={`mt-1 ${inputCls}`} />
                </label>

                <div className="flex items-center justify-end gap-3 pt-1">
                  <button type="button" onClick={() => router.push('/dashboard')}
                    className="px-4 py-2 rounded-none text-sm border border-vz-border dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 transition">
                    Cancel
                  </button>
                  <button type="submit" disabled={saving}
                    className="px-5 py-2 rounded-none text-sm font-medium bg-[#405189] hover:bg-[#364574] text-white transition disabled:opacity-50">
                    {saving ? 'Saving…' : 'Save changes'}
                  </button>
                </div>
              </form>
              )}
            </div>
          )}
        </main>
  );
}
