"use client"

import { useState, useEffect } from "react"
import { Briefcase, ChevronDown, Loader2 } from "lucide-react"

interface Job {
  job_title: string
  keywords: string[]
  industry: string
  description: string
}

interface JobSelectorProps {
  onSelect: (job: Job | null) => void
}

export function JobSelector({ onSelect }: JobSelectorProps) {
  const [jobs, setJobs] = useState<Job[]>([])
  const [loading, setLoading] = useState(true)
  const [open, setOpen] = useState(false)
  const [selected, setSelected] = useState<Job | null>(null)

  useEffect(() => {
    fetch("/api/ai/jobs")
      .then((r) => r.json())
      .then((data) => setJobs(data.jobs || []))
      .catch(() => setJobs([]))
      .finally(() => setLoading(false))
  }, [])

  const handleSelect = (job: Job) => {
    setSelected(job)
    setOpen(false)
    onSelect(job)
  }

  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className="w-full flex items-center gap-2 bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2 text-sm text-[#e8e8ef] hover:border-[#1BB0CE]/50 transition-colors"
      >
        <Briefcase className="h-4 w-4 text-[#1BB0CE] flex-none" />
        <span className="flex-1 text-left truncate">
          {selected ? selected.job_title : loading ? "Loading jobs..." : "Select a job category"}
        </span>
        {loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <ChevronDown className="h-3.5 w-3.5 text-[#6a6a75]" />}
      </button>

      {open && (
        <>
          <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
          <div className="absolute top-full left-0 right-0 mt-1 z-20 bg-[#15151e] border border-[#2a2a35] rounded-lg shadow-xl max-h-60 overflow-y-auto">
            {jobs.map((job, i) => (
              <button
                key={i}
                type="button"
                onClick={() => handleSelect(job)}
                className="w-full text-left px-3 py-2.5 text-sm text-[#c8c8d0] hover:bg-[#1a1a24] hover:text-[#e8e8ef] transition-colors border-b border-[#1a1a24] last:border-0"
              >
                <div className="font-medium">{job.job_title}</div>
                <div className="text-xs text-[#6a6a75] mt-0.5">{job.industry} — {job.description}</div>
              </button>
            ))}
            {jobs.length === 0 && !loading && (
              <div className="px-3 py-4 text-xs text-[#6a6a75] text-center">No job categories loaded</div>
            )}
          </div>
        </>
      )}
    </div>
  )
}
