// src/app/(dashboard)/jobs/create/page.tsx
'use client'

import { useState } from 'react'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Textarea } from '@/components/ui/Textarea'
import { Select } from '@/components/ui/Select'

const JOB_TYPES = [
  { value: 'FULL_TIME', label: 'Full-time' },
  { value: 'PART_TIME', label: 'Part-time' },
  { value: 'CONTRACT', label: 'Contract' },
  { value: 'FREELANCE', label: 'Freelance' },
  { value: 'INTERNSHIP', label: 'Internship' },
]

export default function CreateJobPage() {
  const { data: session } = useSession()
  const router = useRouter()
  const [form, setForm] = useState({
    title: '',
    companyName: '',
    location: '',
    jobType: 'FULL_TIME',
    salaryRange: '',
    description: '',
    requirements: '',
    status: 'pending',
  })
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [loading, setLoading] = useState(false)
  const [globalError, setGlobalError] = useState('')

  function update(field: string, value: string) {
    setForm((f) => ({ ...f, [field]: value }))
    setErrors((e) => ({ ...e, [field]: '' }))
  }

  if (!session || !['EMPLOYER', 'ADMIN'].includes(session.user.role)) {
    return (
      <div className="page-header">
        <h1 className="page-title">Access Denied</h1>
        <p className="page-subtitle">Only employers can post jobs.</p>
      </div>
    )
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setGlobalError('')
    setLoading(true)

    try {
      const res = await fetch('/api/jobs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      })
      const data = await res.json()

      if (!res.ok) {
        if (data.issues) {
          const fieldErrors: Record<string, string> = {}
          for (const [field, msgs] of Object.entries(data.issues as Record<string, string[]>)) {
            fieldErrors[field] = msgs[0] ?? 'Invalid'
          }
          setErrors(fieldErrors)
        } else {
          setGlobalError(data.error ?? 'Failed to create job')
        }
        return
      }

      router.push('/jobs/' + data.job.id)
    } catch {
      setGlobalError('Something went wrong.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="max-w-2xl">
      <div className="page-header">
        <h1 className="page-title">Post a Job</h1>
        <p className="page-subtitle">Fill in the details for your job listing. It will be reviewed before going live.</p>
      </div>

      <form onSubmit={handleSubmit} className="card p-6 space-y-5">
        {globalError && (
          <div className="p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700">{globalError}</div>
        )}

        <Input label="Job title" id="job-title" value={form.title} onChange={(e) => update('title', e.target.value)} placeholder="e.g. Senior Frontend Developer" error={errors.title} required />
        <Input label="Company name" id="job-company" value={form.companyName} onChange={(e) => update('companyName', e.target.value)} placeholder="e.g. TechCo Solutions" error={errors.companyName} required />
        <div className="grid sm:grid-cols-2 gap-4">
          <Input label="Location" id="job-location" value={form.location} onChange={(e) => update('location', e.target.value)} placeholder="e.g. Cape Town, ZA or Remote" error={errors.location} required />
          <Select label="Job type" id="job-type" value={form.jobType} onChange={(e) => update('jobType', e.target.value)} options={JOB_TYPES} />
        </div>
        <Input label="Salary range (optional)" id="job-salary" value={form.salaryRange} onChange={(e) => update('salaryRange', e.target.value)} placeholder="e.g. R25,000 – R35,000 / month" />
        <Textarea label="Job description" id="job-description" value={form.description} onChange={(e) => update('description', e.target.value)} placeholder="Describe the role, responsibilities, and what success looks like..." className="min-h-[160px]" error={errors.description} required />
        <Textarea label="Requirements (optional)" id="job-requirements" value={form.requirements} onChange={(e) => update('requirements', e.target.value)} placeholder="List required skills, qualifications, and experience..." className="min-h-[120px]" />
        <Select
          label="Save as"
          id="job-status"
          value={form.status}
          onChange={(e) => update('status', e.target.value)}
          options={[
            { value: 'draft', label: 'Draft (not visible)' },
            { value: 'pending', label: 'Submit for review' },
          ]}
        />

        <div className="flex gap-3 pt-2">
          <Button type="submit" loading={loading} size="lg">Post Job</Button>
          <Button type="button" variant="secondary" size="lg" onClick={() => router.back()}>Cancel</Button>
        </div>
      </form>
    </div>
  )
}
