'use client'

import { useEffect, useMemo, useRef, useState } from 'react'
import {
  AlertCircle,
  ArrowRight,
  Briefcase,
  ChevronLeft,
  ChevronRight,
  Clock3,
  ExternalLink,
  Loader2,
  MapPin,
  Search,
  Wifi,
  X,
} from 'lucide-react'
import { ApplyJobModal } from './ApplyJobModal'
import './AvailableJobs.css'

interface Job {
  id: string
  title: string
  location: string
  schedule: string
  category: string
  postedDate: string
  company: string
  pageUrl: string
  applyUrl: string
  jobType: string
  employmentType: string
  hourlyPay: string
  monthlyPay: string
  remote: boolean
}

interface JobDetail extends Job {
  description: string
  basicQualifications: string
  preferredQualifications: string
}

interface Applicant {
  id: string
  name: string
  email: string
  cvName: string
  hasCv: boolean
}

interface AvailableJobsProps {
  applicants?: Applicant[]
  onApplyWithApplicant?: (jobTitle: string, location: string, applyUrl: string, applicantId: string) => void
}

const PAGE_SIZE = 8
const stripScripts = (html: string) => html.replace(/<script[\s\S]*?<\/script>/gi, '')

export function AvailableJobs({ applicants = [], onApplyWithApplicant }: AvailableJobsProps) {
  const [jobs, setJobs] = useState<Job[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [query, setQuery] = useState('')
  const [page, setPage] = useState(1)

  const [workMode, setWorkMode] = useState<'all' | 'onsite' | 'remote'>('all')
  const [jobTypeFilter, setJobTypeFilter] = useState('all')
  const [payView, setPayView] = useState<'hourly' | 'monthly'>('hourly')
  const [employmentFilter, setEmploymentFilter] = useState('all')
  const [minPay, setMinPay] = useState('')
  const [scheduleFilter, setScheduleFilter] = useState('all')

  const [detail, setDetail] = useState<JobDetail | null>(null)
  const [detailLoading, setDetailLoading] = useState(false)
  const [detailError, setDetailError] = useState('')
  const [applyModal, setApplyModal] = useState<{ jobTitle: string; location: string; applyUrl: string } | null>(null)
  const [filterOpen, setFilterOpen] = useState(false)
  const filterRef = useRef<HTMLDivElement>(null)

  // Close filter dropdown on outside click
  useEffect(() => {
    function handler(e: MouseEvent) {
      if (filterRef.current && !filterRef.current.contains(e.target as Node)) setFilterOpen(false)
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [])

  useEffect(() => {
    let active = true
    setLoading(true)
    setError('')
    fetch('/api/jobs')
      .then((res) => (res.ok ? res.json() : Promise.reject(new Error('Failed to load jobs'))))
      .then((data) => {
        if (!active) return
        setJobs(data.jobs || [])
        setTotal(data.total || 0)
        setPage(1)
        if (data.jobs?.[0]) openDetail(data.jobs[0].id)
      })
      .catch((err: any) => {
        if (active) setError(err.message || 'Failed to load jobs')
      })
      .finally(() => {
        if (active) setLoading(false)
      })
    return () => {
      active = false
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const jobTypeOptions = useMemo(() => {
    const set = new Set<string>()
    for (const job of jobs) {
      for (const type of (job.jobType || '').split(';')) {
        const clean = type.trim()
        if (clean) set.add(clean)
      }
    }
    return Array.from(set).sort()
  }, [jobs])

  const employmentOptions = useMemo(() => {
    const set = new Set<string>()
    for (const job of jobs) {
      const e = (job.employmentType || '').trim()
      if (e) set.add(e)
    }
    return Array.from(set).sort()
  }, [jobs])

  const scheduleOptions = useMemo(() => {
    const set = new Set<string>()
    for (const job of jobs) {
      const s = (job.schedule || '').trim()
      if (s) set.add(s)
    }
    return Array.from(set).sort()
  }, [jobs])

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase()
    return jobs.filter((job) => {
      if (workMode === 'remote' && !job.remote) return false
      if (workMode === 'onsite' && job.remote) return false
      if (jobTypeFilter !== 'all' && !(job.jobType || '').split(';').some((t) => t.trim() === jobTypeFilter)) {
        return false
      }
      // Employment type filter (Seasonal / Regular)
      if (employmentFilter !== 'all' && (job.employmentType || '').trim() !== employmentFilter) return false
      // Schedule filter (Full-time / Part-time etc)
      if (scheduleFilter !== 'all' && (job.schedule || '').trim() !== scheduleFilter) return false
      // Minimum hourly pay filter
      if (minPay) {
        const threshold = parseFloat(minPay)
        if (!isNaN(threshold)) {
          const payStr = job.hourlyPay || ''
          const match = payStr.match(/[\d.]+/)
          const jobPay = match ? parseFloat(match[0]) : 0
          if (jobPay < threshold) return false
        }
      }
      if (!q) return true
      return `${job.title} ${job.location} ${job.schedule} ${job.employmentType} ${job.company} ${job.category}`
        .toLowerCase()
        .includes(q)
    })
  }, [jobs, query, workMode, jobTypeFilter, employmentFilter, scheduleFilter, minPay])

  const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
  const currentPage = Math.min(page, pageCount)
  const pageJobs = filtered.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE)

  const payLabel = (job: Job) => {
    const value = payView === 'monthly' ? job.monthlyPay : job.hourlyPay
    if (!value) return ''
    return payView === 'monthly' ? `From ${value}/month` : `From ${value}/hour`
  }

  const openDetail = async (id: string) => {
    setDetailLoading(true)
    setDetailError('')
    setDetail(null)
    try {
      const res = await fetch(`/api/jobs/${id}`)
      if (!res.ok) throw new Error('Failed to load job detail')
      const data = await res.json()
      if (data.error) throw new Error(data.error)
      setDetail(data)
    } catch (err: any) {
      // Fallback — show basic info from list if detail fetch fails
      const fallback = jobs.find(j => j.id === id)
      if (fallback) {
        setDetail({ ...fallback, description: '', basicQualifications: '', preferredQualifications: '' } as JobDetail)
        setDetailError('')
      } else {
        setDetailError('Could not load job description. Click the job title to view on Amazon.')
      }
    } finally {
      setDetailLoading(false)
    }
  }

  const goPage = (p: number) => {
    if (p < 1 || p > pageCount) return
    setPage(p)
  }

  const pagination = (
    <div className="jobs-pagination">
      <button className="page-btn" onClick={() => goPage(currentPage - 1)} disabled={currentPage <= 1}>
        <ChevronLeft size={15} />
      </button>
      {Array.from({ length: pageCount }, (_, i) => i + 1).map((p) => (
        <button key={p} className={`page-btn ${p === currentPage ? 'active' : ''}`} onClick={() => goPage(p)}>
          {p}
        </button>
      ))}
      <button
        className="page-btn"
        onClick={() => goPage(currentPage + 1)}
        disabled={currentPage >= pageCount}
      >
        <ChevronRight size={15} />
      </button>
    </div>
  )

  return (
    <section className="jobs-layout">
      <div className="jobs-sidebar panel">
        <div className="panel-heading">
          <div>
            <h2>Available jobs</h2>
            <p>Hourly Amazon jobs • jobsatamazon.co.uk</p>
          </div>
          {!loading && !error && <span className="job-hits">{total} jobs</span>}
        </div>

        <div className="jobs-toolbar">
          {/* Search */}
          <div className="table-search">
            <Search size={15} />
            <input
              value={query}
              onChange={(e) => { setQuery(e.target.value); setPage(1) }}
              placeholder="Search jobs..."
            />
            {query && <button className="jobs-clear" onClick={() => setQuery('')}><X size={13} /></button>}
          </div>

          {/* Filter dropdown */}
          <div className="jf-dropdown-wrap" ref={filterRef}>
            <button
              className={`jf-filter-btn ${filterOpen || (employmentFilter !== 'all' || scheduleFilter !== 'all' || minPay || jobTypeFilter !== 'all' || workMode !== 'all') ? 'active' : ''}`}
              onClick={() => setFilterOpen(v => !v)}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M3 6h18M6 12h12M9 18h6"/></svg>
              Filters
              {(employmentFilter !== 'all' || scheduleFilter !== 'all' || minPay || jobTypeFilter !== 'all' || workMode !== 'all') && (
                <span className="jf-badge">
                  {[workMode !== 'all', jobTypeFilter !== 'all', employmentFilter !== 'all', scheduleFilter !== 'all', !!minPay].filter(Boolean).length}
                </span>
              )}
            </button>

            {filterOpen && (
              <div className="jf-dropdown">
                {/* Work format */}
                <div className="jf-section">
                  <p className="jf-label">Work format</p>
                  <div className="jf-chips">
                    {(['all', 'onsite', 'remote'] as const).map(m => (
                      <button key={m} className={`jf-chip ${workMode === m ? 'active' : ''}`}
                        onClick={() => { setWorkMode(m); setPage(1) }}>
                        {m === 'all' ? 'All' : m === 'onsite' ? 'On-site' : 'Remote'}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Employment type */}
                {employmentOptions.length > 0 && (
                  <div className="jf-section">
                    <p className="jf-label">Employment type</p>
                    <div className="jf-chips">
                      <button className={`jf-chip ${employmentFilter === 'all' ? 'active' : ''}`}
                        onClick={() => { setEmploymentFilter('all'); setPage(1) }}>All</button>
                      {employmentOptions.map(e => (
                        <button key={e} className={`jf-chip ${employmentFilter === e ? 'active' : ''}`}
                          onClick={() => { setEmploymentFilter(e === employmentFilter ? 'all' : e); setPage(1) }}>{e}</button>
                      ))}
                    </div>
                  </div>
                )}

                {/* Shift type */}
                {scheduleOptions.length > 0 && (
                  <div className="jf-section">
                    <p className="jf-label">Shift type</p>
                    <div className="jf-chips">
                      <button className={`jf-chip ${scheduleFilter === 'all' ? 'active' : ''}`}
                        onClick={() => { setScheduleFilter('all'); setPage(1) }}>All</button>
                      {scheduleOptions.map(s => (
                        <button key={s} className={`jf-chip ${scheduleFilter === s ? 'active' : ''}`}
                          onClick={() => { setScheduleFilter(s === scheduleFilter ? 'all' : s); setPage(1) }}>{s}</button>
                      ))}
                    </div>
                  </div>
                )}

                {/* Min pay */}
                <div className="jf-section">
                  <p className="jf-label">Min hourly pay (£)</p>
                  <div className="jf-pay-row">
                    <span>£</span>
                    <input type="number" min="0" step="0.5" placeholder="e.g. 14.00"
                      value={minPay} onChange={e => { setMinPay(e.target.value); setPage(1) }} />
                    {minPay && <button className="jobs-clear" onClick={() => { setMinPay(''); setPage(1) }}><X size={12}/></button>}
                  </div>
                </div>

                {/* Pay view */}
                <div className="jf-section">
                  <p className="jf-label">Pay view</p>
                  <div className="jf-chips">
                    {(['hourly', 'monthly'] as const).map(m => (
                      <button key={m} className={`jf-chip ${payView === m ? 'active' : ''}`}
                        onClick={() => setPayView(m)}>
                        {m === 'hourly' ? 'Hourly' : 'Monthly'}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Clear all */}
                {(employmentFilter !== 'all' || scheduleFilter !== 'all' || minPay || jobTypeFilter !== 'all' || workMode !== 'all') && (
                  <button className="jf-clear-all" onClick={() => {
                    setEmploymentFilter('all'); setScheduleFilter('all')
                    setMinPay(''); setJobTypeFilter('all'); setWorkMode('all'); setPage(1)
                  }}>
                    <X size={11} /> Clear all filters
                  </button>
                )}
              </div>
            )}
          </div>
        </div>

        {loading ? (
          <div className="jobs-state">
            <Loader2 className="spin" size={22} />
            <p>Loading live Amazon jobs...</p>
          </div>
        ) : error ? (
          <div className="jobs-state jobs-error">
            <AlertCircle size={22} />
            <p>{error}</p>
          </div>
        ) : filtered.length === 0 ? (
          <div className="jobs-state">
            <p>No jobs match your filter.</p>
          </div>
        ) : (
          <>
            <div className="jobs-list">
              {pageJobs.map((job) => (
                <button
                  key={job.id}
                  className={`job-item ${detail?.id === job.id ? 'selected' : ''}`}
                  onClick={() => openDetail(job.id)}
                >
                  <div className="job-item-top">
                    <b>{job.title}</b>
                    <ArrowRight size={15} />
                  </div>
                  <div className="job-item-meta">
                    <span>
                      <MapPin size={13} /> {job.location}
                      {job.remote && (
                        <span className="remote-chip">
                          <Wifi size={11} /> Remote
                        </span>
                      )}
                    </span>
                    <span className="job-item-schedule">{job.schedule}</span>
                  </div>
                  <div className="job-item-pay">
                    <span className="pay-value">{payLabel(job) || job.hourlyPay}</span>
                    <span className="emp-type">{job.employmentType}</span>
                  </div>
                </button>
              ))}
            </div>
            <div className="jobs-footer">
              <span className="jobs-range">
                Showing {Math.min(filtered.length, (currentPage - 1) * PAGE_SIZE + 1)}–
                {Math.min(filtered.length, currentPage * PAGE_SIZE)} of {filtered.length}
              </span>
              {pagination}
            </div>
          </>
        )}
      </div>

      <div className="jobs-detail panel">
        {detailLoading ? (
          <div className="jobs-state">
            <Loader2 className="spin" size={22} />
            <p>Loading full description...</p>
          </div>
        ) : detailError ? (
          <div className="jobs-state jobs-error">
            <AlertCircle size={22} />
            <p>{detailError}</p>
          </div>
        ) : detail ? (
          <>
            <div className="job-detail-head">
              <div>
                <p className="job-detail-kicker">{detail.employmentType}</p>
                <h2>{detail.title}</h2>
              </div>
              {detail.remote && (
                <span className="remote-chip detail-remote">
                  <Wifi size={12} /> Remote
                </span>
              )}
            </div>
            <div className="job-detail-meta">
              <span>
                <MapPin size={14} /> {detail.location}
              </span>
              <span>
                <Briefcase size={14} /> {detail.schedule}
              </span>
              {(payLabel(detail) || detail.hourlyPay) && (
                <span>
                  <Clock3 size={14} /> {payLabel(detail) || detail.hourlyPay}
                </span>
              )}
              {detail.postedDate && (
                <span>
                  <Clock3 size={14} /> Posted {detail.postedDate}
                </span>
              )}
            </div>

            <div className="job-section">
              <div className="section-label">Job description</div>
              <div
                className="job-body"
                dangerouslySetInnerHTML={{ __html: stripScripts(detail.description || '') }}
              />
            </div>

            {detail.basicQualifications && (
              <div className="job-section">
                <div className="section-label">Basic qualifications</div>
                <div
                  className="job-body"
                  dangerouslySetInnerHTML={{ __html: stripScripts(detail.basicQualifications) }}
                />
              </div>
            )}

            {detail.preferredQualifications && (
              <div className="job-section">
                <div className="section-label">Preferred qualifications</div>
                <div
                  className="job-body"
                  dangerouslySetInnerHTML={{ __html: stripScripts(detail.preferredQualifications) }}
                />
              </div>
            )}

            {detail.applyUrl && (
              <div className="job-detail-actions">
                <button
                  className="btn primary job-apply"
                  onClick={() => setApplyModal({ jobTitle: detail.title, location: detail.location, applyUrl: detail.applyUrl })}
                >
                  Apply with CV <ExternalLink size={15} />
                </button>
                <a className="btn" href={detail.pageUrl} target="_blank" rel="noreferrer">
                  View original
                </a>
              </div>
            )}
          </>
        ) : (
          <div className="jobs-state">
            <p>Select a job from the list to see its full description.</p>
          </div>
        )}
      </div>

      {applyModal && (
        <ApplyJobModal
          jobTitle={applyModal.jobTitle}
          location={applyModal.location}
          applyUrl={applyModal.applyUrl}
          applicants={applicants}
          onApply={(applicantId) => {
            if (onApplyWithApplicant) {
              onApplyWithApplicant(applyModal.jobTitle, applyModal.location, applyModal.applyUrl, applicantId)
            }
            setApplyModal(null)
          }}
          onClose={() => setApplyModal(null)}
        />
      )}
    </section>
  )
}