// src/app/(public)/jobs/[id]/page.tsx
'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import { Badge, statusBadgeVariant, jobTypeBadgeVariant } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { Spinner } from '@/components/ui/Spinner'

interface Job {
  id: string; title: string; companyName: string; location: string; jobType: string
  salaryRange?: string; description: string; requirements?: string; status: string
  createdAt: string; updatedAt: string; employerId: string
  employer?: { name: string; surname: string; email: string }
  isExternal?: boolean
  applyUrl?: string
  source?: string
  category?: string
}

function formatJobType(t: string) {
  return t.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
}

export default function JobDetailPage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  const { data: session } = useSession()
  const [job, setJob] = useState<Job | null>(null)
  const [loading, setLoading] = useState(true)
  const [notFound, setNotFound] = useState(false)

  useEffect(() => {
    fetch(`/api/jobs/${params.id}`)
      .then((r) => {
        if (!r.ok) { setNotFound(true); return null }
        return r.json()
      })
      .then((d) => { if (d?.job) setJob(d.job) })
      .finally(() => setLoading(false))
  }, [params.id])

  if (loading) return (
    <div className="max-w-4xl mx-auto px-4 py-20 flex justify-center"><Spinner size="lg" /></div>
  )

  if (notFound || !job) return (
    <div className="max-w-4xl mx-auto px-4 py-20 text-center">
      <h1 className="text-2xl font-bold text-neutral-800 mb-2">Job not found</h1>
      <p className="text-neutral-500 mb-6">This listing may have been removed or is not publicly visible.</p>
      <Link href="/jobs"><Button variant="secondary">← Back to Jobs</Button></Link>
    </div>
  )

  const isOwner = session?.user?.id === job.employerId
  const isAdmin = session?.user?.role === 'ADMIN'

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
      <Link href="/jobs" className="text-sm text-brand-600 hover:underline flex items-center gap-1 mb-6">
        ← Back to Jobs
      </Link>

      <div className="card p-8">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-start gap-4 mb-6">
          <div className="flex-1">
            <div className="flex flex-wrap items-center gap-2 mb-2">
              <h1 className="text-2xl font-bold text-neutral-900" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
                {job.title}
              </h1>
              <Badge variant={jobTypeBadgeVariant(job.jobType)}>{formatJobType(job.jobType)}</Badge>
              {job.isExternal && <Badge variant="yellow">External Listing</Badge>}
              {isAdmin && <Badge variant={statusBadgeVariant(job.status)}>{job.status}</Badge>}
            </div>
            <p className="text-lg text-neutral-700 font-medium">{job.companyName}</p>
            <div className="flex flex-wrap items-center gap-4 mt-3 text-sm text-neutral-500">
              <span className="flex items-center gap-1">
                <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                {job.location}
              </span>
              {job.salaryRange && (
                <span className="flex items-center gap-1 text-emerald-600 font-medium">
                  {job.salaryRange}
                </span>
              )}
              {job.source && (
                <span className="bg-[#063B25] text-white px-2 py-0.5 rounded text-[10px]">
                  Source: {job.source}
                </span>
              )}
              <span>Posted {new Date(job.createdAt).toLocaleDateString()}</span>
            </div>
          </div>

          {(isOwner || isAdmin) && (
            <div className="flex gap-2 shrink-0">
              <Link href={`/jobs/${job.id}/edit`}>
                <Button variant="secondary" size="sm">Edit</Button>
              </Link>
            </div>
          )}
        </div>

        <hr className="border-neutral-200 my-6" />

        {/* Description */}
        <div className="mb-6">
          <h2 className="text-lg font-bold text-neutral-900 mb-3" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
            About this role
          </h2>
          <p className="text-neutral-700 leading-relaxed whitespace-pre-line">{job.description}</p>
        </div>

        {/* Requirements */}
        {job.requirements && (
          <div className="mb-6">
            <h2 className="text-lg font-bold text-neutral-900 mb-3" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
              Requirements
            </h2>
            <p className="text-neutral-700 leading-relaxed whitespace-pre-line">{job.requirements}</p>
          </div>
        )}

        <hr className="border-neutral-200 my-6" />

        {/* Apply */}
        <div className="flex flex-wrap items-center gap-4">
          {job.isExternal ? (
            <a href={job.applyUrl} target="_blank" rel="noopener noreferrer">
              <Button size="lg" className="bg-[#FF7628] hover:bg-[#e55a13] text-white font-bold">
                Apply on original site
              </Button>
            </a>
          ) : (
            job.employer?.email && (
              <a href={`mailto:${job.employer.email}?subject=Application for ${encodeURIComponent(job.title)} at ${encodeURIComponent(job.companyName)}`}>
                <Button size="lg">Apply via Email</Button>
              </a>
            )
          )}
          {!job.isExternal && (
            <div className="text-sm text-neutral-500">
              Posted by {job.employer?.name} {job.employer?.surname}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
